diff options
452 files changed, 4873 insertions, 4873 deletions
diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java index 559e3c51..5670ac95 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/Batch.java @@ -98,11 +98,11 @@ public abstract class Batch { // load extra properties, i.e. // PERF.cassandra.clusters=.... batchEnv = env.getProperty(CASS_ENV); - if(batchEnv != null) { + if (batchEnv != null) { batchEnv = batchEnv.trim(); env.info().log("Redirecting to ",batchEnv,"environment"); String str; - for(String key : new String[]{ + for (String key : new String[]{ CassAccess.CASSANDRA_CLUSTERS, CassAccess.CASSANDRA_CLUSTERS_PORT, CassAccess.CASSANDRA_CLUSTERS_USER_NAME, @@ -111,7 +111,7 @@ public abstract class Batch { LOG_DIR, "SPECIAL_NAMES" }) { - if((str = env.getProperty(batchEnv+'.'+key))!=null) { + if ((str = env.getProperty(batchEnv+'.'+key))!=null) { env.setProperty(key, str); } } @@ -319,8 +319,8 @@ public abstract class Batch { private static void transferVMProps(AuthzEnv env, String ... props) { String value; - for(String key : props) { - if((value = System.getProperty(key))!=null) { + for (String key : props) { + if ((value = System.getProperty(key))!=null) { env.setProperty(key, value); } } @@ -357,8 +357,8 @@ public abstract class Batch { protected static String logDir() { String ld = env.getProperty(LOG_DIR); - if(ld==null) { - if(batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir + if (ld==null) { + if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir ld = "logs/"; } else { ld = "logs/"+batchEnv; @@ -367,11 +367,11 @@ public abstract class Batch { return ld; } protected int count(String str, char c) { - if(str==null || str.isEmpty()) { + if (str==null || str.isEmpty()) { return 0; } else { int count=1; - for(int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) { + for (int i=str.indexOf(c);i>=0;i=str.indexOf(c,i+1)) { ++count; } return count; diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java index cb2b158f..e80eada1 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/CassBatch.java @@ -59,14 +59,14 @@ public abstract class CassBatch extends Batch { } public ResultSet executeQuery(String cql, String extra) { - if(isDryRun() && !cql.startsWith("SELECT")) { - if(extra!=null)env.info().log("Would query" + extra + ": " + cql); + if (isDryRun() && !cql.startsWith("SELECT")) { + if (extra!=null)env.info().log("Would query" + extra + ": " + cql); } else { - if(extra!=null)env.info().log("query" + extra + ": " + cql); + if (extra!=null)env.info().log("query" + extra + ": " + cql); try { return session.execute(cql); } catch (InvalidQueryException e) { - if(extra==null) { + if (extra==null) { env.info().log("query: " + cql); } throw e; diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java index af636d65..5275cf93 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionDAO.java @@ -65,7 +65,7 @@ public abstract class ActionDAO<D,RV,T> implements Action<D,RV,T> { } public void close(AuthzTrans trans) { - if(clean) { + if (clean) { q.close(trans); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java index 95b35fdb..707425ca 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/ActionPuntDAO.java @@ -58,9 +58,9 @@ public abstract class ActionPuntDAO<D, RV, T> extends ActionDAO<D, RV, T> { * This method Randomized date. This is no longer needed. Just add the Punt Months. temp.setTime(now); temp.add(GregorianCalendar.MONTH, months); - if(range>0) { + if (range>0) { int forward = Math.abs(random.nextInt()%range); - if(forward>1) { + if (forward>1) { temp.add(GregorianCalendar.MONTH, forward); temp.add(GregorianCalendar.DAY_OF_MONTH, (random.nextInt()%30)-15); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java index e0fa4be5..269edc77 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CacheTouch.java @@ -41,7 +41,7 @@ public class CacheTouch extends ActionDAO<String,Void, String> { @Override public Result<Void> exec(AuthzTrans trans, String table, String text) { - if(dryRun) { + if (dryRun) { trans.info().printf("Would mark %s cache in DB for clearing: %s",table, text); return Result.ok(); } else { diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java index b4b7d0b3..ceb0453b 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredDelete.java @@ -43,7 +43,7 @@ public class CredDelete extends ActionDAO<CredDAO.Data,Void, String> { @Override public Result<Void> exec(AuthzTrans trans, CredDAO.Data cred, String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Delete:",text,cred.id,CredPrint.type(cred.type),Chrono.dateOnlyStamp(cred.expires)); return Result.ok(); } else { diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java index a2c9ecf6..33151d9f 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/CredPunt.java @@ -46,14 +46,14 @@ public class CredPunt extends ActionPuntDAO<CredDAO.Data,Void,String> { public Result<Void> exec(AuthzTrans trans, CredDAO.Data cdd,String text) { Result<Void> rv = null; Result<List<CredDAO.Data>> read = q.credDAO.read(trans, cdd); - if(read.isOKhasData()) { - for(CredDAO.Data data : read.value) { + if (read.isOKhasData()) { + for (CredDAO.Data data : read.value) { Date from = data.expires; data.expires = puntDate(from); - if(data.expires.compareTo(from)<=0) { + if (data.expires.compareTo(from)<=0) { trans.debug().printf("Error: %s is before %s", Chrono.dateOnlyStamp(data.expires), Chrono.dateOnlyStamp(from)); } else { - if(dryRun) { + if (dryRun) { trans.info().log("Would Update Cred",cdd.id, CredPrint.type(cdd.type), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires)); } else { trans.info().log("Updated Cred",cdd.id, CredPrint.type(cdd.type), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires)); @@ -62,7 +62,7 @@ public class CredPunt extends ActionPuntDAO<CredDAO.Data,Void,String> { } } } - if(rv==null) { + if (rv==null) { rv=Result.err(read); } return rv; diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java index 0ac8f61d..f40eeb58 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Email.java @@ -55,7 +55,7 @@ public class Email implements Action<Organization,Void, String>{ public Email clear() { toList.clear(); ccList.clear(); - for(String s: defaultCC) { + for (String s: defaultCC) { ccList.add(s); } return this; @@ -71,35 +71,35 @@ public class Email implements Action<Organization,Void, String>{ } public Email addTo(Identity id) { - if(id!=null && !toList.contains(id.email())) { + if (id!=null && !toList.contains(id.email())) { toList.add(id.email()); } return this; } public Email addTo(Collection<String> users) { - for(String u : users) { + for (String u : users) { addTo(u); } return this; } public Email addTo(String email) { - if(!toList.contains(email)) { + if (!toList.contains(email)) { toList.add(email); } return this; } public Email addCC(Identity id) { - if(id!=null && !ccList.contains(id.email())) { + if (id!=null && !ccList.contains(id.email())) { ccList.add(id.email()); } return this; } public Email addCC(String email) { - if(!ccList.contains(email)) { + if (!ccList.contains(email)) { ccList.add(email); } return this; @@ -108,7 +108,7 @@ public class Email implements Action<Organization,Void, String>{ public Email add(Identity id, boolean toSuper) throws OrganizationException { Identity responsible = id.responsibleTo(); - if(toSuper) { + if (toSuper) { addTo(responsible.email()); addCC(id.email()); } else { @@ -119,7 +119,7 @@ public class Email implements Action<Organization,Void, String>{ } public Email subject(String format, Object ... args) { - if(format.contains("%s")) { + if (format.contains("%s")) { subject = String.format(format, args); } else { subject = format; @@ -140,18 +140,18 @@ public class Email implements Action<Organization,Void, String>{ @Override public Result<Void> exec(AuthzTrans trans, Organization org, String text) { StringBuilder sb = new StringBuilder(); - if(preamble!=null) { + if (preamble!=null) { sb.append(lineIndent); sb.append(preamble); sb.append("\n\n"); } - if(msg!=null) { + if (msg!=null) { msg.msg(sb,lineIndent); sb.append("\n"); } - if(sig!=null) { + if (sig!=null) { sb.append(sig); sb.append("\n"); } @@ -159,7 +159,7 @@ public class Email implements Action<Organization,Void, String>{ long ct = System.currentTimeMillis(); long wait = ct-lastSent; lastSent = ct; - if(wait < 100) { // 10 per second + if (wait < 100) { // 10 per second try { Thread.sleep(wait); } catch (InterruptedException e) { @@ -188,8 +188,8 @@ public class Email implements Action<Organization,Void, String>{ public void log(PrintStream ps, String text) { ps.print(Chrono.dateTime()); boolean first = true; - for(String s : toList) { - if(first) { + for (String s : toList) { + if (first) { first = false; ps.print(": "); } else { @@ -197,10 +197,10 @@ public class Email implements Action<Organization,Void, String>{ } ps.print(s); } - if(!ccList.isEmpty()) { + if (!ccList.isEmpty()) { first=true; - for(String s : ccList) { - if(first) { + for (String s : ccList) { + if (first) { first = false; ps.print(" ["); } else { diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java index 5fdc15b1..141e382f 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/EmailPrint.java @@ -43,8 +43,8 @@ public class EmailPrint extends Email { PrintStream out = System.out; boolean first = true; out.print("To: "); - for(String s: toList) { - if(first) {first = false;} + for (String s: toList) { + if (first) {first = false;} else {out.print(',');} out.print(s); } @@ -52,8 +52,8 @@ public class EmailPrint extends Email { first = true; out.print("CC: "); - for(String s: ccList) { - if(first) {first = false;} + for (String s: ccList) { + if (first) {first = false;} else {out.print(',');} out.print(s); } @@ -64,7 +64,7 @@ public class EmailPrint extends Email { out.println(); boolean go = true; - for(int start=0, end=LINE_LENGTH;go;start=end,end=Math.min(msg.length(), start+LINE_LENGTH)) { + for (int start=0, end=LINE_LENGTH;go;start=end,end=Math.min(msg.length(), start+LINE_LENGTH)) { int ret = msg.indexOf("\n",start+1); switch(ret) { case -1: @@ -75,13 +75,13 @@ public class EmailPrint extends Email { out.println(); break; default: - if(ret<end) { + if (ret<end) { end = ret; } - if(end==start+LINE_LENGTH) { + if (end==start+LINE_LENGTH) { // Word-wrapping ret = msg.lastIndexOf(" ", end); - if(ret>start && ret<end) { + if (ret>start && ret<end) { end=ret+1; } out.println(msg.substring(start,end)); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java index ac594a47..f1eadb20 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/Message.java @@ -42,8 +42,8 @@ public class Message { } public void msg(StringBuilder sb, String lineIndent) { - if(!lines.isEmpty()) { - for(String line : lines) { + if (!lines.isEmpty()) { + for (String line : lines) { sb.append(lineIndent); sb.append(line); sb.append('\n'); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java index 5e531269..58a8c4b8 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSACreate.java @@ -41,12 +41,12 @@ public class NSACreate extends ActionDAO<NsAttrib,Void,String> { @Override public Result<Void> exec(AuthzTrans trans, NsAttrib nsa, String text) { - if(dryRun) { + if (dryRun) { trans.info().printf("Would Create %s Attrib '%s=%s' in %s",text,nsa.key,nsa.value,nsa.ns); return Result.ok(); } else { Result<Void> rv = q.nsDAO.dao().attribAdd(trans, nsa.ns, nsa.key, nsa.value); - if(rv.isOK()) { + if (rv.isOK()) { trans.info().printf("%s - Created Attrib '%s=%s' in %s",text,nsa.key,nsa.value,nsa.ns); } else { trans.error().printf("Error Creating Attrib '%s=%s' in %s - %s",nsa.key,nsa.value,nsa.ns,rv.details); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java index 4bed8687..c8a1c82c 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSADelete.java @@ -41,12 +41,12 @@ public class NSADelete extends ActionDAO<NsAttrib,Void,String> { @Override public Result<Void> exec(AuthzTrans trans, NsAttrib nsa, String text) { - if(dryRun) { + if (dryRun) { trans.info().printf("Would Delete %s Attrib '%s' in %s",text,nsa.key,nsa.ns); return Result.ok(); } else { Result<Void> rv = q.nsDAO.dao().attribRemove(trans, nsa.ns, nsa.key); - if(rv.isOK()) { + if (rv.isOK()) { trans.info().printf("%s - Deleted Attrib '%s' in %s",text,nsa.key,nsa.value,nsa.ns); } else { trans.error().printf("Error Deleting Attrib '%s' in %s - %s",nsa.key,nsa.value,nsa.ns,rv.details); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java index 98fad0ab..d5d93b38 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/NSDescUpdate.java @@ -41,12 +41,12 @@ public class NSDescUpdate extends ActionDAO<NS,Void,String> { @Override public Result<Void> exec(AuthzTrans trans, NS ns, String desc) { - if(dryRun) { + if (dryRun) { trans.info().printf("Would Update '%s' Description to '%s'",ns,desc); return Result.ok(); } else { Result<Void> rv = q.nsDAO.dao().addDescription(trans, ns.name, desc); - if(rv.isOK()) { + if (rv.isOK()) { trans.info().printf("Updated '%s' Description to '%s'",ns,desc); } else { trans.error().printf("Error Updating '%s' Description to '%s' - %s",ns,desc,rv.details); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java index c32234d7..a6c02f2c 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermCreate.java @@ -52,12 +52,12 @@ public class PermCreate extends ActionDAO<Perm,Data,String> { pdd.description = p.description; pdd.roles = p.roles; - if(dryRun) { + if (dryRun) { trans.info().log("Would Create Perm:",text,p.fullType()); return Result.ok(pdd); } else { Result<Data> rv = q.permDAO.create(trans, pdd); // need to read for undelete - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log("Created Perm:",text,p.fullType()); } else { trans.error().log("Error Creating Role -",rv.details,":",p.fullType()); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java index c5b79185..db549948 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermDelete.java @@ -47,12 +47,12 @@ public class PermDelete extends ActionDAO<Perm,Void,String> { pdd.type = p.type; pdd.instance = p.instance; pdd.action = p.action; - if(dryRun) { + if (dryRun) { trans.info().log("Would Delete Perm:",text,p.fullType()); return Result.ok(); } else { Result<Void> rv = q.permDAO.delete(trans, pdd, true); // need to read for undelete - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log("Deleted Perm:",text,p.fullType()); } else { trans.error().log("Error Deleting Perm -",rv.details,":",p.fullType()); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java index bc6f70ca..a3d4bb6d 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/PermModify.java @@ -48,35 +48,35 @@ public class PermModify extends ActionDAO<Perm,PermDAO.Data,PermModify.Modify> { @Override public Result<PermDAO.Data> exec(AuthzTrans trans, final Perm p, final Modify modify) { Result<List<PermDAO.Data>> rr = q.permDAO.read(trans, p.ns,p.type,p.instance,p.action); - if(dryRun) { - if(rr.isOKhasData()) { + if (dryRun) { + if (rr.isOKhasData()) { return Result.ok(rr.value.get(0)); } else { return Result.err(Result.ERR_NotFound, "Data not Found " + p.toString()); } } else { Result<PermDAO.Data> rv = null; - if(rr.isOKhasData()) { - for(final Data d : rr.value) { + if (rr.isOKhasData()) { + for (final Data d : rr.value) { modify.change(d); - if(d.ns.equals(p.ns) && d.type.equals(p.type) && d.instance.equals(p.instance) && d.action.equals(p.action)) { + if (d.ns.equals(p.ns) && d.type.equals(p.type) && d.instance.equals(p.instance) && d.action.equals(p.action)) { // update for fields // In either case, adjust Permissions - for(String r : d.roles) { - if(!p.roles.contains(r)) { + for (String r : d.roles) { + if (!p.roles.contains(r)) { q.permDAO.dao().addRole(trans, d, r); } } - for(String r : p.roles) { - if(!d.roles.contains(r)) { + for (String r : p.roles) { + if (!d.roles.contains(r)) { q.permDAO.dao().delRole(trans, d, r); } } rv = Result.ok(d); } else { - for(String r : d.roles) { + for (String r : d.roles) { Role role = Role.keys.get(r); - if(role.perms.contains(p.encode())) { + if (role.perms.contains(p.encode())) { modify.roleModify().exec(trans, role, new RoleModify.Modify() { @Override public PermModify permModify() { @@ -93,7 +93,7 @@ public class PermModify extends ActionDAO<Perm,PermDAO.Data,PermModify.Modify> { } rv = q.permDAO.create(trans, d); - if(rv.isOK()) { + if (rv.isOK()) { PermDAO.Data pdd = new PermDAO.Data(); pdd.ns = p.ns; pdd.type = p.type; @@ -112,7 +112,7 @@ public class PermModify extends ActionDAO<Perm,PermDAO.Data,PermModify.Modify> { } else { rv = Result.err(rr); } - if(rv==null) { + if (rv==null) { rv = Result.err(Status.ERR_General,"Never get to this code"); } @@ -126,7 +126,7 @@ public class PermModify extends ActionDAO<Perm,PermDAO.Data,PermModify.Modify> { } public Result<Void> delete(AuthzTrans trans, Perm p) { - if(dryRun) { + if (dryRun) { return Result.ok(); } else { PermDAO.Data data = new PermDAO.Data(); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java index 5353166c..cdbe92b4 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleCreate.java @@ -49,12 +49,12 @@ public class RoleCreate extends ActionDAO<Role,Data,String> { rdd.description = r.description; rdd.perms = r.perms; - if(dryRun) { + if (dryRun) { trans.info().log("Would Create Role:",text,r.fullName()); return Result.ok(rdd); } else { Result<Data> rv = q.roleDAO.create(trans, rdd); // need to read for undelete - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log("Created Role:",text,r.fullName()); } else { trans.error().log("Error Creating Role -",rv.details,":",r.fullName()); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java index 1a663c99..67491b5b 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleDelete.java @@ -42,7 +42,7 @@ public class RoleDelete extends ActionDAO<Role,Void,String> { @Override public Result<Void> exec(AuthzTrans trans, Role r,String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Delete Role:",text,r.fullName()); return Result.ok(); } else { @@ -50,7 +50,7 @@ public class RoleDelete extends ActionDAO<Role,Void,String> { rdd.ns = r.ns; rdd.name = r.name; Result<Void> rv = q.roleDAO.delete(trans, rdd, true); // need to read for undelete - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log("Deleted Role:",text,r.fullName()); } else { trans.error().log("Error Deleting Role -",rv.details,":",r.fullName()); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java index 87e2e027..75937ef7 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/RoleModify.java @@ -48,42 +48,42 @@ public class RoleModify extends ActionDAO<Role,RoleDAO.Data,RoleModify.Modify> { @Override public Result<RoleDAO.Data> exec(final AuthzTrans trans, final Role r,final RoleModify.Modify modify) { Result<List<Data>> rr = q.roleDAO.read(trans, r.ns,r.name); - if(dryRun) { - if(rr.isOKhasData()) { + if (dryRun) { + if (rr.isOKhasData()) { return Result.ok(rr.value.get(0)); } else { return Result.err(Result.ERR_NotFound, "Data not Found " + r.toString()); } } else { Result<Data> rv = null; - if(rr.isOKhasData()) { - for(final Data d : rr.value) { + if (rr.isOKhasData()) { + for (final Data d : rr.value) { modify.change(d); - if(d.ns.equals(r.ns) && d.name.equals(r.name)) { + if (d.ns.equals(r.ns) && d.name.equals(r.name)) { // update for fields // In either case, adjust Roles - for(String p : d.perms) { - if(!r.perms.contains(p)) { + for (String p : d.perms) { + if (!r.perms.contains(p)) { Result<PermDAO.Data> rpdd = PermDAO.Data.decode(trans, q, p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { q.roleDAO.dao().addPerm(trans, d, rpdd.value); } } } - for(String p : r.perms) { - if(!d.perms.contains(p)) { + for (String p : r.perms) { + if (!d.perms.contains(p)) { Result<PermDAO.Data> rpdd = PermDAO.Data.decode(trans, q, p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { q.roleDAO.dao().delPerm(trans, d, rpdd.value); } } } rv = Result.ok(d); } else { - for(String p : d.perms) { + for (String p : d.perms) { Perm perm = Perm.keys.get(p); - if(perm!=null) { - if(perm.roles.contains(r.encode())) { + if (perm!=null) { + if (perm.roles.contains(r.encode())) { modify.permModify().exec(trans, perm, new PermModify.Modify() { @Override public RoleModify roleModify() { @@ -100,11 +100,11 @@ public class RoleModify extends ActionDAO<Role,RoleDAO.Data,RoleModify.Modify> { } } Result<List<Data>> preexist = q.roleDAO.read(trans, d); - if(preexist.isOKhasData()) { + if (preexist.isOKhasData()) { Data rdd = preexist.value.get(0); - for(String p : d.perms) { + for (String p : d.perms) { Result<PermDAO.Data> perm = PermDAO.Data.decode(trans, q, p); - if(perm.isOKhasData()) { + if (perm.isOKhasData()) { q.roleDAO.dao().addPerm(trans,rdd, perm.value); } } @@ -112,7 +112,7 @@ public class RoleModify extends ActionDAO<Role,RoleDAO.Data,RoleModify.Modify> { } else { rv = q.roleDAO.create(trans, d); } - if(rv.isOK()) { + if (rv.isOK()) { trans.info().printf("Updating %s|%s to %s|%s", r.ns, r.name, d.ns, d.name); RoleDAO.Data rmme = new RoleDAO.Data(); rmme.ns=r.ns; @@ -127,7 +127,7 @@ public class RoleModify extends ActionDAO<Role,RoleDAO.Data,RoleModify.Modify> { } else { rv = Result.err(rr); } - if(rv==null) { + if (rv==null) { rv = Result.err(Status.ERR_General,"Never get to this code"); } return rv; @@ -140,7 +140,7 @@ public class RoleModify extends ActionDAO<Role,RoleDAO.Data,RoleModify.Modify> { } public Result<Void> delete(AuthzTrans trans, Role r) { - if(dryRun) { + if (dryRun) { return Result.ok(); } else { RoleDAO.Data data = new RoleDAO.Data(); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java index b6baea6c..4538c56b 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URAdd.java @@ -44,7 +44,7 @@ public class URAdd extends ActionDAO<UserRole,UserRoleDAO.Data,String> { @Override public Result<Data> exec(AuthzTrans trans, UserRole ur, String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Add:",text,ur.role(),ur.user(),"on",Chrono.dateOnlyStamp(ur.expires())); return Result.ok(ur.urdd()); } else { diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java index d54b7805..cf519f6f 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URDelete.java @@ -42,12 +42,12 @@ public class URDelete extends ActionDAO<UserRole,Void,String> { @Override public Result<Void> exec(AuthzTrans trans, UserRole ur,String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Delete UserRole:",text,ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); return Result.ok(); } else { Result<Void> rv = q.userRoleDAO.delete(trans,ur.urdd(), true); // need to read for undelete - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log("Deleted UserRole:",text,ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires())); } else { trans.error().log("Error Deleting User Role -",rv.details,":",ur.user(),ur.role(),"on",Chrono.dateOnlyStamp(ur.expires()) ); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java index 8590714f..36b476e1 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApprove.java @@ -59,11 +59,11 @@ public class URFutureApprove extends ActionDAO<UserRole, String,String> implemen @Override public Result<String> exec(AuthzTrans trans, UserRole ur,String text) { - if(dryRun) { + if (dryRun) { return Result.ok(text); } else { Result<NsDAO.Data> rns = q.deriveNs(trans, ur.ns()); - if(rns.isOK()) { + if (rns.isOK()) { FutureDAO.Data data = new FutureDAO.Data(); data.id=null; // let Create function assign UUID @@ -78,7 +78,7 @@ public class URFutureApprove extends ActionDAO<UserRole, String,String> implemen return Result.err(e); } Result<String> rfuture = f.createFuture(trans, data, Function.FOP_USER_ROLE, ur.user(), rns.value, FUTURE_OP.A); - if(rfuture.isOK()) { + if (rfuture.isOK()) { trans.info().log(rfuture.value, text, ur.user(), data.memo); } else { trans.error().log(rfuture.details, text); @@ -93,15 +93,15 @@ public class URFutureApprove extends ActionDAO<UserRole, String,String> implemen @Override public String key(UserRole ur) { String expire; - if(expires.before(start)) { + if (expires.before(start)) { expire = "' - EXPIRED "; } else { expire = "' - expiring "; } - if(Question.OWNER.equals(ur.rname())) { + if (Question.OWNER.equals(ur.rname())) { return Approval.RE_VALIDATE_OWNER + ur.ns() + expire + Chrono.dateOnlyStamp(ur.expires()); - } else if(Question.ADMIN.equals(ur.rname())) { + } else if (Question.ADMIN.equals(ur.rname())) { return Approval.RE_VALIDATE_ADMIN + ur.ns() + expire + Chrono.dateOnlyStamp(ur.expires()); } else { return Approval.RE_APPROVAL_IN_ROLE + ur.role() + expire + Chrono.dateOnlyStamp(ur.expires()); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java index fcba2364..75bbd813 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URFutureApproveExec.java @@ -52,16 +52,16 @@ public class URFutureApproveExec extends ActionDAO<List<Approval>, OP_STATUS, Fu @Override public Result<OP_STATUS> exec(AuthzTrans trans, List<Approval> app, Future future) { - if(dryRun) { + if (dryRun) { return Result.err(Result.ERR_ActionNotCompleted,"Not Executed"); } else { // Save on Lookups final List<ApprovalDAO.Data> apprs = new ArrayList<>(); final List<UserRoleDAO.Data> urs = new ArrayList<>(); - for(Approval a : app) { + for (Approval a : app) { apprs.add(a.add); UserRole ur = UserRole.get(a.add.user, future.role); - if(ur!=null) { + if (ur!=null) { urs.add(ur.urdd()); } } @@ -76,9 +76,9 @@ public class URFutureApproveExec extends ActionDAO<List<Approval>, OP_STATUS, Fu @Override public UserRoleDAO.Data get(AuthzTrans trans, Object ... keys) { List<UserRole> lur = UserRole.getByUser().get(keys[0]); - if(lur!=null) { - for(UserRole ur : lur) { - if(ur.role().equals(keys[1])) { + if (lur!=null) { + for (UserRole ur : lur) { + if (ur.role().equals(keys[1])) { return ur.urdd(); } } @@ -86,7 +86,7 @@ public class URFutureApproveExec extends ActionDAO<List<Approval>, OP_STATUS, Fu return null; } }); - if(rv.isOK()) { + if (rv.isOK()) { switch(rv.value) { case D: trans.info().printf("Denied %s on %s", future.memo(),future.fdd.target); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java index a7d420e3..12460c97 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URModify.java @@ -45,22 +45,22 @@ public class URModify extends ActionDAO<UserRole,Void,URModify.Modify> { @Override public Result<Void> exec(AuthzTrans trans, UserRole ur,Modify modify) { - if(dryRun) { + if (dryRun) { trans.info().printf("Would Update %s %s", ur.user(), ur.role()); return Result.ok(); } else { Result<List<Data>> rr = q.userRoleDAO.read(trans, ur.user(),ur.role()); - if(rr.notOKorIsEmpty()) { + if (rr.notOKorIsEmpty()) { return Result.err(rr); } - for(Data d : rr.value) { + for (Data d : rr.value) { modify.change(d); - if(!(ur.expires().equals(d.expires))) { + if (!(ur.expires().equals(d.expires))) { ur.expires(d.expires); } - if(ur.user().equals(d.user) && ur.role().equals(d.role)){ + if (ur.user().equals(d.user) && ur.role().equals(d.role)){ Result<Void> rv = q.userRoleDAO.update(trans, d); - if(rv.isOK()) { + if (rv.isOK()) { trans.info().printf("Updated %s %s to %s", ur.user(), ur.role(), d.toString()); } else { trans.info().log(rv.errorString()); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java index 856c89dc..6371ebb5 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/actions/URPunt.java @@ -45,16 +45,16 @@ public class URPunt extends ActionPuntDAO<UserRole,Void,String> { } public Result<Void> exec(AuthzTrans trans, UserRole ur, String text) { - if(dryRun) { + if (dryRun) { trans.info().log("Would Update User",ur.user(),"and Role", ur.role(), text); return Result.ok(); } else { Result<List<Data>> read = q.userRoleDAO.read(trans, ur.user(), ur.role()); - if(read.isOK()) { - for(UserRoleDAO.Data data : read.value) { + if (read.isOK()) { + for (UserRoleDAO.Data data : read.value) { Date from = data.expires; data.expires = puntDate(from); - if(data.expires.compareTo(from)<=0) { + if (data.expires.compareTo(from)<=0) { trans.debug().printf("Error: %s is same or before %s", Chrono.dateOnlyStamp(data.expires), Chrono.dateOnlyStamp(from)); } else { trans.info().log("Updating User",ur.user(),"and Role", ur.role(), "from",Chrono.dateOnlyStamp(from),"to",Chrono.dateOnlyStamp(data.expires), text); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java index 94c709b3..a4c4efbc 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Approval.java @@ -70,19 +70,19 @@ public class Approval implements CacheChange.Data { } public static String roleFromMemo(String memo) { - if(memo==null) { + if (memo==null) { return null; } int first = memo.indexOf('\''); - if(first>=0) { + if (first>=0) { int second = memo.indexOf('\'', ++first); - if(second>=0) { + if (second>=0) { String role = memo.substring(first, second); - if(memo.startsWith(RE_VALIDATE_ADMIN)) { + if (memo.startsWith(RE_VALIDATE_ADMIN)) { return role + ".admin"; - } else if(memo.startsWith(RE_VALIDATE_OWNER)) { + } else if (memo.startsWith(RE_VALIDATE_OWNER)) { return role + ".owner"; - } else if(memo.startsWith(RE_APPROVAL_IN_ROLE)) { + } else if (memo.startsWith(RE_APPROVAL_IN_ROLE)) { return role; } } @@ -106,14 +106,14 @@ public class Approval implements CacheChange.Data { try { List<Approval> ln; - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; try { Approval app = creator.create(row); String person = app.getApprover(); - if(person!=null) { + if (person!=null) { ln = byApprover.get(person); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); byApprover.put(app.getApprover(), ln); } @@ -122,18 +122,18 @@ public class Approval implements CacheChange.Data { person = app.getUser(); - if(person!=null) { + if (person!=null) { ln = byUser.get(person); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); byUser.put(app.getUser(), ln); } ln.add(app); } UUID ticket = app.getTicket(); - if(ticket!=null) { + if (ticket!=null) { ln = byTicket.get(ticket); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); byTicket.put(app.getTicket(), ln); } @@ -152,25 +152,25 @@ public class Approval implements CacheChange.Data { @Override public void expunge() { List<Approval> la = byApprover.get(getApprover()); - if(la!=null) { + if (la!=null) { la.remove(this); } la = byUser.get(getUser()); - if(la!=null) { + if (la!=null) { la.remove(this); } UUID ticket = this.add==null?null:this.add.ticket; - if(ticket!=null) { + if (ticket!=null) { la = byTicket.get(this.add.ticket); - if(la!=null) { + if (la!=null) { la.remove(this); } } } public void update(AuthzTrans trans, ApprovalDAO apprDAO, boolean dryRun) { - if(dryRun) { + if (dryRun) { trans.info().printf("Would update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified); } else { trans.info().printf("Update Approval %s, %s, last_notified %s",add.id,add.status,add.last_notified); @@ -272,11 +272,11 @@ public class Approval implements CacheChange.Data { } public void delayDelete(AuthzTrans trans, ApprovalDAO ad, boolean dryRun, String text) { - if(dryRun) { + if (dryRun) { trans.info().log(text,"- Would Delete: Approval",getId(),"on ticket",getTicket(),"for",getApprover()); } else { Result<Void> rv = ad.delete(trans, add, false); - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log(text,"- Deleted: Approval",getId(),"on ticket",getTicket(),"for",getApprover()); cache.delayedDelete(this); } else { @@ -295,8 +295,8 @@ public class Approval implements CacheChange.Data { } public static void delayDelete(AuthzTrans noAvg, ApprovalDAO apprDAO, boolean dryRun, List<Approval> list, String text) { - if(list!=null) { - for(Approval a : list) { + if (list!=null) { + for (Approval a : list) { a.delayDelete(noAvg, apprDAO, dryRun,text); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java index 1adc3d08..1407bdd0 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/CacheChange.java @@ -44,10 +44,10 @@ public class CacheChange<T extends CacheChange.Data> { } public final void resetLocalData() { - if(removed==null || removed.isEmpty()) { + if (removed==null || removed.isEmpty()) { return; } - for(T t : removed) { + for (T t : removed) { t.expunge(); } removed.clear(); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java index 11580b80..a3eb8363 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Creator.java @@ -29,7 +29,7 @@ public abstract class Creator<T> { public String query(String where) { StringBuilder sb = new StringBuilder(select()); - if(where!=null) { + if (where!=null) { sb.append(" WHERE "); sb.append(where); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java index 4013f193..2f6ed415 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Cred.java @@ -71,20 +71,20 @@ public class Cred { public Date last(final int ... types) { Date last = null; - for(Instance i : instances) { - if(types.length>0) { // filter by types, if requested + for (Instance i : instances) { + if (types.length>0) { // filter by types, if requested boolean quit = true; - for(int t : types) { - if(t==i.type) { + for (int t : types) { + if (t==i.type) { quit=false; break; } } - if(quit) { + if (quit) { continue; } } - if(last==null || i.expires.after(last)) { + if (last==null || i.expires.after(last)) { last = i.expires; } } @@ -94,7 +94,7 @@ public class Cred { public Set<Integer> types() { Set<Integer> types = new HashSet<>(); - for(Instance i : instances) { + for (Instance i : instances) { types.add(i.type); } return types; @@ -129,42 +129,42 @@ public class Cred { String id; tt = trans.start("Load Credentials", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { ++count; row = iter.next(); id = row.getString(0); type = row.getInt(1); - if(types.length>0) { // filter by types, if requested + if (types.length>0) { // filter by types, if requested boolean quit = true; - for(int t : types) { - if(t==type) { + for (int t : types) { + if (t==type) { quit=false; break; } } - if(quit) { + if (quit) { continue; } } Cred cred = data.get(id); - if(cred==null) { + if (cred==null) { cred = new Cred(id); data.put(id, cred); } cred.instances.add(new Instance(type, row.getTimestamp(2), row.getInt(3), row.getLong(4)/1000)); List<Cred> lscd = byNS.get(cred.ns); - if(lscd==null) { + if (lscd==null) { byNS.put(cred.ns, (lscd=new ArrayList<>())); } boolean found = false; - for(Cred c : lscd) { - if(c.id.equals(cred.id)) { + for (Cred c : lscd) { + if (c.id.equals(cred.id)) { found=true; break; } } - if(!found) { + if (!found) { lscd.add(cred); } } @@ -184,7 +184,7 @@ public class Cred { */ public static CredCount count(int numbuckets) { CredCount cc = new CredCount(numbuckets); - for(Cred c : data.values()) { + for (Cred c : data.values()) { for (Instance ci : c.instances) { cc.inc(ci.type,ci.written, ci.expires); } @@ -228,7 +228,7 @@ public class Cred { gc.set(GregorianCalendar.SECOND,0); gc.set(GregorianCalendar.MILLISECOND,0); gc.add(GregorianCalendar.MILLISECOND, -1); // last milli of month - for(int i=1;i<numbuckets;++i) { + for (int i=1;i<numbuckets;++i) { dates[i] = gc.getTime(); gc.add(GregorianCalendar.MONTH, -1); } @@ -236,14 +236,14 @@ public class Cred { } public void inc(int type, Date start, Date expires) { - for(int i=0;i<dates.length-1;++i) { - if(start.before(dates[i])) { - if(type==CredDAO.CERT_SHA256_RSA) { - if(start.after(dates[i+1])) { + for (int i=0;i<dates.length-1;++i) { + if (start.before(dates[i])) { + if (type==CredDAO.CERT_SHA256_RSA) { + if (start.after(dates[i+1])) { ++x509Added[i]; } } - if(expires.after(dates[i])) { + if (expires.after(dates[i])) { switch(type) { case CredDAO.RAW: ++raw[i]; @@ -276,7 +276,7 @@ public class Cred { public String toString() { StringBuilder sb = new StringBuilder(id); sb.append('['); - for(Instance i : instances) { + for (Instance i : instances) { sb.append('{'); sb.append(i.type); sb.append(",\""); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java index 0c618eeb..8a11479e 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Future.java @@ -98,15 +98,15 @@ public class Future implements CacheChange.Data, Comparable<Future> { int count = 0; tt = trans.start("Process Futures", Env.SUB); try { - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; Future f = creator.create(row); data.put(f.fdd.id,f); - if(f.role==null) { + if (f.role==null) { continue; } List<Future> lf = byRole.get(f.role); - if(lf==null) { + if (lf==null) { lf = new ArrayList<>(); byRole.put(f.role,lf); } @@ -148,16 +148,16 @@ public class Future implements CacheChange.Data, Comparable<Future> { public Result<Void> delayedDelete(AuthzTrans trans, FutureDAO fd, boolean dryRun, String text) { Result<Void> rv; - if(dryRun) { + if (dryRun) { trans.info().log(text,"- Would Delete: ",fdd.id,fdd.memo,"expiring on",Chrono.dateOnlyStamp(fdd.expires)); rv = Result.ok(); } else { rv = fd.delete(trans, fdd, true); // need to read for undelete - if(rv.isOK()) { + if (rv.isOK()) { trans.info().log(text, "- Deleted:",fdd.id,fdd.memo,"expiring on",Chrono.dateOnlyStamp(fdd.expires)); cache.delayedDelete(this); } else { - if(rv.status!=6) { + if (rv.status!=6) { trans.info().log(text,"- Failed to Delete Future", fdd.id); } } @@ -171,9 +171,9 @@ public class Future implements CacheChange.Data, Comparable<Future> { @Override public void expunge() { data.remove(fdd.id); - if(role!=null) { + if (role!=null) { List<Future> lf = byRole.get(role); - if(lf!=null) { + if (lf!=null) { lf.remove(this); } } @@ -181,7 +181,7 @@ public class Future implements CacheChange.Data, Comparable<Future> { @Override public int compareTo(Future o) { - if(o==null) { + if (o==null) { return -1; } return fdd.id.compareTo(o.fdd.id); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java index c0841590..cffb55a5 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/History.java @@ -84,7 +84,7 @@ public class History { Row row; tt = trans.start("Load History", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { ++count; row = iter.next(); loader.exec(creator.create(row)); @@ -151,9 +151,9 @@ public class History { ByteBuffer bb = row.getBytes(3); sb.setLength(0); - if(bb!=null && bb.hasRemaining()) { + if (bb!=null && bb.hasRemaining()) { sb.append("0x"); - while(bb.hasRemaining()) { + while (bb.hasRemaining()) { sb.append(String.format("%02x",bb.get())); } bb.flip(); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java index 60b34af9..5fb3e5dc 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/InputIterator.java @@ -58,7 +58,7 @@ public class InputIterator implements Iterable<String> { @Override public String next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return input; diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java index afa68c08..8eecb656 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MiscID.java @@ -64,7 +64,7 @@ public class MiscID { * @throws IllegalArgumentException */ public void set(String row []) throws BatchException { - if(row.length<4) {throw new BatchException("Row of MiscID_XRef is too short");} + if (row.length<4) {throw new BatchException("Row of MiscID_XRef is too short");} id = row[0]; sponsor = row[1]; created = row[2]; @@ -106,7 +106,7 @@ public class MiscID { try { tt = trans.start("Load Map", Env.SUB); try { - for( Row row : results.all()) { + for ( Row row : results.all()) { MiscID miscID = new MiscID(); miscID.set(row); data.put(miscID.id,miscID); @@ -133,7 +133,7 @@ public class MiscID { */ @Override public boolean equals(Object obj) { - if(obj!=null && obj instanceof MiscID) { + if (obj!=null && obj instanceof MiscID) { return id.equals(((MiscID)obj).id); } return false; @@ -156,12 +156,12 @@ public class MiscID { public StringBuilder updateStmt(MiscID source) { StringBuilder sb = null; - if(id.equals(source.id)) { + if (id.equals(source.id)) { sb = addField(sb,"sponser",sponsor,source.sponsor); sb = addField(sb,"created",created,source.created); sb = addField(sb,"renewal",renewal,source.renewal); } - if(sb!=null) { + if (sb!=null) { sb.append(" WHERE id='"); sb.append(id); sb.append('\''); @@ -170,8 +170,8 @@ public class MiscID { } private StringBuilder addField(StringBuilder sb, String name, String a, String b) { - if(!a.equals(b)) { - if(sb==null) { + if (!a.equals(b)) { + if (sb==null) { sb = new StringBuilder("UPDATE authz.miscid SET "); } else { sb.append(','); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java index e9321f5f..e15a6bc2 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/MonthData.java @@ -42,15 +42,15 @@ public class MonthData { public MonthData(String env) throws IOException { f = new File("Monthly"+env+".dat"); - if(f.exists()) { + if (f.exists()) { BufferedReader br = new BufferedReader(new FileReader(f)); try { String line; String[] split; - while((line=br.readLine())!=null) { - if(!line.startsWith("#")) { + while ((line=br.readLine())!=null) { + if (!line.startsWith("#")) { split = Split.split(',', line); - if(split.length==5) { + if (split.length==5) { add(Integer.parseInt(split[0]),split[1], Integer.parseInt(split[2]), Integer.parseInt(split[3]), @@ -67,7 +67,7 @@ public class MonthData { public void add(int yr_mon, String target, long total, long adds, long drops) { Set<Row> row = data.get(yr_mon); - if(row==null) { + if (row==null) { data.put(yr_mon, (row=new HashSet<>())); } row.add(new Row(target,total,adds,drops)); @@ -101,14 +101,14 @@ public class MonthData { } public void write() throws IOException { - if(f.exists()) { + if (f.exists()) { File bu = new File(f.getName()+".bak"); f.renameTo(bu); } PrintStream ps = new PrintStream(f); try { - for( Entry<Integer, Set<Row>> rows : data.entrySet()) { - for(Row row : rows.getValue()) { + for ( Entry<Integer, Set<Row>> rows : data.entrySet()) { + for (Row row : rows.getValue()) { ps.printf("%d,%s,%d,%d,%d\n",rows.getKey(),row.target,row.total,row.adds,row.drops); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java index a2833e55..5692d116 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NS.java @@ -81,7 +81,7 @@ public class NS implements Comparable<NS> { Row row; tt = trans.start("Load Namespaces", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { row = iter.next(); NS ns = creator.create(row); data.put(ns.name,ns); @@ -143,9 +143,9 @@ public class NS implements Comparable<NS> { } } public static NSSplit deriveParent(String dotted) { - if(dotted==null)return null; - for(int idx = dotted.lastIndexOf('.');idx>=0; idx=dotted.lastIndexOf('.',idx-1)) { - if(data.get(dotted.substring(0, idx))!=null) { + if (dotted==null)return null; + for (int idx = dotted.lastIndexOf('.');idx>=0; idx=dotted.lastIndexOf('.',idx-1)) { + if (data.get(dotted.substring(0, idx))!=null) { return new NSSplit(dotted,idx); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java index abfd1ca4..b178c377 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Notification.java @@ -61,8 +61,8 @@ public class Notification { } public static TYPE get(int idx) { - for(TYPE nt : TYPE.values()) { - if(idx==nt.type) { + for (TYPE nt : TYPE.values()) { + if (idx==nt.type) { return nt; } } @@ -107,12 +107,12 @@ public class Notification { tt = trans.start("Process Notify", Env.SUB); try { - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; try { Notification not = creator.create(row); List<Notification> ln = data.get(not.user); - if(ln==null) { + if (ln==null) { ln = new ArrayList<>(); data.put(not.user, ln); } @@ -129,9 +129,9 @@ public class Notification { public static Notification get(String user, TYPE type) { List<Notification> ln = data.get(user); - if(ln!=null) { - for(Notification n : ln) { - if(type.equals(n.type)) { + if (ln!=null) { + for (Notification n : ln) { + if (type.equals(n.type)) { return n; } } @@ -148,7 +148,7 @@ public class Notification { public Notification create(Row row) { int idx =row.getInt(1); TYPE type = TYPE.get(idx); - if(type==null) { + if (type==null) { return null; } return new Notification(row.getString(0), type, row.getTimestamp(2), row.getInt(3)); @@ -166,11 +166,11 @@ public class Notification { } public int checksum() { - if(msg==null) { + if (msg==null) { current=0; - } else if(current==0) { - for(String l : msg.lines) { - for(byte b : l.getBytes()) { + } else if (current==0) { + for (String l : msg.lines) { + for (byte b : l.getBytes()) { current+=b; } } @@ -180,7 +180,7 @@ public class Notification { public boolean update(AuthzTrans trans, Session session, boolean dryRun) { checksum(); - if(last==null || current==0 || current!=checksum) { + if (last==null || current==0 || current!=checksum) { last = now; current = checksum(); String update = "UPDATE authz.notify SET " + @@ -192,7 +192,7 @@ public class Notification { "' AND type=" + type.idx() + ";"; - if(dryRun) { + if (dryRun) { trans.info().log("Would",update); } else { session.execute(update); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java index d980bcc2..a3354f38 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/NsAttrib.java @@ -76,20 +76,20 @@ public class NsAttrib { tt = trans.start("Process NsAttributes", Env.SUB); try { - for(Row row : results.all()) { + for (Row row : results.all()) { ++count; NsAttrib ur = creator.create(row); data.add(ur); List<NsAttrib> lna = byKey.get(ur.key); - if(lna==null) { + if (lna==null) { lna = new ArrayList<>(); byKey.put(ur.key, lna); } lna.add(ur); lna = byNS.get(ur.ns); - if(lna==null) { + if (lna==null) { lna = new ArrayList<>(); byNS.put(ur.ns, lna); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java index 799ce4df..ce22724b 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Perm.java @@ -47,21 +47,21 @@ public class Perm implements Comparable<Perm> { public final Set<String> roles; public String encode() { - if(encode == null) { + if (encode == null) { encode = ns + '|' + type + '|' + instance + '|' + action; } return encode; } public String fullType() { - if(fullType==null) { + if (fullType==null) { fullType = ns + '.' + type; } return fullType; } public String fullPerm() { - if(fullPerm==null) { + if (fullPerm==null) { fullPerm = ns + '.' + type + '|' + instance + '|' + action; } return fullPerm; @@ -104,7 +104,7 @@ public class Perm implements Comparable<Perm> { Row row; tt = trans.start("Load Perms", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { row = iter.next(); Perm pk = new Perm( row.getString(0),row.getString(1),row.getString(2), @@ -164,7 +164,7 @@ public class Perm implements Comparable<Perm> { } public static void executeRemove() { - for(Perm p : deletePerms) { + for (Perm p : deletePerms) { keys.remove(p.encode); data.remove(p); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java index 46d3cced..04a5dceb 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/Role.java @@ -64,14 +64,14 @@ public class Role implements Comparable<Role> { } public String encode() { - if(encode==null) { + if (encode==null) { encode = ns + '|' + name; } return encode; } public String fullName() { - if(full==null) { + if (full==null) { full = ns + '.' + name; } return full; @@ -102,7 +102,7 @@ public class Role implements Comparable<Role> { Row row; tt = trans.start("Load Roles", Env.SUB); try { - while(iter.hasNext()) { + while (iter.hasNext()) { row = iter.next(); Role rk =new Role(row.getString(0),row.getString(1), row.getString(2),row.getSet(3,String.class)); keys.put(rk.encode(), rk); @@ -165,7 +165,7 @@ public class Role implements Comparable<Role> { } public static void executeRemove() { - for(Role p : deleteRoles) { + for (Role p : deleteRoles) { keys.remove(p.encode); data.remove(p); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java index fab9233d..762f6c66 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/helpers/UserRole.java @@ -143,21 +143,21 @@ public class UserRole implements Cloneable, CacheChange.Data { private static void iterateResults(Creator<UserRole> creator, Iterator<Row> iter ) { Row row; - while(iter.hasNext()) { + while (iter.hasNext()) { ++totalLoaded; row = iter.next(); UserRole ur = creator.create(row); data.add(ur); List<UserRole> lur = byUser.get(ur.urdd.user); - if(lur==null) { + if (lur==null) { lur = new ArrayList<>(); byUser.put(ur.urdd.user, lur); } lur.add(ur); lur = byRole.get(ur.urdd.role); - if(lur==null) { + if (lur==null) { lur = new ArrayList<>(); byRole.put(ur.urdd.role, lur); } @@ -178,12 +178,12 @@ public class UserRole implements Cloneable, CacheChange.Data { data.remove(this); List<UserRole> lur = byUser.get(urdd.user); - if(lur!=null) { + if (lur!=null) { lur.remove(this); } lur = byRole.get(urdd.role); - if(lur!=null) { + if (lur!=null) { lur.remove(this); } } @@ -245,10 +245,10 @@ public class UserRole implements Cloneable, CacheChange.Data { public static UserRole get(String u, String r) { List<UserRole> lur = byUser.get(u); - if(lur!=null) { - for(UserRole ur : lur) { + if (lur!=null) { + for (UserRole ur : lur) { - if(ur.urdd.role.equals(r)) { + if (ur.urdd.role.equals(r)) { return ur; } } @@ -260,7 +260,7 @@ public class UserRole implements Cloneable, CacheChange.Data { // We write to a file, and validate. If the size is iffy, we email Support public void delayDelete(AuthzTrans trans, String text, boolean dryRun) { String dt = Chrono.dateTime(urdd.expires); - if(dryRun) { + if (dryRun) { trans.info().printf(LOG_FMT,text,"Would Delete",urdd.user,urdd.role,urdd.ns,urdd.rname,dt); } else { trans.info().printf(LOG_FMT,text,"Staged Deletion",urdd.user,urdd.role,urdd.ns,urdd.rname,dt); @@ -289,7 +289,7 @@ public class UserRole implements Cloneable, CacheChange.Data { } public static void actuateDeletionNow(AuthzTrans trans, URDelete directDel) { - for(UserRole ur : cache.getRemoved()) { + for (UserRole ur : cache.getRemoved()) { directDel.exec(trans, ur, "Actuating UserRole Deletion"); } cache.getRemoved().clear(); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java index 4555857a..f4a0f37c 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/javax/JavaxMailer.java @@ -150,7 +150,7 @@ public class JavaxMailer implements Mailer { try{ addressArray[count] = new InternetAddress(addr); count++; - }catch(Exception e){ + } catch (Exception e){ throw new OrganizationException("Failed to parse the email address "+ addr +": "+e.getMessage()); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java index 886bd56a..d34f9248 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/reports/ExpiringNext.java @@ -76,20 +76,20 @@ public class ExpiringNext extends Batch { List<String> expiring = new ArrayList<>(); trans.info().log("Checking for Expired UserRoles"); - for(UserRole ur : UserRole.getData()) { - if(ur.expires().after(now)) { - if(ur.expires().before(twoWeeks)) { + for (UserRole ur : UserRole.getData()) { + if (ur.expires().after(now)) { + if (ur.expires().before(twoWeeks)) { expiring.add(Chrono.dateOnlyStamp(ur.expires()) + ":\t" + ur.user() + '\t' + ur.role()); } - if(ur.expires().before(earliestUR)) { + if (ur.expires().before(earliestUR)) { earliestUR = ur.expires(); } } } - if(expiring.size()>0) { + if (expiring.size()>0) { Collections.sort(expiring,Collections.reverseOrder()); - for(String s : expiring) { + for (String s : expiring) { System.err.print('\t'); System.err.println(s); } @@ -101,30 +101,30 @@ public class ExpiringNext extends Batch { expiring.clear(); trans.info().log("Checking for Expired Credentials"); - for( Cred creds : Cred.data.values()) { + for ( Cred creds : Cred.data.values()) { Instance lastInstance=null; - for(Instance inst : creds.instances) { - if(inst.type==CredDAO.BASIC_AUTH || inst.type==CredDAO.BASIC_AUTH_SHA256) { - if(lastInstance == null || inst.expires.after(lastInstance.expires)) { + for (Instance inst : creds.instances) { + if (inst.type==CredDAO.BASIC_AUTH || inst.type==CredDAO.BASIC_AUTH_SHA256) { + if (lastInstance == null || inst.expires.after(lastInstance.expires)) { lastInstance = inst; } } } - if(lastInstance!=null) { - if(lastInstance.expires.after(now)) { - if(lastInstance.expires.before(twoWeeks)) { + if (lastInstance!=null) { + if (lastInstance.expires.after(now)) { + if (lastInstance.expires.before(twoWeeks)) { expiring.add(Chrono.dateOnlyStamp(lastInstance.expires) + ": \t" + creds.id); } } - if(lastInstance.expires.before(earliestCred)) { + if (lastInstance.expires.before(earliestCred)) { earliestCred = lastInstance.expires; } } } - if(expiring.size()>0) { + if (expiring.size()>0) { Collections.sort(expiring,Collections.reverseOrder()); - for(String s : expiring) { + for (String s : expiring) { System.err.print('\t'); System.err.println(s); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java index 868811a3..e9f0e726 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/Expiring.java @@ -117,7 +117,7 @@ public class Expiring extends Batch { } File data_dir = new File(env.getProperty("aaf_data_dir")); - if(!data_dir.exists() || !data_dir.canWrite() || !data_dir.canRead()) { + if (!data_dir.exists() || !data_dir.canWrite() || !data_dir.canRead()) { throw new IOException("Cannot read/write to Data Directory "+ data_dir.getCanonicalPath() + ": EXITING!!!"); } UserRole.setDeleteStream( @@ -137,7 +137,7 @@ public class Expiring extends Batch { email.preamble("Expiring Process Alert for %s",batchEnv); email.signature("Sincerely,\nAAF Expiring Batch Process\n"); String address = env.getProperty("ALERT_TO_ADDRESS"); - if(address==null) { + if (address==null) { throw new APIException("ALERT_TO_ADDRESS property is required"); } email.addTo(address); @@ -169,30 +169,30 @@ public class Expiring extends Batch { // Clean out Approvals UserRoles are fixed up. String memo; - for(List<Approval> la : Approval.byUser.values()) { - for(Approval a : la ) { + for (List<Approval> la : Approval.byUser.values()) { + for (Approval a : la ) { memo = a.getMemo(); - if(memo!=null && (memo.contains("Re-Approval") || memo.contains("Re-Validate"))) { + if (memo!=null && (memo.contains("Re-Approval") || memo.contains("Re-Validate"))) { String role = a.getRole(); - if(role!=null) { + if (role!=null) { UserRole ur = UserRole.get(a.getUser(), a.getRole()); Future f=null; - if(ur!=null) { - if(ur.expires().after(future)) { // no need for Approval anymore + if (ur!=null) { + if (ur.expires().after(future)) { // no need for Approval anymore a.delayDelete(noAvg, apprDAO, dryRun, "User Role already Extended"); UUID tkt = a.getTicket(); - if(tkt!=null && Future.data.containsKey(tkt)) { + if (tkt!=null && Future.data.containsKey(tkt)) { f = Future.data.get(a.getTicket()); } } } else { a.delayDelete(noAvg, apprDAO, dryRun, "User Role does not exist"); UUID tkt = a.getTicket(); - if(tkt !=null && Future.data.containsKey(tkt)) { + if (tkt !=null && Future.data.containsKey(tkt)) { f = Future.data.get(a.getTicket()); } } - if(f!=null) { + if (f!=null) { f.delayedDelete(noAvg, futureDAO, dryRun, "Approvals removed"); } } @@ -212,12 +212,12 @@ public class Expiring extends Batch { tt = trans.start("Delete old Futures", Env.REMOTE); trans.info().log("### Running Future Execution on ",Future.data.size(), "Items"); // Execute any Futures waiting - for(Future f : Future.data.values()) { - if(f.memo().contains("Re-Approval") || f.memo().contains("Re-Validate")) { + for (Future f : Future.data.values()) { + if (f.memo().contains("Re-Approval") || f.memo().contains("Re-Validate")) { List<Approval> la = Approval.byTicket.get(f.id()); - if(la!=null) { + if (la!=null) { Result<OP_STATUS> ruf = urFutureApproveExec.exec(noAvg,la,f); - if(ruf.isOK()) { + if (ruf.isOK()) { switch(ruf.value) { case P: break; @@ -246,11 +246,11 @@ public class Expiring extends Batch { String expiredBeforeNow = "Expired before " + tooLate; String expiredAfterFuture = "Expired after " + future; try { - for(Future f : Future.data.values()) { - if(f.expires().before(tooLate)) { + for (Future f : Future.data.values()) { + if (f.expires().before(tooLate)) { f.delayedDelete(noAvg,futureDAO,dryRun, expiredBeforeNow); Approval.delayDelete(noAvg, apprDAO, dryRun, Approval.byTicket.get(f.id()), expiredBeforeNow); - } else if(f.expires().after(future)) { + } else if (f.expires().after(future)) { f.delayedDelete(noAvg,futureDAO,dryRun, expiredAfterFuture); Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), expiredAfterFuture); } @@ -268,19 +268,19 @@ public class Expiring extends Batch { trans.info().log("### Checking Approvals valid (",Approval.byApprover.size(),"Items)"); // Make sure users of Approvals are still valid - for(List<Approval> lapp : Approval.byTicket.values()) { - for(Approval app : lapp) { + for (List<Approval> lapp : Approval.byTicket.values()) { + for (Approval app : lapp) { Future f; - if(app.getTicket()==null) { + if (app.getTicket()==null) { f = null; } else { f = Future.data.get(app.getTicket()); - if(Future.pendingDelete(f)) { + if (Future.pendingDelete(f)) { f=null; } } String msg; - if(f!=null && app.getRole()!=null && Role.byName.get(app.getRole())==null) { + if (f!=null && app.getRole()!=null && Role.byName.get(app.getRole())==null) { f.delayedDelete(noAvg,futureDAO,dryRun,msg="Role '" + app.getRole() + "' no longer exists"); Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); continue; @@ -288,7 +288,7 @@ public class Expiring extends Batch { switch(app.getStatus()) { case "pending": - if(f==null) { + if (f==null) { app.delayDelete(noAvg,apprDAO, isDryRun(), "ticketDeleted"); continue; } @@ -296,19 +296,19 @@ public class Expiring extends Batch { case "owner": boolean anOwner=false; String approle = app.getRole(); - if(approle!=null) { + if (approle!=null) { Role role = Role.byName.get(approle); - if(role==null) { + if (role==null) { app.delayDelete(noAvg, apprDAO, dryRun, "Role No Longer Exists"); continue; } else { // Make sure Owner Role exists String owner = role.ns + ".owner"; - if(Role.byName.containsKey(owner)) { + if (Role.byName.containsKey(owner)) { List<UserRole> lur = UserRole.getByRole().get(owner); - if(lur != null) { - for(UserRole ur : lur) { - if(ur.user().equals(app.getApprover())) { + if (lur != null) { + for (UserRole ur : lur) { + if (ur.user().equals(app.getApprover())) { anOwner = true; break; } @@ -316,7 +316,7 @@ public class Expiring extends Batch { } } } - if(!anOwner) { + if (!anOwner) { app.delayDelete(noAvg, apprDAO, dryRun, "No longer Owner"); } @@ -325,14 +325,14 @@ public class Expiring extends Batch { case "supervisor": try { Identity identity = org.getIdentity(noAvg, app.getUser()); - if(identity==null) { - if(f!=null) { + if (identity==null) { + if (f!=null) { f.delayedDelete(noAvg,futureDAO,dryRun,msg = app.getUser() + " is no longer associated with " + org.getName()); Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); } } else { - if(!app.getApprover().equals(identity.responsibleTo().fullID())) { - if(f!=null) { + if (!app.getApprover().equals(identity.responsibleTo().fullID())) { + if (f!=null) { f.delayedDelete(noAvg,futureDAO,dryRun,msg = app.getApprover() + " is no longer a Supervisor of " + app.getUser()); Approval.delayDelete(noAvg,apprDAO,dryRun, Approval.byTicket.get(f.id()), msg); } @@ -360,9 +360,9 @@ public class Expiring extends Batch { // Run for User Roles trans.info().log("Checking for Expired User Roles"); try { - for(UserRole ur : UserRole.getData()) { - if(org.getIdentity(noAvg, ur.user())==null) { // if not part of Organization; - if(isSpecial(ur.user())) { + for (UserRole ur : UserRole.getData()) { + if (org.getIdentity(noAvg, ur.user())==null) { // if not part of Organization; + if (isSpecial(ur.user())) { trans.info().log(ur.user(),"is not part of organization, but may not be deleted"); } else { ur.delayDelete(noAvg, "Not Part of Organization", dryRun); @@ -370,16 +370,16 @@ public class Expiring extends Batch { ++delayedURDeletes; } } else { - if(NS.data.get(ur.ns())==null) { + if (NS.data.get(ur.ns())==null) { ur.delayDelete(noAvg,"Namespace " + ur.ns() + " does not exist.",dryRun); ++delayedURDeletes; ++deleted; - } else if(!Role.byName.containsKey(ur.role())) { + } else if (!Role.byName.containsKey(ur.role())) { ur.delayDelete(noAvg,"Role " + ur.role() + " does not exist.",dryRun); ++deleted; ++delayedURDeletes; - } else if(ur.expires().before(tooLate)) { - if("owner".equals(ur.rname())) { // don't delete Owners, even if Expired + } else if (ur.expires().before(tooLate)) { + if ("owner".equals(ur.rname())) { // don't delete Owners, even if Expired urPrint.exec(noAvg,ur,"Owner Expired (but not deleted)"); } else { // In this case, when UR is expired, not dependent on other lookups, we delete straight out. @@ -387,16 +387,16 @@ public class Expiring extends Batch { ++deleted; } //trans.logAuditTrail(trans.info()); - } else if(ur.expires().before(future) && ur.expires().after(now)) { + } else if (ur.expires().before(future) && ur.expires().after(now)) { ++count; // Is there an Approval set already boolean needNew = true; - if(ur.role()!=null && ur.user()!=null) { + if (ur.role()!=null && ur.user()!=null) { List<Approval> abm = Approval.byUser.get(ur.user()); - if(abm!=null) { - for(Approval a : abm) { - if(a.getOperation().equals(FUTURE_OP.A.name()) && ur.role().equals(a.getRole())) { - if(Future.data.get(a.getTicket())!=null) { + if (abm!=null) { + for (Approval a : abm) { + if (a.getOperation().equals(FUTURE_OP.A.name()) && ur.role().equals(a.getRole())) { + if (Future.data.get(a.getTicket())!=null) { needNew = false; break; } @@ -404,7 +404,7 @@ public class Expiring extends Batch { } } } - if(needNew) { + if (needNew) { urFutureApprove.exec(noAvg, ur,""); } } @@ -418,10 +418,10 @@ public class Expiring extends Batch { } // Actualize UR Deletes, or send Email - if(UserRole.sizeForDeletion()>0) { + if (UserRole.sizeForDeletion()>0) { count+=UserRole.sizeForDeletion(); double onePercent = 0.01; - if(((double)UserRole.sizeForDeletion())/UserRole.getData().size() > onePercent) { + if (((double)UserRole.sizeForDeletion())/UserRole.getData().size() > onePercent) { Message msg = new Message(); try { msg.line("Found %d of %d UserRoles marked for Deletion in file %s", @@ -448,7 +448,7 @@ public class Expiring extends Batch { } } } - if(count>0) { + if (count>0) { String str = String.format("%d UserRoles modified or deleted", count); cacheTouch.exec(trans, "user_role", str); } @@ -460,20 +460,20 @@ public class Expiring extends Batch { try { CredDAO.Data crd = new CredDAO.Data(); Date last = null; - for( Cred creds : Cred.data.values()) { + for ( Cred creds : Cred.data.values()) { crd.id = creds.id; - for(int type : creds.types()) { + for (int type : creds.types()) { crd.type = type; - for( Instance inst : creds.instances) { - if(inst.expires.before(tooLate)) { + for ( Instance inst : creds.instances) { + if (inst.expires.before(tooLate)) { crd.expires = inst.expires; crDelete.exec(noAvg, crd,"Expired before " + tooLate); - } else if(last==null || inst.expires.after(last)) { + } else if (last==null || inst.expires.after(last)) { last = inst.expires; } } - if(last!=null) { - if(last.before(future)) { + if (last!=null) { + if (last.before(future)) { crd.expires = last; crPrint.exec(noAvg, crd,""); ++count; @@ -483,7 +483,7 @@ public class Expiring extends Batch { } } finally { String str = String.format("Found %d current creds expiring before %s", count, Chrono.dateOnlyStamp(future)); - if(count>0) { + if (count>0) { cacheTouch.exec(trans, "cred", str); } } @@ -493,8 +493,8 @@ public class Expiring extends Batch { @Override protected void _close(AuthzTrans trans) { aspr.info("End " + this.getClass().getSimpleName() + " processing" ); - for(Action<?,?,?> action : new Action<?,?,?>[] {crDelete}) { - if(action instanceof ActionDAO) { + for (Action<?,?,?> action : new Action<?,?,?>[] {crDelete}) { + if (action instanceof ActionDAO) { ((ActionDAO<?,?,?>)action).close(trans); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java index f9797c86..cab612eb 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/ExpiringP2.java @@ -70,7 +70,7 @@ public class ExpiringP2 extends Batch { cacheTouch = new CacheTouch(trans,urDelete); File data_dir = new File(env.getProperty("aaf_data_dir")); - if(!data_dir.exists() || !data_dir.canWrite() || !data_dir.canRead()) { + if (!data_dir.exists() || !data_dir.canWrite() || !data_dir.canRead()) { throw new IOException("Cannot read/write to Data Directory "+ data_dir.getCanonicalPath() + ": EXITING!!!"); } urDeleteF = new BufferedReader(new FileReader(new File(data_dir,"UserRoleDeletes.dat"))); @@ -92,10 +92,10 @@ public class ExpiringP2 extends Batch { Map<String,Count> tally = new HashMap<>(); int count=0; try { - while((line=urDeleteF.readLine())!=null) { - if(line.startsWith("#")) { + while ((line=urDeleteF.readLine())!=null) { + if (line.startsWith("#")) { Count cnt = tally.get(line); - if(cnt==null) { + if (cnt==null) { tally.put(line, cnt=new Count()); } cnt.inc(); @@ -114,11 +114,11 @@ public class ExpiringP2 extends Batch { } System.out.println("Tallies of UserRole Deletions"); - for(Entry<String, Count> es : tally.entrySet()) { + for (Entry<String, Count> es : tally.entrySet()) { System.out.printf(" %6d\t%20s\n", es.getValue().cnt,es.getKey()); } } finally { - if(cacheTouch!=null && count>0) { + if (cacheTouch!=null && count>0) { cacheTouch.exec(trans, "user_roles", "Removing UserRoles"); } } @@ -142,8 +142,8 @@ public class ExpiringP2 extends Batch { @Override protected void _close(AuthzTrans trans) { aspr.info("End " + this.getClass().getSimpleName() + " processing" ); - for(Action<?,?,?> action : new Action<?,?,?>[] {urDelete,cacheTouch}) { - if(action instanceof ActionDAO) { + for (Action<?,?,?> action : new Action<?,?,?>[] {urDelete,cacheTouch}) { + if (action instanceof ActionDAO) { ((ActionDAO<?,?,?>)action).close(trans); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java index 8b12399d..50c6dc21 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyApprovals.java @@ -69,7 +69,7 @@ public class NotifyApprovals extends Batch { session = historyDAO.getSession(trans); apprDAO = new ApprovalDAO(trans, historyDAO); futureDAO = new FutureDAO(trans, historyDAO); - if(isDryRun()) { + if (isDryRun()) { email = new EmailPrint(); maxEmails=3; } else { @@ -105,10 +105,10 @@ public class NotifyApprovals extends Batch { int emailCount = 0; List<Approval> pending = new ArrayList<>(); boolean isOwner,isSupervisor; - for(Entry<String, List<Approval>> es : Approval.byApprover.entrySet()) { + for (Entry<String, List<Approval>> es : Approval.byApprover.entrySet()) { isOwner = isSupervisor = false; String approver = es.getKey(); - if(approver.indexOf('@')<0) { + if (approver.indexOf('@')<0) { approver += org.getRealm(); } Date latestNotify=null, soonestExpire=null; @@ -116,28 +116,28 @@ public class NotifyApprovals extends Batch { GregorianCalendar soonest=new GregorianCalendar(); pending.clear(); - for(Approval app : es.getValue()) { + for (Approval app : es.getValue()) { Future f = app.getTicket()==null?null:Future.data.get(app.getTicket()); - if(f==null) { // only Ticketed Approvals are valid.. the others are records. + if (f==null) { // only Ticketed Approvals are valid.. the others are records. // Approvals without Tickets are no longer valid. - if("pending".equals(app.getStatus())) { + if ("pending".equals(app.getStatus())) { app.setStatus("lapsed"); app.update(noAvg,apprDAO,dryRun); // obeys dryRun } } else { - if((soonestExpire==null && f.expires()!=null) || (soonestExpire!=null && f.expires()!=null && soonestExpire.before(f.expires()))) { + if ((soonestExpire==null && f.expires()!=null) || (soonestExpire!=null && f.expires()!=null && soonestExpire.before(f.expires()))) { soonestExpire=f.expires(); } - if("pending".equals(app.getStatus())) { - if(!isOwner) { + if ("pending".equals(app.getStatus())) { + if (!isOwner) { isOwner = "owner".equals(app.getType()); } - if(!isSupervisor) { + if (!isSupervisor) { isSupervisor = "supervisor".equals(app.getType()); } - if((latestNotify==null && app.getLast_notified()!=null) ||(latestNotify!=null && app.getLast_notified()!=null && latestNotify.before(app.getLast_notified()))) { + if ((latestNotify==null && app.getLast_notified()!=null) ||(latestNotify!=null && app.getLast_notified()!=null && latestNotify.before(app.getLast_notified()))) { latestNotify=app.getLast_notified(); } pending.add(app); @@ -145,29 +145,29 @@ public class NotifyApprovals extends Batch { } } - if(!pending.isEmpty()) { + if (!pending.isEmpty()) { boolean go = false; - if(latestNotify==null) { // never notified... make it so + if (latestNotify==null) { // never notified... make it so go=true; } else { - if(!today.equals(Chrono.dateOnlyStamp(latest))) { // already notified today + if (!today.equals(Chrono.dateOnlyStamp(latest))) { // already notified today latest.setTime(latestNotify); soonest.setTime(soonestExpire); int year; int days = soonest.get(GregorianCalendar.DAY_OF_YEAR)-latest.get(GregorianCalendar.DAY_OF_YEAR); days+=((year=soonest.get(GregorianCalendar.YEAR))-latest.get(GregorianCalendar.YEAR))*365 + (soonest.isLeapYear(year)?1:0); - if(days<7) { // If Expirations get within a Week (or expired), notify everytime. + if (days<7) { // If Expirations get within a Week (or expired), notify everytime. go = true; } } } - if(go) { - if(maxEmails>emailCount++) { + if (go) { + if (maxEmails>emailCount++) { try { Organization org = OrganizationFactory.obtain(env, approver); Identity user = org.getIdentity(noAvg, approver); - if(user==null) { + if (user==null) { ps.printf("Invalid Identity: %s\n", approver); } else { email.clear(); @@ -175,7 +175,7 @@ public class NotifyApprovals extends Batch { email.addTo(user.email()); msg.line(LINE); msg.line("Why are you receiving this Notification?\n"); - if(isSupervisor) { + if (isSupervisor) { msg.line("%sYou are the supervisor of one or more employees who need access to tools which are protected by AAF. " + "Your employees may ask for access to various tools and applications to do their jobs. ASPR requires " + "that you are notified and approve their requests. The details of each need is provided when you click " @@ -183,7 +183,7 @@ public class NotifyApprovals extends Batch { msg.line("Your participation in this process fulfills the ASPR requirement to re-authorize users in roles on a regular basis.\n\n"); } - if(isOwner) { + if (isOwner) { msg.line("%sYou are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for " + "applications and their access review them regularly for accuracy. The AAF WIKI page for AT&T is https://wiki.web.att.com/display/aaf. " + "More info regarding questions of being a Namespace Owner is available at https://wiki.web.att.com/pages/viewpage.action?pageId=594741363\n",isSupervisor?"2) ":""); @@ -208,9 +208,9 @@ public class NotifyApprovals extends Batch { email.msg(msg); email.exec(noAvg, org,""); - if(!isDryRun()) { + if (!isDryRun()) { email.log(ps,"NotifyApprovals"); - for(Approval app : pending) { + for (Approval app : pending) { app.setLastNotified(now); app.update(noAvg, apprDAO, dryRun); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java index ab386c56..b4631f66 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/update/NotifyCredExpiring.java @@ -87,10 +87,10 @@ public class NotifyCredExpiring extends Batch { noAvg = env.newTransNoAvg(); noAvg.setUser(new BatchPrincipal("batch:NotifyCredExpiring")); - if((supportEmailAddr = env.getProperty("mailFromUserId"))==null) { + if ((supportEmailAddr = env.getProperty("mailFromUserId"))==null) { throw new APIException("mailFromUserId property must be set"); } - if(isDryRun()) { + if (isDryRun()) { email = new EmailPrint(); maxEmails=3; maxEmails = Integer.parseInt(trans.getProperty("MAX_EMAILS","3")); @@ -137,17 +137,17 @@ public class NotifyCredExpiring extends Batch { ownerCreds.put(UNKNOWN_ID,noOwner); // Get a list of ONLY the ones needing email by Owner - for(Entry<String, List<Cred>> es : Cred.byNS.entrySet()) { + for (Entry<String, List<Cred>> es : Cred.byNS.entrySet()) { lastCred.clear(); - for(Cred c : es.getValue()) { + for (Cred c : es.getValue()) { last = c.last(CredDAO.BASIC_AUTH,CredDAO.BASIC_AUTH_SHA256); - if(last!=null && last.after(tooLate) && last.before(early)) { + if (last!=null && last.after(tooLate) && last.before(early)) { List<UserRole> ownerURList = UserRole.getByRole().get(es.getKey()+".owner"); - if(ownerURList!=null) { - for(UserRole ur:ownerURList) { + if (ownerURList!=null) { + for (UserRole ur:ownerURList) { String owner = ur.user(); List<LastCred> llc = ownerCreds.get(owner); - if(llc==null) { + if (llc==null) { ownerCreds.put(owner, (llc=new ArrayList<>())); } llc.add(new LastCred(c,last)); @@ -164,39 +164,39 @@ public class NotifyCredExpiring extends Batch { Message msg = new Message(); Notification ownNotf; StringBuilder logMessage = new StringBuilder(); - for(Entry<String,List<LastCred>> es : ownerCreds.entrySet()) { + for (Entry<String,List<LastCred>> es : ownerCreds.entrySet()) { String owner = es.getKey(); boolean header = true; try { Organization org = OrganizationFactory.obtain(env, owner); Identity user = org.getIdentity(noAvg, owner); - if(!UNKNOWN_ID.equals(owner) && user==null) { + if (!UNKNOWN_ID.equals(owner) && user==null) { ps.printf("Invalid Identity: %s\n", owner); } else { logMessage.setLength(0); - if(maxEmails>emailCount) { + if (maxEmails>emailCount) { bCritical=bNormal=bEarly = false; email.clear(); msg.clear(); email.addTo(user==null?supportEmailAddr:user.email()); ownNotf = Notification.get(es.getKey(),TYPE.CN); - if(ownNotf==null) { + if (ownNotf==null) { ownNotf = Notification.create(user==null?UNKNOWN_ID:user.fullID(), TYPE.CN); } last = ownNotf.last; // Get Max ID size for formatting purposes int length = AAF_INSTANTIATED_MECHID.length(); - for(LastCred lc : es.getValue()) { + for (LastCred lc : es.getValue()) { length = Math.max(length, lc.cred.id.length()); } String id_exp_fmt = "\t%-"+length+"s %15s %s"; Collections.sort(es.getValue(),LastCred.COMPARE); - for(LastCred lc : es.getValue()) { - if(lc.last.after(must) && lc.last.before(early) && + for (LastCred lc : es.getValue()) { + if (lc.last.after(must) && lc.last.before(early) && (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { - if(!bEarly && header) { + if (!bEarly && header) { msg.line("\tThe following are friendly 2 month reminders, just in case you need to schedule your updates early. " + "You will be reminded next month\n"); msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); @@ -204,19 +204,19 @@ public class NotifyCredExpiring extends Batch { header = false; } bEarly = true; - } else if(lc.last.after(critical) && lc.last.before(must) && + } else if (lc.last.after(critical) && lc.last.before(must) && (ownNotf.last==null || ownNotf.last.before(withinLastWeek))) { - if(!bNormal) { + if (!bNormal) { boolean last2wks = lc.last.before(within2Weeks); - if(last2wks) { + if (last2wks) { try { Identity supvsr = user.responsibleTo(); email.addCC(supvsr.email()); - } catch(OrganizationException e) { + } catch (OrganizationException e) { trans.error().log(e, "Supervisor cannot be looked up"); } } - if(header) { + if (header) { msg.line("\tIt is now important for you to update Passwords all all configurations using them for the following.\n" + (last2wks?"\tNote: Your Supervisor is CCd\n":"\tNote: Your Supervisor will be notified if this is not being done before the last 2 weeks\n")); msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); @@ -225,8 +225,8 @@ public class NotifyCredExpiring extends Batch { header = false; } bNormal=true; - } else if(lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor - if(!bCritical && header) { + } else if (lc.last.after(tooLate) && lc.last.before(critical)) { // Email Every Day, with Supervisor + if (!bCritical && header) { msg.line("\t!!! WARNING: These Credentials will expire in LESS THAN ONE WEEK !!!!\n" + "\tYour supervisor is added to this Email\n"); msg.line(id_exp_fmt, AAF_INSTANTIATED_MECHID,EXPIRATION_DATE, QUICK_LINK); @@ -235,22 +235,22 @@ public class NotifyCredExpiring extends Batch { } bCritical = true; try { - if(user!=null) { + if (user!=null) { Identity supvsr = user.responsibleTo(); - if(supvsr!=null) { + if (supvsr!=null) { email.addCC(supvsr.email()); supvsr = supvsr.responsibleTo(); - if(supvsr!=null) { + if (supvsr!=null) { email.addCC(supvsr.email()); } } } - } catch(OrganizationException e) { + } catch (OrganizationException e) { trans.error().log(e, "Supervisor cannot be looked up"); } } - if(bEarly || bNormal || bCritical) { - if(logMessage.length()==0) { + if (bEarly || bNormal || bCritical) { + if (logMessage.length()==0) { logMessage.append("NotifyCredExpiring"); } logMessage.append("\n\t"); @@ -261,7 +261,7 @@ public class NotifyCredExpiring extends Batch { } } - if(bEarly || bNormal || bCritical) { + if (bEarly || bNormal || bCritical) { msg.line(LINE); msg.line("Why are you receiving this Notification?\n"); msg.line("You are the listed owner of one or more AAF Namespaces. ASPR requires that those responsible for " @@ -271,9 +271,9 @@ public class NotifyCredExpiring extends Batch { msg.line(" %s/ns\n\n",env.getProperty(GUI_URL)); email.msg(msg); Result<Void> rv = email.exec(trans, org,""); - if(rv.isOK()) { + if (rv.isOK()) { ++emailCount; - if(!isDryRun()) { + if (!isDryRun()) { ownNotf.update(noAvg, session, false); // SET LastNotification } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java index c0a9a3cd..07fd65f0 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_InputIterator.java @@ -69,7 +69,7 @@ public class JU_InputIterator { @After public void cleanUp() { - if(f.exists()) { + if (f.exists()) { f.delete(); } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java index cef81ded..97b6c56b 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/helpers/test/JU_MonthData.java @@ -94,10 +94,10 @@ public class JU_MonthData { @After public void cleanUp() { File g = new File("Monthlyenv.dat.bak"); - if(f.exists()) { + if (f.exists()) { f.delete(); } - if(g.exists()) { + if (g.exists()) { g.delete(); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java index f24c7c9f..d0e4eaab 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/AbsCassDAO.java @@ -128,18 +128,18 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { psinfos.add(this); cql = theCQL.trim().toUpperCase(); - if(cql.startsWith("INSERT")) { + if (cql.startsWith("INSERT")) { crud = CRUD.create; - } else if(cql.startsWith("UPDATE")) { + } else if (cql.startsWith("UPDATE")) { crud = CRUD.update; - } else if(cql.startsWith("DELETE")) { + } else if (cql.startsWith("DELETE")) { crud = CRUD.delete; } else { crud = CRUD.read; } int idx = 0, count=0; - while((idx=cql.indexOf('?',idx))>=0) { + while ((idx=cql.indexOf('?',idx))>=0) { ++idx; ++count; } @@ -155,7 +155,7 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { You should prepare only once, and cache the PreparedStatement in your application (it is thread-safe). If you call prepare multiple times with the same query string, the driver will log a warning. */ - if(ps==null) { + if (ps==null) { TimeTaken tt = trans.start("Preparing PSInfo " + crud.toString().toUpperCase() + " on " + name,Env.SUB); try { ps = getSession(trans).prepare(cql); @@ -287,7 +287,7 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { rs = getSession(trans).execute(key==null?ps(trans):ps(trans).bind(key)); /// TEST CODE for Exception // boolean force = true; -// if(force) { +// if (force) { // Map<InetSocketAddress, Throwable> misa = new HashMap<>(); // //misa.put(new InetSocketAddress(444),new Exception("no host was tried")); // misa.put(new InetSocketAddress(444),new Exception("Connection has been closed")); @@ -334,19 +334,19 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { @SuppressWarnings("unchecked") protected final Result<List<DATA>> extract(Loader<DATA> loader, ResultSet rs, List<DATA> indata, Accept<DATA> accept) { List<Row> rows = rs.all(); - if(rows.isEmpty()) { + if (rows.isEmpty()) { return Result.ok((List<DATA>)EMPTY); // Result sets now .emptyList(true); } else { DATA d; List<DATA> data = indata==null?new ArrayList<>(rows.size()):indata; - for(Row row : rows) { + for (Row row : rows) { try { d = loader.load(dataClass.newInstance(),row); - if(accept.ok(d)) { + if (accept.ok(d)) { data.add(d); } - } catch(Exception e) { + } catch (Exception e) { return Result.err(e); } } @@ -372,8 +372,8 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { public static final void primePSIs(TransStore trans) throws APIException, IOException { - for(AbsCassDAO<? extends TransStore, ?>.PSInfo psi : psinfos) { - if(psi.ps==null) { + for (AbsCassDAO<? extends TransStore, ?>.PSInfo psi : psinfos) { + if (psi.ps==null) { psi.ps(trans); } } @@ -382,28 +382,28 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { public final Session getSession(TransStore trans) throws APIException, IOException { // SessionFilter unused since 2015 // Try to use Trans' session, if exists -// if(sessionSlot!=null) { // try to get from Trans +// if (sessionSlot!=null) { // try to get from Trans // Session sess = trans.get(sessionSlot, null); -// if(sess!=null) { +// if (sess!=null) { // return sess; // } // } // If there's an owning DAO, use it's session - if(owningDAO!=null) { + if (owningDAO!=null) { return owningDAO.getSession(trans); } // OK, nothing else works... get our own. - if(session==null || resetTrigger) { + if (session==null || resetTrigger) { Cluster tempCluster = null; Session tempSession = null; try { synchronized(LOCK) { boolean reset = false; - for(ResetRequest r : resetDeque) { - if(r.session == session) { - if(r.timestamp>nextAvailableReset) { + for (ResetRequest r : resetDeque) { + if (r.session == session) { + if (r.timestamp>nextAvailableReset) { reset=true; nextAvailableReset = System.currentTimeMillis() + 60000; tempCluster = cluster; @@ -415,22 +415,22 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { } } - if(reset || session == null) { + if (reset || session == null) { TimeTaken tt = trans.start(NEW_CASSANDRA_SESSION, Env.SUB); try { // Note: Maitrayee recommended not closing the cluster, just // overwrite it. Jonathan 9/30/2016 assuming same for Session // This was a bad idea. Ran out of File Handles as I suspected, Jonathan - if(reset) { - for(AbsCassDAO<? extends TransStore, ?>.PSInfo psi : psinfos) { + if (reset) { + for (AbsCassDAO<? extends TransStore, ?>.PSInfo psi : psinfos) { psi.reset(); } } - if(reset || cluster==null) { + if (reset || cluster==null) { cluster = CassAccess.cluster(trans, keyspace); trans.warn().log(NEW_CASSANDRA_CLUSTER_OBJECT_CREATED); } - if(reset || session==null) { + if (reset || session==null) { session = cluster.connect(keyspace); trans.warn().log(NEW_CASSANDRA_SESSION_CREATED); } @@ -445,10 +445,10 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { try { resetDeque.clear(); // Not clearing Session/Cluster appears to kill off FileHandles - if(tempSession!=null && !tempSession.isClosed()) { + if (tempSession!=null && !tempSession.isClosed()) { tempSession.close(); } - if(tempCluster!=null && !tempCluster.isClosed()) { + if (tempCluster!=null && !tempCluster.isClosed()) { tempCluster.close(); } } finally { @@ -460,11 +460,11 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { } public final boolean reportPerhapsReset(TransStore trans, Exception e) { - if(owningDAO!=null) { + if (owningDAO!=null) { return owningDAO.reportPerhapsReset(trans, e); } else { boolean rv = false; - if(CassAccess.isResetException(e)) { + if (CassAccess.isResetException(e)) { trans.warn().printf("Session Reset called for %s by %s ",session==null?"":session,e==null?"Mgmt Command":e.getClass().getName()); resetDeque.addFirst(new ResetRequest(session)); rv = resetTrigger = true; @@ -475,8 +475,8 @@ public abstract class AbsCassDAO<TRANS extends TransStore,DATA> { } public void close(TransStore trans) { - if(owningDAO==null) { - if(session!=null) { + if (owningDAO==null) { + if (session!=null) { TimeTaken tt = trans.start("Cassandra Session Close", Env.SUB); try { session.close(); diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java index 3f4bbb20..1bda405c 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Cached.java @@ -56,7 +56,7 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T for (int i = 0; i < key.length(); i++) { h = 31*h + key.charAt(i); } - if(h<0)h*=-1; + if (h<0)h*=-1; return h%segSize; } @@ -67,7 +67,7 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T this.expireIn = expireIn; cache = new Object[segSize]; // Create a new Map for each Segment, and store locally - for(int i=0;i<segSize;++i) { + for (int i=0;i<segSize;++i) { cache[i]=obtain(name+i); } } @@ -83,17 +83,17 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T int cacheIdx = cacheIdx(key); @SuppressWarnings("unchecked") Map<String,Dated> map = ((Map<String,Dated>)cache[cacheIdx]); -// if(map.remove(key)!=null) // Not seeming to remove all the time - if(map!=null)map.clear(); +// if (map.remove(key)!=null) // Not seeming to remove all the time + if (map!=null)map.clear(); // System.err.println("Remove " + name + " " + key); return cacheIdx; } public Result<Void> invalidate(int segment) { - if(segment<0 || segment>=cache.length) return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment)); + if (segment<0 || segment>=cache.length) return Result.err(Status.ERR_BadData,"Cache Segment %s is out of range",Integer.toString(segment)); @SuppressWarnings("unchecked") Map<String,Dated> map = ((Map<String,Dated>)cache[segment]); - if(map!=null) { + if (map!=null) { map.clear(); } return Result.ok(); @@ -118,14 +118,14 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T Date dbStamp = info.get(trans, name,cacheIdx); // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax) - if(cached!=null && dbStamp.before(cached.timestamp)) { + if (cached!=null && dbStamp.before(cached.timestamp)) { ld = (List<DATA>)cached.data; rld = Result.ok(ld); } else { rld = getter.get(); - if(rld.isOK()) { // only store valid lists + if (rld.isOK()) { // only store valid lists map.put(key, new Dated(rld.value,expireIn)); // successful item found gets put in cache -// } else if(rld.status == Result.ERR_Backend){ +// } else if (rld.status == Result.ERR_Backend){ // map.remove(key); } } @@ -138,8 +138,8 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T * @param dao */ public static void startCleansing(AuthzEnv env, CachedDAO<?,?,?> ... dao) { - for(CachedDAO<?,?,?> d : dao) { - for(int i=0;i<d.segSize;++i) { + for (CachedDAO<?,?,?> d : dao) { + for (int i=0;i<d.segSize;++i) { startCleansing(env, d.table()+i); } } @@ -147,7 +147,7 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T public static<T extends Trans> void startRefresh(AuthzEnv env, CIDAO<AuthzTrans> cidao) { - if(infoTimer==null) { + if (infoTimer==null) { infoTimer = new Timer("CachedDAO Info Refresh Timer"); int minRefresh = 10*1000*60; // 10 mins Integer.parseInt(env.getProperty(CACHE_MIN_REFRESH_INTERVAL,"2000")); // 2 second minimum refresh infoTimer.schedule(new Refresh(env,cidao, minRefresh), 1000, minRefresh); // note: Refresh from DB immediately @@ -156,7 +156,7 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T public static void stopTimer() { Cache.stopTimer(); - if(infoTimer!=null) { + if (infoTimer!=null) { infoTimer.cancel(); infoTimer = null; } @@ -182,14 +182,14 @@ public class Cached<TRANS extends Trans, DATA extends Cacheable> extends Cache<T long now = System.currentTimeMillis(); long interval = now-lastRun; - if(interval < minRefresh || interval < Math.min(env.transRate(),maxRefresh)) return; + if (interval < minRefresh || interval < Math.min(env.transRate(),maxRefresh)) return; lastRun = now; AuthzTrans trans = env.newTransNoAvg(); Result<Void> rv = cidao.check(trans); - if(rv.status!=Result.OK) { + if (rv.status!=Result.OK) { env.error().log("Error in CacheInfo Refresh",rv.details); } - if(env.debug().isLoggable()) { + if (env.debug().isLoggable()) { StringBuilder sb = new StringBuilder("Cache Info Refresh: "); trans.auditTrail(0, sb, Env.REMOTE); env.debug().log(sb); diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java index 9375502c..cf410d0b 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CachedDAO.java @@ -52,7 +52,7 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend this.dao = dao; //read_str = "Cached READ for " + dao.table(); // dirty_str = "Cache DIRTY on " + dao.table(); - if(dao instanceof CassDAOImpl) { + if (dao instanceof CassDAOImpl) { ((CassDAOImpl<?,?>)dao).cache = this; } } @@ -80,14 +80,14 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend public static String keyFromObjs(Object ... objs) { String key; - if(objs.length==1 && objs[0] instanceof String) { + if (objs.length==1 && objs[0] instanceof String) { key = (String)objs[0]; } else { StringBuilder sb = new StringBuilder(); boolean first = true; - for(Object o : objs) { - if(o!=null) { - if(first) { + for (Object o : objs) { + if (o!=null) { + if (first) { first =false; } else { sb.append('|'); @@ -102,7 +102,7 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend public Result<DATA> create(TRANS trans, DATA data) { Result<DATA> d = dao.create(trans,data); - if(d.status==Status.OK) { + if (d.status==Status.OK) { add(d.value); } else { trans.error().log(d.errorString()); @@ -134,7 +134,7 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend @Override public final Result<List<DATA>> get() { return call(); -// if(result.isOKhasData()) { // Note, given above logic, could exist, but stale +// if (result.isOKhasData()) { // Note, given above logic, could exist, but stale // return result.value; // } else { // return null; @@ -146,11 +146,11 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend public Result<List<DATA>> read(final TRANS trans, final Object ... objs) { DAOGetter getter = new DAOGetter(trans,dao,objs); return get(trans, keyFromObjs(objs),getter); -// if(ld!=null) { +// if (ld!=null) { // return Result.ok(ld);//.emptyList(ld.isEmpty()); // } // // Result Result if exists -// if(getter.result==null) { +// if (getter.result==null) { // return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); // } // return getter.result; @@ -160,11 +160,11 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend public Result<List<DATA>> read(final String key, final TRANS trans, final Object[] objs) { DAOGetter getter = new DAOGetter(trans,dao,objs); return get(trans, key, getter); -// if(ld!=null) { +// if (ld!=null) { // return Result.ok(ld);//.emptyList(ld.isEmpty()); // } // // Result Result if exists -// if(getter.result==null) { +// if (getter.result==null) { // return Result.err(Status.ERR_NotFound, "No Cache or Lookup found on [%s]",dao.table()); // } // return getter.result; @@ -176,7 +176,7 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend } public Result<Void> update(TRANS trans, DATA data) { Result<Void> d = dao.update(trans, data); - if(d.status==Status.OK) { + if (d.status==Status.OK) { add(data); } else { trans.error().log(d.errorString()); @@ -185,14 +185,14 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend } public Result<Void> delete(TRANS trans, DATA data, boolean reread) { - if(reread) { // If reread, get from Cache, if possible, not DB exclusively + if (reread) { // If reread, get from Cache, if possible, not DB exclusively Result<List<DATA>> rd = read(trans,data); - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); // } else { // trans.error().log(rd.errorString()); } - if(rd.isEmpty()) { + if (rd.isEmpty()) { data.invalidate(this); return Result.err(Status.ERR_NotFound,"Not Found"); } @@ -205,7 +205,7 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend @Override public void close(TRANS trans) { - if(dao!=null) { + if (dao!=null) { dao.close(trans); } } @@ -221,7 +221,7 @@ public class CachedDAO<TRANS extends Trans,D extends DAO<TRANS,DATA>,DATA extend } public void invalidate(TRANS trans, DATA data) { - if(info.touch(trans, dao.table(),data.invalidate(this)).notOK()) { + if (info.touch(trans, dao.table(),data.invalidate(this)).notOK()) { trans.error().log("Cannot touch CacheInfo for Role"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java index 9b168a83..b8062fcd 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassAccess.java @@ -64,9 +64,9 @@ public class CassAccess { // @SuppressWarnings("deprecation") public static synchronized Cluster cluster(Env env, String prefix) throws APIException, IOException { - if(cb == null) { + if (cb == null) { String pre; - if(prefix==null) { + if (prefix==null) { pre=""; } else { env.info().log("Cassandra Connection for ",prefix); @@ -74,19 +74,19 @@ public class CassAccess { } cb = Cluster.builder(); String str = env.getProperty(pre+CASSANDRA_CLUSTERS_PORT,env.getProperty(CASSANDRA_CLUSTERS_PORT,"9042")); - if(str!=null) { + if (str!=null) { env.init().log("Cass Port = ",str ); cb.withPort(Integer.parseInt(str)); } str = env.getProperty(pre+CASSANDRA_CLUSTERS_USER_NAME,env.getProperty(CASSANDRA_CLUSTERS_USER_NAME,null)); - if(str!=null) { + if (str!=null) { env.init().log("Cass User = ",str ); String epass = env.getProperty(pre + CASSANDRA_CLUSTERS_PASSWORD,env.getProperty(CASSANDRA_CLUSTERS_PASSWORD,null)); - if(epass==null) { + if (epass==null) { throw new APIException("No Password configured for " + str); } //TODO Figure out way to ensure Decryptor setting in AuthzEnv - if(env instanceof AuthzEnv) { + if (env instanceof AuthzEnv) { cb.withCredentials(str,((AuthzEnv)env).decrypt(epass,true)); } else { cb.withCredentials(str, env.decryptor().decrypt(epass)); @@ -94,9 +94,9 @@ public class CassAccess { } str = env.getProperty(pre+CASSANDRA_RESET_EXCEPTIONS,env.getProperty(CASSANDRA_RESET_EXCEPTIONS,null)); - if(str!=null) { + if (str!=null) { env.init().log("Cass ResetExceptions = ",str ); - for(String ex : Split.split(',', str)) { + for (String ex : Split.split(',', str)) { resetExceptions.add(new Resettable(env,ex)); } } @@ -105,7 +105,7 @@ public class CassAccess { Double lat = str!=null?Double.parseDouble(str):null; str = env.getProperty(Config.CADI_LONGITUDE); Double lon = str!=null?Double.parseDouble(str):null; - if(lat == null || lon == null) { + if (lat == null || lon == null) { throw new APIException(Config.CADI_LATITUDE + " and/or " + Config.CADI_LONGITUDE + " are not set"); } @@ -118,23 +118,23 @@ public class CassAccess { String bestDC = null; int numInBestDC = 1; double mlat, mlon,temp,distance = Double.MAX_VALUE; - for(int i=0;i<machs.length;++i) { + for (int i=0;i<machs.length;++i) { String[] minfo = Split.split(':',machs[i]); - if(minfo.length>0) { + if (minfo.length>0) { cpoints[i]=minfo[0]; } - if(minfo.length>3) { - if(minfo[1].equals(bestDC)) { + if (minfo.length>3) { + if (minfo[1].equals(bestDC)) { ++numInBestDC; } else { // Calc closest DC with Great Circle mlat = Double.parseDouble(minfo[2]); mlon = Double.parseDouble(minfo[3]); // Note: GreatCircle Distance is always >= 0.0 (not negative) - if((temp=GreatCircle.calc(lat, lon, mlat, mlon)) < distance) { + if ((temp=GreatCircle.calc(lat, lon, mlat, mlon)) < distance) { distance = temp; - if(bestDC==null || !bestDC.equals(minfo[1])) { + if (bestDC==null || !bestDC.equals(minfo[1])) { bestDC = minfo[1]; numInBestDC = 1; } @@ -145,7 +145,7 @@ public class CassAccess { cb.addContactPoints(cpoints); - if(bestDC!=null) { + if (bestDC!=null) { // 8/26/2016 Management has determined that Accuracy is preferred over speed in bad situations // Local DC Aware Load Balancing appears to have the highest normal performance, with the best // Degraded Accuracy @@ -171,18 +171,18 @@ public class CassAccess { @SuppressWarnings("unchecked") public Resettable(Env env, String propData) throws APIException { - if(propData!=null && propData.length()>1) { + if (propData!=null && propData.length()>1) { String[] split = Split.split(':', propData); - if(split.length>0) { + if (split.length>0) { try { cls = (Class<? extends Exception>)Class.forName(split[0]); } catch (ClassNotFoundException e) { throw new APIException("Declared Cassandra Reset Exception, " + propData + ", cannot be ClassLoaded"); } } - if(split.length>1) { + if (split.length>1) { messages=new ArrayList<>(); - for(int i=1;i<split.length;++i) { + for (int i=1;i<split.length;++i) { String str = split[i]; int start = str.startsWith("\"")?1:0; int end = str.length()-(str.endsWith("\"")?1:0); @@ -195,11 +195,11 @@ public class CassAccess { } public boolean matches(Exception ex) { - if(ex.getClass().equals(cls)) { - if(messages!=null) { + if (ex.getClass().equals(cls)) { + if (messages!=null) { String msg = ex.getMessage(); - for(String m : messages) { - if(msg.contains(m)) { + for (String m : messages) { + if (msg.contains(m)) { return true; } } @@ -210,11 +210,11 @@ public class CassAccess { } public static final boolean isResetException(Exception e) { - if(e==null) { + if (e==null) { return true; } - for(Resettable re : resetExceptions) { - if(re.matches(e)) { + for (Resettable re : resetExceptions) { + if (re.matches(e)) { return true; } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassDAOImpl.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassDAOImpl.java index fae8f693..58c4386b 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassDAOImpl.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/CassDAOImpl.java @@ -120,25 +120,25 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS StringBuilder sbwc = new StringBuilder(); StringBuilder sbup = new StringBuilder(); - if(keylimit>0) { - for(int i=0;i<end;++i) { - if(i>0) { + if (keylimit>0) { + for (int i=0;i<end;++i) { + if (i>0) { sbfc.append(','); sbq.append(','); - if(i<keylimit) { + if (i<keylimit) { sbwc.append(" AND "); } } sbfc.append(fields[i].getName()); sbq.append('?'); - if(i>=keylimit) { - if(i>keylimit) { + if (i>=keylimit) { + if (i>keylimit) { sbup.append(','); } sbup.append(fields[i].getName()); sbup.append("=?"); } - if(i<keylimit) { + if (i<keylimit) { sbwc.append(fields[i].getName()); sbwc.append("=?"); } @@ -149,7 +149,7 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS readPS = new PSInfo(trans, "SELECT " + sbfc + " FROM " + table + " WHERE " + sbwc + ';',loader,readConsistency); // Note: UPDATES can't compile if there are no fields besides keys... Use "Insert" - if(sbup.length()==0) { + if (sbup.length()==0) { updatePS = createPS; // the same as an insert } else { updatePS = new PSInfo(trans, "UPDATE " + table + " SET " + sbup + " WHERE " + sbwc + ';',loader,writeConsistency); @@ -184,17 +184,17 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS * execute element. */ public Result<DATA> create(TRANS trans, DATA data) { - if(createPS==null) { + if (createPS==null) { return Result.err(Result.ERR_NotImplemented,"Create is disabled for %s",getClass().getSimpleName()); } - if(async) /*ResultSetFuture */ { + if (async) /*ResultSetFuture */ { Result<ResultSetFuture> rs = createPS.execAsync(trans, C_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result<ResultSet> rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } @@ -206,26 +206,26 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS * Read the Unique Row associated with Full Keys */ public Result<List<DATA>> read(TRANS trans, DATA data) { - if(readPS==null) { + if (readPS==null) { return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); } return readPS.read(trans, R_TEXT, data); } public Result<List<DATA>> read(TRANS trans, Object ... key) { - if(readPS==null) { + if (readPS==null) { return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); } return readPS.read(trans, R_TEXT, key); } public Result<DATA> readPrimKey(TRANS trans, Object ... key) { - if(readPS==null) { + if (readPS==null) { return Result.err(Result.ERR_NotImplemented,"Read is disabled for %s",getClass().getSimpleName()); } Result<List<DATA>> rld = readPS.read(trans, R_TEXT, key); - if(rld.isOK()) { - if(rld.isEmpty()) { + if (rld.isOK()) { + if (rld.isEmpty()) { return Result.err(Result.ERR_NotFound,rld.details); } else { return Result.ok(rld.value.get(0)); @@ -240,17 +240,17 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS } public Result<Void> update(TRANS trans, DATA data, boolean async) { - if(updatePS==null) { + if (updatePS==null) { return Result.err(Result.ERR_NotImplemented,"Update is disabled for %s",getClass().getSimpleName()); } - if(async)/* ResultSet rs =*/ { + if (async)/* ResultSet rs =*/ { Result<ResultSetFuture> rs = updatePS.execAsync(trans, U_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result<ResultSet> rs = updatePS.exec(trans, U_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } @@ -261,41 +261,41 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS // This method Sig for Cached... public Result<Void> delete(TRANS trans, DATA data, boolean reread) { - if(deletePS==null) { + if (deletePS==null) { return Result.err(Result.ERR_NotImplemented,"Delete is disabled for %s",getClass().getSimpleName()); } // Since Deleting will be stored off, for possible re-constitution, need the whole thing - if(reread) { + if (reread) { Result<List<DATA>> rd = read(trans,data); - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); } - if(rd.isEmpty()) { + if (rd.isEmpty()) { return Result.err(Status.ERR_NotFound,"Not Found"); } - for(DATA d : rd.value) { - if(async) { + for (DATA d : rd.value) { + if (async) { Result<ResultSetFuture> rs = deletePS.execAsync(trans, D_TEXT, d); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result<ResultSet> rs = deletePS.exec(trans, D_TEXT, d); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } wasModified(trans, CRUD.delete, d); } } else { - if(async)/* ResultSet rs =*/ { + if (async)/* ResultSet rs =*/ { Result<ResultSetFuture> rs = deletePS.execAsync(trans, D_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } else { Result<ResultSet> rs = deletePS.exec(trans, D_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } } @@ -317,9 +317,9 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS public static final String CASS_WRITE_CONSISTENCY="cassandra.writeConsistency"; protected static ConsistencyLevel readConsistency(AuthzTrans trans, String table) { String prop = trans.getProperty(CASS_READ_CONSISTENCY+'.'+table); - if(prop==null) { + if (prop==null) { prop = trans.getProperty(CASS_READ_CONSISTENCY); - if(prop==null) { + if (prop==null) { return ConsistencyLevel.ONE; // this is Cassandra Default } } @@ -328,9 +328,9 @@ public class CassDAOImpl<TRANS extends TransStore,DATA> extends AbsCassDAO<TRANS protected static ConsistencyLevel writeConsistency(AuthzTrans trans, String table) { String prop = trans.getProperty(CASS_WRITE_CONSISTENCY+'.'+table); - if(prop==null) { + if (prop==null) { prop = trans.getProperty(CASS_WRITE_CONSISTENCY); - if(prop==null) { + if (prop==null) { return ConsistencyLevel.ONE; // this is Cassandra Default\ } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java index cdfd0697..4a078f90 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/Loader.java @@ -60,14 +60,14 @@ public abstract class Loader<DATA> { rv = new Object[size]; body(data,0,rv); int body = size-keylimit(); - if(body>0) { + if (body>0) { key(data,body,rv); } break; default: rv = new Object[size]; key(data,0,rv); - if(size>keylimit()) { + if (size>keylimit()) { body(data,keylimit(),rv); } break; @@ -76,7 +76,7 @@ public abstract class Loader<DATA> { } public static void writeString(DataOutputStream os, String s) throws IOException { - if(s==null) { + if (s==null) { os.writeInt(-1); } else { switch(s.length()) { @@ -108,7 +108,7 @@ public abstract class Loader<DATA> { case 0: return ""; default: // Cover case where there is a large string, without always allocating a large buffer. - if(l>buff.length) { + if (l>buff.length) { buff = new byte[l]; } is.read(buff,0,l); @@ -127,11 +127,11 @@ public abstract class Loader<DATA> { * @throws IOException */ public static void writeStringSet(DataOutputStream os, Collection<String> set) throws IOException { - if(set==null) { + if (set==null) { os.writeInt(-1); } else { os.writeInt(set.size()); - for(String s : set) { + for (String s : set) { writeString(os, s); } } @@ -140,11 +140,11 @@ public abstract class Loader<DATA> { public static Set<String> readStringSet(DataInputStream is, byte[] buff) throws IOException { int l = is.readInt(); - if(l<0) { + if (l<0) { return null; } Set<String> set = new HashSet<>(l); - for(int i=0;i<l;++i) { + for (int i=0;i<l;++i) { set.add(readString(is,buff)); } return set; @@ -152,11 +152,11 @@ public abstract class Loader<DATA> { public static List<String> readStringList(DataInputStream is, byte[] buff) throws IOException { int l = is.readInt(); - if(l<0) { + if (l<0) { return null; } List<String> list = new ArrayList<>(l); - for(int i=0;i<l;++i) { + for (int i=0;i<l;++i) { list.add(Loader.readString(is,buff)); } return list; @@ -169,12 +169,12 @@ public abstract class Loader<DATA> { * @throws IOException */ public static void writeStringMap(DataOutputStream os, Map<String,String> map) throws IOException { - if(map==null) { + if (map==null) { os.writeInt(-1); } else { Set<Entry<String, String>> es = map.entrySet(); os.writeInt(es.size()); - for(Entry<String,String> e : es) { + for (Entry<String,String> e : es) { writeString(os, e.getKey()); writeString(os, e.getValue()); } @@ -184,11 +184,11 @@ public abstract class Loader<DATA> { public static Map<String,String> readStringMap(DataInputStream is, byte[] buff) throws IOException { int l = is.readInt(); - if(l<0) { + if (l<0) { return null; } Map<String,String> map = new HashMap<>(l); - for(int i=0;i<l;++i) { + for (int i=0;i<l;++i) { String key = readString(is,buff); map.put(key,readString(is,buff)); } @@ -200,11 +200,11 @@ public abstract class Loader<DATA> { } public static int readHeader(DataInputStream is, final int magic, final int version) throws IOException { - if(is.readInt()!=magic) { + if (is.readInt()!=magic) { throw new IOException("Corrupted Data Stream"); } int v = is.readInt(); - if(version<0 || v>version) { + if (version<0 || v>version) { throw new IOException("Unsupported Data Version: " + v); } return v; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java index eb5885f0..106999d3 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedCredDAO.java @@ -57,7 +57,7 @@ public class CachedCredDAO extends CachedDAO<AuthzTrans, CredDAO, CredDAO.Data> }; Result<List<CredDAO.Data>> lurd = get(trans, id, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_UserNotFound,"No User Cred found"); } return lurd; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java index a18e6a67..13180ab1 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedPermDAO.java @@ -46,13 +46,13 @@ public class CachedPermDAO extends CachedDAO<AuthzTrans,PermDAO, PermDAO.Data> { }; Result<List<Data>> lurd = get(trans, ns, getter); - if(lurd.isOKhasData()) { + if (lurd.isOKhasData()) { return lurd; } else { } -// if(getter.result==null) { -// if(lurd==null) { +// if (getter.result==null) { +// if (lurd==null) { return Result.err(Status.ERR_PermissionNotFound,"No Permission found - " + lurd.details); // } else { // return Result.ok(lurd); @@ -81,7 +81,7 @@ public class CachedPermDAO extends CachedDAO<AuthzTrans,PermDAO, PermDAO.Data> { // Note: Can reuse index1 here, because there is no name collision versus response Result<List<Data>> lurd = get(trans, ns+'|'+type, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_PermissionNotFound,"No Permission found"); } return lurd; @@ -106,7 +106,7 @@ public class CachedPermDAO extends CachedDAO<AuthzTrans,PermDAO, PermDAO.Data> { public Result<Void> addRole(AuthzTrans trans, PermDAO.Data perm, RoleDAO.Data role) { Result<Void> rv = dao().addRole(trans,perm,role.encode()); - if(trans.debug().isLoggable()) + if (trans.debug().isLoggable()) trans.debug().log("Adding",role.encode(),"to", perm, "with CachedPermDAO.addRole"); invalidate(trans,perm); return rv; @@ -114,7 +114,7 @@ public class CachedPermDAO extends CachedDAO<AuthzTrans,PermDAO, PermDAO.Data> { public Result<Void> delRole(AuthzTrans trans, Data perm, RoleDAO.Data role) { Result<Void> rv = dao().delRole(trans,perm,role.encode()); - if(trans.debug().isLoggable()) + if (trans.debug().isLoggable()) trans.debug().log("Removing",role.encode(),"from", perm, "with CachedPermDAO.delRole"); invalidate(trans,perm); return rv; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java index 1d8e6709..99fac2da 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedRoleDAO.java @@ -45,7 +45,7 @@ public class CachedRoleDAO extends CachedDAO<AuthzTrans,RoleDAO, RoleDAO.Data> { }; Result<List<Data>> lurd = get(trans, ns, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_RoleNotFound,"No Role found"); } return lurd; @@ -59,7 +59,7 @@ public class CachedRoleDAO extends CachedDAO<AuthzTrans,RoleDAO, RoleDAO.Data> { }; Result<List<Data>> lurd = get(trans, name, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_RoleNotFound,"No Role found"); } return lurd; @@ -74,7 +74,7 @@ public class CachedRoleDAO extends CachedDAO<AuthzTrans,RoleDAO, RoleDAO.Data> { public Result<Void> addPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { Result<Void> rv = dao().addPerm(trans,rd,perm); - if(trans.debug().isLoggable()) + if (trans.debug().isLoggable()) trans.debug().log("Adding",perm,"to", rd, "with CachedRoleDAO.addPerm"); invalidate(trans, rd); return rv; @@ -82,7 +82,7 @@ public class CachedRoleDAO extends CachedDAO<AuthzTrans,RoleDAO, RoleDAO.Data> { public Result<Void> delPerm(AuthzTrans trans, RoleDAO.Data rd, PermDAO.Data perm) { Result<Void> rv = dao().delPerm(trans,rd,perm); - if(trans.debug().isLoggable()) + if (trans.debug().isLoggable()) trans.debug().log("Removing",perm,"from", rd, "with CachedRoleDAO.addPerm"); invalidate(trans, rd); return rv; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java index 2121b136..c1aa9017 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cached/CachedUserRoleDAO.java @@ -53,9 +53,9 @@ public class CachedUserRoleDAO extends CachedDAO<AuthzTrans,UserRoleDAO, UserRol DAOGetter getter = new DAOGetter(trans,dao()) { public Result<List<Data>> call() { // If the call is for THIS user, and it exists, get from TRANS, add to TRANS if not. - if(user!=null && user.equals(trans.user())) { + if (user!=null && user.equals(trans.user())) { Result<List<Data>> transLD = trans.get(transURSlot,null); - if(transLD==null ) { + if (transLD==null ) { transLD = dao.readByUser(trans, user); } return transLD; @@ -65,7 +65,7 @@ public class CachedUserRoleDAO extends CachedDAO<AuthzTrans,UserRoleDAO, UserRol } }; Result<List<Data>> lurd = get(trans, user, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",user); } return lurd; @@ -79,7 +79,7 @@ public class CachedUserRoleDAO extends CachedDAO<AuthzTrans,UserRoleDAO, UserRol } }; Result<List<Data>> lurd = get(trans, role, getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for [%s]",role); } return lurd; @@ -88,12 +88,12 @@ public class CachedUserRoleDAO extends CachedDAO<AuthzTrans,UserRoleDAO, UserRol public Result<List<UserRoleDAO.Data>> readUserInRole(final AuthzTrans trans, final String user, final String role) { DAOGetter getter = new DAOGetter(trans,dao()) { public Result<List<Data>> call() { - if(user.equals(trans.user())) { + if (user.equals(trans.user())) { Result<List<Data>> rrbu = readByUser(trans, user); - if(rrbu.isOK()) { + if (rrbu.isOK()) { List<Data> ld = new ArrayList<>(1); - for(Data d : rrbu.value) { - if(d.role.equals(role)) { + for (Data d : rrbu.value) { + if (d.role.equals(role)) { ld.add(d); break; } @@ -107,7 +107,7 @@ public class CachedUserRoleDAO extends CachedDAO<AuthzTrans,UserRoleDAO, UserRol } }; Result<List<Data>> lurd = get(trans, keyFromObjs(user,role), getter); - if(lurd.isOK() && lurd.isEmpty()) { + if (lurd.isOK() && lurd.isEmpty()) { return Result.err(Status.ERR_UserRoleNotFound,"UserRole not found for role [%s] and user [%s]",role,user); } return lurd; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java index 1948ac65..cc4135ee 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ApprovalDAO.java @@ -99,7 +99,7 @@ public class ApprovalDAO extends CassDAOImpl<AuthzTrans,ApprovalDAO.Data> { data.operation = row.getString(7); data.last_notified = row.getTimestamp(8); // This is used to get "WRITETIME(STATUS)" from Approval, which gives us an "updated" - if(row.getColumnDefinitions().size()>9) { + if (row.getColumnDefinitions().size()>9) { // Rows reported in MicroSeconds data.updated = new Date(row.getLong(9)/1000); } @@ -168,11 +168,11 @@ public class ApprovalDAO extends CassDAOImpl<AuthzTrans,ApprovalDAO.Data> { @Override public Result<Data> create(AuthzTrans trans, Data data) { // If ID is not set (typical), create one. - if(data.id==null) { + if (data.id==null) { data.id = Chrono.dateToUUID(System.currentTimeMillis()); } Result<ResultSet> rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } return Result.ok(data); @@ -200,14 +200,14 @@ public class ApprovalDAO extends CassDAOImpl<AuthzTrans,ApprovalDAO.Data> { */ @Override public Result<Void> delete(AuthzTrans trans, Data data, boolean reread) { - if(reread || data.status == null) { // if Memo is empty, likely not full record + if (reread || data.status == null) { // if Memo is empty, likely not full record Result<ResultSet> rd = readPS.exec(trans, R_TEXT, data); - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); } ApprovalLoader.deflt.load(data, rd.value.one()); } - if("approved".equals(data.status) || "denied".equals(data.status)) { + if ("approved".equals(data.status) || "denied".equals(data.status)) { StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); sb.append("INSERT INTO "); sb.append(TABLELOG); @@ -228,7 +228,7 @@ public class ApprovalDAO extends CassDAOImpl<AuthzTrans,ApprovalDAO.Data> { sb.append("APPLY BATCH;\n"); TimeTaken tt = trans.start("DELETE APPROVAL",Env.REMOTE); try { - if(async) { + if (async) { getSession(trans).executeAsync(sb.toString()); return Result.ok(); } else { @@ -270,7 +270,7 @@ public class ApprovalDAO extends CassDAOImpl<AuthzTrans,ApprovalDAO.Data> { : (modified.name() + "d approval for " + data.user); // Detail? // Reconstruct? - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java index 6702476a..e0c0c0d4 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/ArtiDAO.java @@ -170,7 +170,7 @@ public class ArtiDAO extends CassDAOImpl<AuthzTrans,ArtiDAO.Data> { writeString(os, data.mechid); writeString(os, data.machine); os.writeInt(data.type.size()); - for(String s : data.type) { + for (String s : data.type) { writeString(os, s); } writeString(os, data.sponsor); @@ -181,9 +181,9 @@ public class ArtiDAO extends CassDAOImpl<AuthzTrans,ArtiDAO.Data> { writeString(os, data.notify); os.writeLong(data.expires==null?-1:data.expires.getTime()); os.writeInt(data.renewDays); - if(data.sans!=null) { + if (data.sans!=null) { os.writeInt(data.sans.size()); - for(String s : data.sans) { + for (String s : data.sans) { writeString(os, s); } } else { @@ -200,7 +200,7 @@ public class ArtiDAO extends CassDAOImpl<AuthzTrans,ArtiDAO.Data> { data.machine = readString(is,buff); int size = is.readInt(); data.type = new HashSet<>(size); - for(int i=0;i<size;++i) { + for (int i=0;i<size;++i) { data.type.add(readString(is,buff)); } data.sponsor = readString(is,buff); @@ -214,7 +214,7 @@ public class ArtiDAO extends CassDAOImpl<AuthzTrans,ArtiDAO.Data> { data.renewDays = is.readInt(); size = is.readInt(); data.sans = new HashSet<>(size); - for(int i=0;i<size;++i) { + for (int i=0;i<size;++i) { data.sans.add(readString(is,buff)); } } @@ -222,7 +222,7 @@ public class ArtiDAO extends CassDAOImpl<AuthzTrans,ArtiDAO.Data> { private void init(AuthzTrans trans) { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans,this); } @@ -288,7 +288,7 @@ public class ArtiDAO extends CassDAOImpl<AuthzTrans,ArtiDAO.Data> { ? String.format("%s by %s", override[0], hd.user) : String.format("%sd %s for %s",modified.name(),data.mechid,data.machine); // Detail? - if(modified==CRUD.delete) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -296,7 +296,7 @@ public class ArtiDAO extends CassDAOImpl<AuthzTrans,ArtiDAO.Data> { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java index e3f994c0..4aa94866 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CacheInfoDAO.java @@ -138,7 +138,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl } public static<T extends Trans> void startUpdate(AuthzEnv env, HMangr hman, SecuritySetter<HttpURLConnection> ss, String ip, int port) { - if(cacheUpdate==null) { + if (cacheUpdate==null) { Thread t= new Thread(cacheUpdate = new CacheUpdate(env,hman,ss, ip,port),"CacheInfo Update Thread"); t.setDaemon(true); t.start(); @@ -146,7 +146,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl } public static<T extends Trans> void stopUpdate() { - if(cacheUpdate!=null) { + if (cacheUpdate!=null) { cacheUpdate.go=false; } } @@ -195,9 +195,9 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl @Override public Integer code(Rcli<?> client) throws APIException, CadiException { URI to = client.getURI(); - if(!to.getAuthority().equals(authority)) { + if (!to.getAuthority().equals(authority)) { Future<Void> f = client.delete("/mgmt/cache/"+type+'/'+segs,VOID_CT); - if(f.get(hman.readTimeout())) { + if (f.get(hman.readTimeout())) { ++total; } else { trans.error().log("Error During AAF Peer Notify",f.code(),f.body()); @@ -216,14 +216,14 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl set = null; } public void add(int[] ints) { - if(set==null) { + if (set==null) { set = new HashSet<>(); - for(int i=0;i<raw.length;++i) { + for (int i=0;i<raw.length;++i) { set.add(raw[i]); } } - for(int i=0;i<ints.length;++i) { + for (int i=0;i<ints.length;++i) { set.add(ints[i]); } } @@ -232,9 +232,9 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; - if(set==null) { - for(int i : raw) { - if(first) { + if (set==null) { + for (int i : raw) { + if (first) { first=false; } else { sb.append(','); @@ -242,8 +242,8 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl sb.append(i); } } else { - for(Integer i : set) { - if(first) { + for (Integer i : set) { + if (first) { first=false; } else { sb.append(','); @@ -260,7 +260,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl do { try { Transfer data = notifyDQ.poll(4,TimeUnit.SECONDS); - if(data==null) { + if (data==null) { continue; } @@ -271,37 +271,37 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl long start=0; // Do a block poll first do { - if(gather==null) { + if (gather==null) { start = System.nanoTime(); trans = env.newTransNoAvg(); cc = new CacheClear(trans); gather = new HashMap<>(); } IntHolder prev = gather.get(data.table); - if(prev==null) { + if (prev==null) { gather.put(data.table,new IntHolder(data.segs)); } else { prev.add(data.segs); } // continue while there is data - } while((data = notifyDQ.poll())!=null); - if(gather!=null) { - for(Entry<String, IntHolder> es : gather.entrySet()) { + } while ((data = notifyDQ.poll())!=null); + if (gather!=null) { + for (Entry<String, IntHolder> es : gather.entrySet()) { cc.set(es); try { - if(hman.all(ss, cc, false)!=null) { + if (hman.all(ss, cc, false)!=null) { ++count; } } catch (Exception e) { trans.error().log(e, "Error on Cache Update"); } } - if(env.debug().isLoggable()) { + if (env.debug().isLoggable()) { float millis = (System.nanoTime()-start)/1000000f; StringBuilder sb = new StringBuilder("Direct Cache Refresh: "); sb.append("Updated "); sb.append(count); - if(count==1) { + if (count==1) { sb.append(" entry for "); } else { sb.append(" entries for "); @@ -309,7 +309,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl int peers = count<=0?0:cc.total/count; sb.append(peers); sb.append(" client"); - if(peers!=1) { + if (peers!=1) { sb.append('s'); } sb.append(" in "); @@ -323,7 +323,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl go = false; Thread.currentThread().interrupt(); } - } while(go); + } while (go); } } @@ -347,9 +347,9 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl ///////////// // ConcurrentQueues are open-ended. We don't want any Memory leaks // Note: we keep a separate counter, because "size()" on a Linked Queue is expensive - if(cacheUpdate!=null) { + if (cacheUpdate!=null) { try { - if(!CacheUpdate.notifyDQ.offer(new CacheUpdate.Transfer(name, seg),2,TimeUnit.SECONDS)) { + if (!CacheUpdate.notifyDQ.offer(new CacheUpdate.Transfer(name, seg),2,TimeUnit.SECONDS)) { trans.error().log("Cache Notify Queue is not accepting messages, bouncing may be appropriate" ); } } catch (InterruptedException e) { @@ -367,7 +367,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl start.append(": "); StringBuilder sb = new StringBuilder("BEGIN BATCH\n"); boolean first = true; - for(int s : seg) { + for (int s : seg) { sb.append(UPDATE_SP); sb.append(TABLE); sb.append(" SET touched=dateof(now()) WHERE name = '"); @@ -375,7 +375,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl sb.append("' AND seg = "); sb.append(s); sb.append(";\n"); - if(first) { + if (first) { first =false; } else { start.append(','); @@ -413,24 +413,24 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl String lastName = null; Date[] dates = null; - for(Row row : rs.all()) { + for (Row row : rs.all()) { String name = row.getString(0); int seg = row.getInt(1); - if(!name.equals(lastName)) { + if (!name.equals(lastName)) { dates = info.get(name); lastName=name; } - if(dates==null) { + if (dates==null) { dates=new Date[seg+1]; info.put(name,dates); - } else if(dates.length<=seg) { + } else if (dates.length<=seg) { Date[] temp = new Date[seg+1]; System.arraycopy(dates, 0, temp, 0, dates.length); dates = temp; info.put(name, dates); } Date temp = row.getTimestamp(2); - if(dates[seg]==null || dates[seg].before(temp)) { + if (dates[seg]==null || dates[seg].before(temp)) { dates[seg]=temp; } } @@ -443,16 +443,16 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl @Override public Date get(AuthzTrans trans, String table, int seg) { Date[] dates = info.get(table); - if(dates==null) { + if (dates==null) { dates = new Date[seg+1]; touch(trans,table, seg); - } else if(dates.length<=seg) { + } else if (dates.length<=seg) { Date[] temp = new Date[seg+1]; System.arraycopy(dates, 0, temp, 0, dates.length); dates = temp; } Date rv = dates[seg]; - if(rv==null) { + if (rv==null) { rv=dates[seg]=startTime; } return rv; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java index 00c9ae90..6c23938f 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CertDAO.java @@ -143,7 +143,7 @@ public class CertDAO extends CassDAOImpl<AuthzTrans,CertDAO.Data> { writeString(os, data.x500); writeString(os, data.x509); writeString(os, data.ca); - if(data.serial==null) { + if (data.serial==null) { os.writeInt(-1); } else { byte[] dsba = data.serial.toByteArray(); @@ -164,9 +164,9 @@ public class CertDAO extends CassDAOImpl<AuthzTrans,CertDAO.Data> { data.ca = readString(is,buff); int i = is.readInt(); data.serial=null; - if(i>=0) { + if (i>=0) { byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads - if(is.read(bytes)>0) { + if (is.read(bytes)>0) { data.serial = new BigInteger(bytes); } } @@ -180,10 +180,10 @@ public class CertDAO extends CassDAOImpl<AuthzTrans,CertDAO.Data> { private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans,this); } - if(infoDAO==null) { + if (infoDAO==null) { infoDAO = new CacheInfoDAO(trans,this); } @@ -226,7 +226,7 @@ public class CertDAO extends CassDAOImpl<AuthzTrans,CertDAO.Data> { ? String.format("%s by %s", override[0], hd.user) : (modified.name() + "d certificate info for " + data.id); // Detail? - if(modified==CRUD.delete) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -234,10 +234,10 @@ public class CertDAO extends CassDAOImpl<AuthzTrans,CertDAO.Data> { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { trans.error().log("Cannot touch Cert"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java index 5bcba9d9..7674c7e8 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/CredDAO.java @@ -158,7 +158,7 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { os.writeInt(data.other==null?0:data.other); writeString(os, data.ns); writeString(os, data.notes); - if(data.cred==null) { + if (data.cred==null) { os.writeInt(-1); } else { int l = data.cred.limit()-data.cred.position(); @@ -183,10 +183,10 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { int i = is.readInt(); data.cred=null; - if(i>=0) { + if (i>=0) { byte[] bytes = new byte[i]; // a bit dangerous, but lessened because of all the previous sized data reads int read = is.read(bytes); - if(read>0) { + if (read>0) { data.cred = ByteBuffer.wrap(bytes); } } @@ -195,10 +195,10 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans,this); } - if(infoDAO==null) { + if (infoDAO==null) { infoDAO = new CacheInfoDAO(trans,this); } @@ -241,7 +241,7 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { ? String.format("%s by %s", override[0], hd.user) : (modified.name() + "d credential for " + data.id); // Detail? - if(modified==CRUD.delete) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -249,10 +249,10 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).status!=Status.OK) { trans.error().log("Cannot touch Cred"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java index 6b0ea2df..a98f101f 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/FutureDAO.java @@ -143,14 +143,14 @@ public class FutureDAO extends CassDAOImpl<AuthzTrans,FutureDAO.Data> { */ public Result<FutureDAO.Data> create(AuthzTrans trans, FutureDAO.Data data, String id) { // If ID is not set (typical), create one. - if(data.id==null) { + if (data.id==null) { StringBuilder sb = new StringBuilder(trans.user()); sb.append(data.target); sb.append(System.currentTimeMillis()); data.id = UUID.nameUUIDFromBytes(sb.toString().getBytes()); } Result<ResultSet> rs = createPS.exec(trans, C_TEXT, data); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } wasModified(trans, CRUD.create, data, null, id); @@ -175,7 +175,7 @@ public class FutureDAO extends CassDAOImpl<AuthzTrans,FutureDAO.Data> { hd.subject = subject?override[1]:""; hd.memo = memo?String.format("%s by %s", override[0], hd.user):data.memo; - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java index ce7e5477..a40b28fb 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/HistoryDAO.java @@ -174,7 +174,7 @@ public class HistoryDAO extends CassDAOImpl<AuthzTrans, HistoryDAO.Data> { public Result<List<Data>> readByYYYYMM(AuthzTrans trans, int yyyymm) { Result<ResultSet> rs = readByYRMN.exec(trans, "yr_mon", yyyymm); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } return extract(defLoader,rs.value,null,dflt); @@ -186,22 +186,22 @@ public class HistoryDAO extends CassDAOImpl<AuthzTrans, HistoryDAO.Data> { * month - the month in a year ...values 1 - 12 **/ public Result<List<Data>> readByUser(AuthzTrans trans, String user, int ... yyyymm) { - if(yyyymm.length==0) { + if (yyyymm.length==0) { return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified"); } Result<ResultSet> rs = readByUser.exec(trans, "user", user); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt); } public Result<List<Data>> readBySubject(AuthzTrans trans, String subject, String target, int ... yyyymm) { - if(yyyymm.length==0) { + if (yyyymm.length==0) { return Result.err(Status.ERR_BadData, "No or invalid yyyymm specified"); } Result<ResultSet> rs = readBySubject.exec(trans, "subject", subject, target); - if(rs.notOK()) { + if (rs.notOK()) { return Result.err(rs); } return extract(defLoader,rs.value,null,yyyymm.length>0?new YYYYMM(yyyymm):dflt); @@ -215,8 +215,8 @@ public class HistoryDAO extends CassDAOImpl<AuthzTrans, HistoryDAO.Data> { @Override public boolean ok(Data data) { int dym = data.yr_mon; - for(int ym:yyyymm) { - if(dym==ym) { + for (int ym:yyyymm) { + if (dym==ym) { return true; } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java index 5d7aebed..757efa5f 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/LocateDAO.java @@ -162,11 +162,11 @@ public class LocateDAO extends CassDAOImpl<AuthzTrans,LocateDAO.Data> { os.writeFloat(data.latitude); os.writeFloat(data.longitude); writeString(os, data.protocol); - if(data.subprotocol==null) { + if (data.subprotocol==null) { os.writeInt(0); } else { os.writeInt(data.subprotocol.size()); - for(String s: data.subprotocol) { + for (String s: data.subprotocol) { writeString(os,s); } } @@ -192,11 +192,11 @@ public class LocateDAO extends CassDAOImpl<AuthzTrans,LocateDAO.Data> { int size = is.readInt(); data.subprotocol = new HashSet<>(size); - for(int i=0;i<size;++i) { + for (int i=0;i<size;++i) { data.subprotocol.add(readString(is,buff)); } String port_key = readString(is,buff); - if(port_key.length()>0) { + if (port_key.length()>0) { data.port_key=UUID.fromString(port_key); } else { data.port_key = null; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java index 29ac379b..192887b9 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/Namespace.java @@ -55,9 +55,9 @@ public class Namespace implements Bytification { description = ndd.description; type = ndd.type; parent = ndd.parent; - if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { + if (ndd.attrib!=null && !ndd.attrib.isEmpty()) { attrib = new ArrayList<>(); - for( Entry<String, String> entry : ndd.attrib.entrySet()) { + for ( Entry<String, String> entry : ndd.attrib.entrySet()) { attrib.add(new Pair<String,String>(entry.getKey(),entry.getValue())); } } @@ -70,9 +70,9 @@ public class Namespace implements Bytification { description = ndd.description; type = ndd.type; parent = ndd.parent; - if(ndd.attrib!=null && !ndd.attrib.isEmpty()) { + if (ndd.attrib!=null && !ndd.attrib.isEmpty()) { attrib = new ArrayList<>(); - for( Entry<String, String> entry : ndd.attrib.entrySet()) { + for ( Entry<String, String> entry : ndd.attrib.entrySet()) { attrib.add(new Pair<String,String>(entry.getKey(),entry.getValue())); } } @@ -141,7 +141,7 @@ public class Namespace implements Bytification { */ @Override public boolean equals(Object arg0) { - if(arg0==null || !(arg0 instanceof Namespace)) { + if (arg0==null || !(arg0 instanceof Namespace)) { return false; } return name.equals(((Namespace)arg0).name); diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java index 30f0d6b5..f769e38c 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsDAO.java @@ -149,10 +149,10 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { private void init(AuthzTrans trans) throws APIException, IOException { // Set up sub-DAOs - if(historyDAO==null) { + if (historyDAO==null) { historyDAO = new HistoryDAO(trans, this); } - if(infoDAO==null) { + if (infoDAO==null) { infoDAO = new CacheInfoDAO(trans,this); } @@ -205,11 +205,11 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { os.writeInt(data.type); writeString(os,data.description); writeString(os,data.parent); - if(data.attrib==null) { + if (data.attrib==null) { os.writeInt(-1); } else { os.writeInt(data.attrib.size()); - for(Entry<String, String> es : data.attrib(false).entrySet()) { + for (Entry<String, String> es : data.attrib(false).entrySet()) { writeString(os,es.getKey()); writeString(os,es.getValue()); } @@ -227,9 +227,9 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { data.description = readString(is,buff); data.parent = readString(is,buff); int count = is.readInt(); - if(count>0) { + if (count>0) { Map<String, String> da = data.attrib(true); - for(int i=0;i<count;++i) { + for (int i=0;i<count;++i) { da.put(readString(is,buff), readString(is,buff)); } } @@ -241,7 +241,7 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { public Result<Data> create(AuthzTrans trans, Data data) { String ns = data.name; // Ensure Parent is set - if(data.parent==null) { + if (data.parent==null) { return Result.err(Result.ERR_BadData, "Need parent for %s", ns); } @@ -254,7 +254,7 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { getSession(trans).execute(stmt.toString()); //// TEST CODE for Exception // boolean force = true; -// if(force) { +// if (force) { // throw new com.datastax.driver.core.exceptions.NoHostAvailableException(new HashMap<>()); //// throw new com.datastax.driver.core.exceptions.AuthenticationException(new InetSocketAddress(9999),"Sample Message"); // } @@ -272,7 +272,7 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { public Result<Void> update(AuthzTrans trans, Data data) { String ns = data.name; // Ensure Parent is set - if(data.parent==null) { + if (data.parent==null) { return Result.err(Result.ERR_BadData, "Need parent for %s", ns); } @@ -281,26 +281,26 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { try { Map<String, String> localAttr = data.attrib; Result<Map<String, String>> rremoteAttr = readAttribByNS(trans,ns); - if(rremoteAttr.notOK()) { + if (rremoteAttr.notOK()) { return Result.err(rremoteAttr); } // update Attributes String str; - for(Entry<String, String> es : localAttr.entrySet()) { + for (Entry<String, String> es : localAttr.entrySet()) { str = rremoteAttr.value.get(es.getKey()); - if(str==null || !str.equals(es.getValue())) { + if (str==null || !str.equals(es.getValue())) { attribUpdateStmt(stmt, ns, es.getKey(),es.getValue()); } } // No point in deleting... insert overwrites... -// for(Entry<String, String> es : remoteAttr.entrySet()) { +// for (Entry<String, String> es : remoteAttr.entrySet()) { // str = localAttr.get(es.getKey()); -// if(str==null || !str.equals(es.getValue())) { +// if (str==null || !str.equals(es.getValue())) { // attribDeleteStmt(stmt, ns, es.getKey()); // } // } - if(stmt.length()>BEGIN_BATCH.length()) { + if (stmt.length()>BEGIN_BATCH.length()) { stmt.append(APPLY_BATCH); getSession(trans).execute(stmt.toString()); } @@ -320,11 +320,11 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { public Result<List<Data>> read(AuthzTrans trans, Data data) { Result<List<Data>> rld = super.read(trans, data); - if(rld.isOKhasData()) { - for(Data d : rld.value) { + if (rld.isOKhasData()) { + for (Data d : rld.value) { // Note: Map is null at this point, save time/mem by assignment Result<Map<String, String>> rabn = readAttribByNS(trans,d.name); - if(rabn.isOK()) { + if (rabn.isOK()) { d.attrib = rabn.value; } else { return Result.err(rabn); @@ -341,11 +341,11 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { public Result<List<Data>> read(AuthzTrans trans, Object... key) { Result<List<Data>> rld = super.read(trans, key); - if(rld.isOKhasData()) { - for(Data d : rld.value) { + if (rld.isOKhasData()) { + for (Data d : rld.value) { // Note: Map is null at this point, save time/mem by assignment Result<Map<String, String>> rabn = readAttribByNS(trans,d.name); - if(rabn.isOK()) { + if (rabn.isOK()) { d.attrib = rabn.value; } else { return Result.err(rabn); @@ -385,7 +385,7 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { + ns + "';"); - for(Iterator<Row> iter = rs.iterator();iter.hasNext(); ) { + for (Iterator<Row> iter = rs.iterator();iter.hasNext(); ) { Row r = iter.next(); map.put(r.getString(0), r.getString(1)); } @@ -408,7 +408,7 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { + key + "';"); - for(Iterator<Row> iter = rs.iterator();iter.hasNext(); ) { + for (Iterator<Row> iter = rs.iterator();iter.hasNext(); ) { Row r = iter.next(); set.add(r.getString(0)); } @@ -489,7 +489,7 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { private void attribInsertStmts(StringBuilder stmt, Data data) { // INSERT new Attrib - for(Entry<String,String> es : data.attrib(false).entrySet() ) { + for (Entry<String,String> es : data.attrib(false).entrySet() ) { stmt.append(" "); attribInsertStmt(stmt,data.name,es.getKey(),es.getValue()); } @@ -541,7 +541,7 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { hd.target = TABLE; hd.subject = subject ? override[1] : data.name; hd.memo = memo ? override[0] : (data.name + " was " + modified.name() + 'd' ); - if(modified==CRUD.delete) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -549,10 +549,10 @@ public class NsDAO extends CassDAOImpl<AuthzTrans,NsDAO.Data> { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { trans.error().log("Cannot touch CacheInfo"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java index a64c0a94..2beeaf38 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsSplit.java @@ -28,10 +28,10 @@ public class NsSplit { public NsSplit(NsDAO.Data nsd, String child) { this.nsd = nsd; - if(child.startsWith(nsd.name)) { + if (child.startsWith(nsd.name)) { ns = nsd.name; int dot = ns.length(); - if(dot<child.length() && child.charAt(dot)=='.') { + if (dot<child.length() && child.charAt(dot)=='.') { name = child.substring(dot+1); } else { name=""; @@ -48,7 +48,7 @@ public class NsSplit { this.nsd = new NsDAO.Data(); nsd.name = ns; int dot = ns.lastIndexOf('.'); - if(dot>=0) { + if (dot>=0) { nsd.parent = ns.substring(0, dot); } else { nsd.parent = "."; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java index 59e18ae9..e656a555 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/NsType.java @@ -46,8 +46,8 @@ public enum NsType { * @return */ public static NsType fromType(int t) { - for(NsType nst : values()) { - if(t==nst.type) { + for (NsType nst : values()) { + if (t==nst.type) { return nst; } } @@ -60,9 +60,9 @@ public enum NsType { * @return */ public static NsType fromString(String s) { - if(s!=null) { - for(NsType nst : values()) { - if(nst.name().equals(s)) { + if (s!=null) { + for (NsType nst : values()) { + if (nst.name().equals(s)) { return nst; } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java index c02387b1..6e1057b8 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/PermDAO.java @@ -114,13 +114,13 @@ public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> { */ public static Result<Data> decode(AuthzTrans trans, Question q, String p) { String[] ss = Split.splitTrim('|', p,4); - if(ss[2]==null) { + if (ss[2]==null) { return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'"); } Data data = new Data(); - if(ss[3]==null) { // older 3 part encoding must be evaluated for NS + if (ss[3]==null) { // older 3 part encoding must be evaluated for NS Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } data.ns=nss.value.ns; @@ -146,15 +146,15 @@ public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> { */ public static Result<String[]> decodeToArray(AuthzTrans trans, Question q, String p) { String[] ss = Split.splitTrim('|', p,4); - if(ss[2]==null) { + if (ss[2]==null) { return Result.err(Status.ERR_BadData,"Perm Encodings must be separated by '|'"); } - if(ss[3]==null) { // older 3 part encoding must be evaluated for NS + if (ss[3]==null) { // older 3 part encoding must be evaluated for NS ss[3] = ss[2]; ss[2] = ss[1]; Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } ss[1] = nss.value.name; @@ -191,7 +191,7 @@ public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> { String[] s = name.split("\\|"); Result<NsSplit> rdns = q.deriveNsSplit(trans, s[0]); Data rv = new PermDAO.Data(); - if(rdns.isOKhasData()) { + if (rdns.isOKhasData()) { switch(s.length) { case 3: rv.type=s[1]; @@ -482,7 +482,7 @@ public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> { hd.memo = String.format("%sd %s|%s|%s", modified.name(),data.fullType(),data.instance,data.action); } - if(modified==CRUD.delete) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -490,10 +490,10 @@ public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { trans.error().log("Cannot touch CacheInfo"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java index 4489d268..127dd4e2 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/RoleDAO.java @@ -124,9 +124,9 @@ public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> { public static Result<Data> decode(AuthzTrans trans, Question q, String r) { String[] ss = Split.splitTrim('|', r,2); Data data = new Data(); - if(ss[1]==null) { // older 1 part encoding must be evaluated for NS + if (ss[1]==null) { // older 1 part encoding must be evaluated for NS Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } data.ns=nss.value.ns; @@ -161,9 +161,9 @@ public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> { */ public static Result<String[]> decodeToArray(AuthzTrans trans, Question q, String p) { String[] ss = Split.splitTrim('|', p,2); - if(ss[1]==null) { // older 1 part encoding must be evaluated for NS + if (ss[1]==null) { // older 1 part encoding must be evaluated for NS Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } ss[0] = nss.value.ns; @@ -287,7 +287,7 @@ public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> { } public Result<List<Data>> readChildren(AuthzTrans trans, String ns, String role) { - if(role.length()==0 || "*".equals(role)) { + if (role.length()==0 || "*".equals(role)) { return psChildren.read(trans, R_TEXT, new Object[]{ns, FIRST_CHAR, LAST_CHAR}); } else { return psChildren.read(trans, R_TEXT, new Object[]{ns, role+DOT, role+DOT_PLUS_ONE}); @@ -392,7 +392,7 @@ public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> { hd.target = TABLE; hd.subject = subject ? override[1] : data.fullName(); hd.memo = memo ? override[0] : (data.fullName() + " was " + modified.name() + 'd' ); - if(modified==CRUD.delete) { + if (modified==CRUD.delete) { try { hd.reconstruct = data.bytify(); } catch (IOException e) { @@ -400,10 +400,10 @@ public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> { } } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { trans.error().log("Cannot touch CacheInfo for Role"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java index 7b9f7b91..26f9a995 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/cass/UserRoleDAO.java @@ -127,7 +127,7 @@ public class UserRoleDAO extends CassDAOImpl<AuthzTrans,UserRoleDAO.Data> { public boolean role(AuthzTrans trans, Question ques, String role) { this.role = role; Result<NsSplit> rnss = ques.deriveNsSplit(trans, role); - if(rnss.isOKhasData()) { + if (rnss.isOKhasData()) { ns = rnss.value.ns; rname = rnss.value.name; return true; @@ -304,15 +304,15 @@ public class UserRoleDAO extends CassDAOImpl<AuthzTrans,UserRoleDAO.Data> { : "n/a"; } - if(historyDAO.create(trans, hd).status!=Status.OK) { + if (historyDAO.create(trans, hd).status!=Status.OK) { trans.error().log("Cannot log to History"); } - if(historyDAO.create(trans, hdRole).status!=Status.OK) { + if (historyDAO.create(trans, hdRole).status!=Status.OK) { trans.error().log("Cannot log to History"); } // uses User as Segment - if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { + if (infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) { trans.error().log("Cannot touch CacheInfo"); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java index f0a59582..0bc23c92 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/CassExecutor.java @@ -47,7 +47,7 @@ public class CassExecutor implements Executor { @Override public boolean inRole(String name) { Result<NsSplit> nss = q.deriveNsSplit(trans, name); - if(nss.notOK())return false; + if (nss.notOK())return false; return q.roleDAO.read(trans, nss.value.ns,nss.value.name).isOKhasData(); } @@ -58,7 +58,7 @@ public class CassExecutor implements Executor { @Override public String namespace() throws Exception { Result<Data> res = q.validNSOfDomain(trans,trans.user()); - if(res.isOK()) { + if (res.isOK()) { String user[] = trans.user().split("\\."); return user[user.length-1] + '.' + user[user.length-2]; } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java index f3aae2ec..f440a8cd 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Function.java @@ -81,9 +81,9 @@ public class Function { * @return */ public static FUTURE_OP toFO(String value) { - if(value!=null) { - for(FUTURE_OP fo : values()) { - if(fo.name().equals(value)){ + if (value!=null) { + for (FUTURE_OP fo : values()) { + if (fo.name().equals(value)){ return fo; } } @@ -194,16 +194,16 @@ public class Function { String reason; if (orgUser == null) { return Result.err(Status.ERR_Policy,"%s is not a valid user at %s",u,org.getName()); - } else if((reason=orgUser.mayOwn())!=null) { + } else if ((reason=orgUser.mayOwn())!=null) { if (org.isTestEnv()) { String reason2; - if((reason2=org.validate(trans, Policy.AS_RESPONSIBLE,new CassExecutor(trans, this), u))!=null) { // can masquerade as responsible + if ((reason2=org.validate(trans, Policy.AS_RESPONSIBLE,new CassExecutor(trans, this), u))!=null) { // can masquerade as responsible trans.debug().log(reason2); return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,orgUser.fullName(),orgUser.id(),namespace.name,reason); } // a null means ok } else { - if(orgUser.isFound()) { + if (orgUser.isFound()) { return Result.err(Status.ERR_Policy,CANNOT_BE_THE_OWNER_OF_A_NAMESPACE,orgUser.fullName(),orgUser.id(),namespace.name, reason); } else { return Result.err(Status.ERR_Policy,u + " is an invalid Identity"); @@ -267,7 +267,7 @@ public class Function { // or helpful for Operations folks.. // Admins can be empty, because they can be changed by lower level // NSs - // if(ns.admin(false).isEmpty()) { + // if (ns.admin(false).isEmpty()) { // ns.admin(true).add(user); // } if (namespace.admin != null) { @@ -334,9 +334,9 @@ public class Function { for (RoleDAO.Data rdd : rrdc.value) { // Remove old Role from Perms, save them off List<PermDAO.Data> lpdd = new ArrayList<>(); - for(String p : rdd.perms(false)) { + for (String p : rdd.perms(false)) { Result<PermDAO.Data> rpdd = PermDAO.Data.decode(trans,q,p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { PermDAO.Data pdd = rpdd.value; lpdd.add(pdd); q.permDAO.delRole(trans, pdd, rdd); @@ -358,13 +358,13 @@ public class Function { // "create" per se if ((rq = q.roleDAO.create(trans, rdd)).isOK()) { // Put Role back into Perm, with correct info - for(PermDAO.Data pdd : lpdd) { + for (PermDAO.Data pdd : lpdd) { q.permDAO.addRole(trans, pdd, rdd); } // Change data for User Roles Result<List<UserRoleDAO.Data>> rurd = q.userRoleDAO.readByRole(trans, rdd.fullName()); - if(rurd.isOKhasData()) { - for(UserRoleDAO.Data urd : rurd.value) { + if (rurd.isOKhasData()) { + for (UserRoleDAO.Data urd : rurd.value) { urd.ns = rdd.ns; urd.rname = rdd.name; q.userRoleDAO.update(trans, urd); @@ -389,9 +389,9 @@ public class Function { // Remove old Perm from Roles, save them off List<RoleDAO.Data> lrdd = new ArrayList<>(); - for(String rl : pdd.roles(false)) { + for (String rl : pdd.roles(false)) { Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,q,rl); - if(rrdd.isOKhasData()) { + if (rrdd.isOKhasData()) { RoleDAO.Data rdd = rrdd.value; lrdd.add(rdd); q.roleDAO.delPerm(trans, rdd, pdd); @@ -408,7 +408,7 @@ public class Function { .substring(targetNameDot) : ""; if ((rq = q.permDAO.create(trans, pdd)).isOK()) { // Put Role back into Perm, with correct info - for(RoleDAO.Data rdd : lrdd) { + for (RoleDAO.Data rdd : lrdd) { q.roleDAO.addPerm(trans, rdd, pdd); } @@ -698,7 +698,7 @@ public class Function { } else { if (org.isTestEnv()) { String reason2; - if((reason2 = org.validate(trans, Policy.AS_RESPONSIBLE, new CassExecutor(trans, this), id))==null) { + if ((reason2 = org.validate(trans, Policy.AS_RESPONSIBLE, new CassExecutor(trans, this), id))==null) { return Result.ok(); } else { trans.debug().log(reason2); @@ -726,7 +726,7 @@ public class Function { rq = q.mayUser(trans, trans.user(), rq.value, Access.write); if (rq.notOK()) { Result<List<UserRoleDAO.Data>> ruinr = q.userRoleDAO.readUserInRole(trans, trans.user(),ns+".owner"); - if(!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { + if (!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { return Result.err(rq); } } @@ -748,7 +748,7 @@ public class Function { "%s is not a valid %s Credential", user, org.getName()); } //TODO find out how to make sure good ALTERNATE OAUTH DOMAIN USER -// } else if(user.endsWith(ALTERNATE OAUTH DOMAIN)) { +// } else if (user.endsWith(ALTERNATE OAUTH DOMAIN)) { // return Result.ok(); } else { Result<List<CredDAO.Data>> cdr = q.credDAO.readID(trans, user); @@ -794,7 +794,7 @@ public class Function { if (rq.notOK()) { // Even though not a "writer", Owners still determine who gets to be an Admin Result<List<UserRoleDAO.Data>> ruinr = q.userRoleDAO.readUserInRole(trans, trans.user(),ns+".owner"); - if(!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { + if (!(ruinr.isOKhasData() && ruinr.value.get(0).expires.after(new Date()))) { return Result.err(rq); } } @@ -827,9 +827,9 @@ public class Function { // Remove old Perm from Roles, save them off List<RoleDAO.Data> lrdd = new ArrayList<>(); - for(String rl : pdd.roles(false)) { + for (String rl : pdd.roles(false)) { Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,q,rl); - if(rrdd.isOKhasData()) { + if (rrdd.isOKhasData()) { RoleDAO.Data rdd = rrdd.value; lrdd.add(rdd); q.roleDAO.delPerm(trans, rdd, pdd); @@ -846,7 +846,7 @@ public class Function { // Use direct Create/Delete, because switching namespaces if ((pd = q.permDAO.create(trans, pdd)).isOK()) { // Put Role back into Perm, with correct info - for(RoleDAO.Data rdd : lrdd) { + for (RoleDAO.Data rdd : lrdd) { q.roleDAO.addPerm(trans, rdd, pdd); } @@ -892,9 +892,9 @@ public class Function { } // Remove old Role from Perms, save them off List<PermDAO.Data> lpdd = new ArrayList<>(); - for(String p : rdd.perms(false)) { + for (String p : rdd.perms(false)) { Result<PermDAO.Data> rpdd = PermDAO.Data.decode(trans,q,p); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { PermDAO.Data pdd = rpdd.value; lpdd.add(pdd); q.permDAO.delRole(trans, pdd, rdd); @@ -912,7 +912,7 @@ public class Function { // Use direct Create/Delete, because switching namespaces if ((rd = q.roleDAO.create(trans, rdd)).isOK()) { // Put Role back into Perm, with correct info - for(PermDAO.Data pdd : lpdd) { + for (PermDAO.Data pdd : lpdd) { q.permDAO.addRole(trans, pdd, rdd); } @@ -973,7 +973,7 @@ public class Function { // For each Role for (String role : roles = perm.roles(true)) { Result<RoleDAO.Data> rdd = RoleDAO.Data.decode(trans,q,role); - if(rdd.isOKhasData()) { + if (rdd.isOKhasData()) { RoleDAO.Data rd = rdd.value; if (!fromApproval) { // May User write to the Role in question. @@ -1038,7 +1038,7 @@ public class Function { for (String role : fullperm.roles) { Result<Void> rv = null; Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, q, role); - if(rrdd.isOKhasData()) { + if (rrdd.isOKhasData()) { trans.debug().log("Removing", role, "from", fullperm, "on Perm Delete"); if ((rv = q.roleDAO.delPerm(trans, rrdd.value, fullperm)).notOK()) { if (rv.notOK()) { @@ -1131,19 +1131,19 @@ public class Function { if (!fromApproval) { Result<NsDAO.Data> rRoleCo = q.deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - if(rRoleCo.notOK()) { + if (rRoleCo.notOK()) { return Result.err(rRoleCo); } Result<NsDAO.Data> rPermCo = q.deriveFirstNsForType(trans, pd.ns, NsType.COMPANY); - if(rPermCo.notOK()) { + if (rPermCo.notOK()) { return Result.err(rPermCo); } // Not from same company - if(!rRoleCo.value.name.equals(rPermCo.value.name)) { + if (!rRoleCo.value.name.equals(rPermCo.value.name)) { Result<Data> r; // Only grant if User ALSO has Write ability in Other Company - if((r = q.mayUser(trans, user, role, Access.write)).notOK()) { + if ((r = q.mayUser(trans, user, role, Access.write)).notOK()) { return Result.err(r); } } @@ -1279,7 +1279,7 @@ public class Function { break; } } - if(!notFound) { + if (!notFound) { break; } } @@ -1343,14 +1343,14 @@ public class Function { */ public Result<Void> addUserRole(AuthzTrans trans,UserRoleDAO.Data urData) { Result<Void> rv; - if(Question.ADMIN.equals(urData.rname)) { + if (Question.ADMIN.equals(urData.rname)) { rv = mayAddAdmin(trans, urData.ns, urData.user); - } else if(Question.OWNER.equals(urData.rname)) { + } else if (Question.OWNER.equals(urData.rname)) { rv = mayAddOwner(trans, urData.ns, urData.user); } else { rv = checkValidID(trans, new Date(), urData.user); } - if(rv.notOK()) { + if (rv.notOK()) { return rv; } @@ -1378,7 +1378,7 @@ public class Function { public Result<Void> addUserRole(AuthzTrans trans, String user, String ns, String rname) { try { - if(trans.org().getIdentity(trans, user)==null) { + if (trans.org().getIdentity(trans, user)==null) { return Result.err(Result.ERR_BadData,user+" is an Invalid Identity for " + trans.org().getName()); } } catch (OrganizationException e) { @@ -1476,9 +1476,9 @@ public class Function { Result<List<UserRoleDAO.Data>> rrbr = q.userRoleDAO .readByRole(trans, nsd.name + Question.DOT_OWNER); if (rrbr.isOKhasData()) { - for(UserRoleDAO.Data urd : rrbr.value) { + for (UserRoleDAO.Data urd : rrbr.value) { Identity owner = org.getIdentity(trans, urd.user); - if(owner==null) { + if (owner==null) { return Result.err(Result.ERR_NotFound,urd.user + " is not a Valid Owner of " + nsd.name); } else { owners.add(owner); @@ -1487,7 +1487,7 @@ public class Function { } } - if(owners.isEmpty()) { + if (owners.isEmpty()) { return Result.err(Result.ERR_NotFound,"No Owners found for " + nsd.name); } @@ -1501,17 +1501,17 @@ public class Function { final UUID ticket = fr.value.id; sb.append(", Approvals: "); Boolean first[] = new Boolean[]{true}; - if(op!=FUTURE_OP.A) { + if (op!=FUTURE_OP.A) { for (Identity u : approvers) { Result<ApprovalDAO.Data> r = addIdentity(trans,sb,first,user,data.memo,op,u,ticket,org.getApproverType()); - if(r.notOK()) { + if (r.notOK()) { return Result.err(r); } } } for (Identity u : owners) { Result<ApprovalDAO.Data> r = addIdentity(trans,sb,first,user,data.memo,op,u,ticket,"owner"); - if(r.notOK()) { + if (r.notOK()) { return Result.err(r); } } @@ -1534,7 +1534,7 @@ public class Function { @Override public UserRoleDAO.Data get(AuthzTrans trans, Object ... keys) { Result<List<UserRoleDAO.Data>> r = q.userRoleDAO.read(trans, keys); - if(r.isOKhasData()) { + if (r.isOKhasData()) { return r.value.get(0); } else { return null; @@ -1556,18 +1556,18 @@ public class Function { public Result<OP_STATUS> performFutureOp(final AuthzTrans trans, FUTURE_OP fop, FutureDAO.Data curr, Lookup<List<ApprovalDAO.Data>> la, Lookup<UserRoleDAO.Data> lur) { // Pre-Evaluate if ReApproval is already done. UserRoleDAO.Data urdd = null; - if(fop.equals(FUTURE_OP.A) && curr.target.equals(FOP_USER_ROLE) && curr.construct!=null) { + if (fop.equals(FUTURE_OP.A) && curr.target.equals(FOP_USER_ROLE) && curr.construct!=null) { try { // Get Expected UserRole from Future urdd = new UserRoleDAO.Data(); urdd.reconstitute(curr.construct); // Get Current UserRole from lookup UserRoleDAO.Data lurdd = lur.get(trans, urdd.user,urdd.role); - if(lurdd==null) { + if (lurdd==null) { q.futureDAO.delete(trans, curr, false); return OP_STATUS.RL; } else { - if(curr.expires.compareTo(lurdd.expires)<0) { + if (curr.expires.compareTo(lurdd.expires)<0) { q.futureDAO.delete(trans, curr, false); return OP_STATUS.RL; } @@ -1579,21 +1579,21 @@ public class Function { boolean aDenial = false; int cntSuper=0, appSuper=0,cntOwner=0, appOwner=0; - for(ApprovalDAO.Data add : la.get(trans)) { + for (ApprovalDAO.Data add : la.get(trans)) { switch(add.status) { case "approved": - if("owner".equals(add.type)) { + if ("owner".equals(add.type)) { ++cntOwner; ++appOwner; - } else if("supervisor".equals(add.type)) { + } else if ("supervisor".equals(add.type)) { ++cntSuper; ++appSuper; } break; case "pending": - if("owner".equals(add.type)) { + if ("owner".equals(add.type)) { ++cntOwner; - } else if("supervisor".equals(add.type)) { + } else if ("supervisor".equals(add.type)) { ++cntSuper; } break; @@ -1604,18 +1604,18 @@ public class Function { } Result<OP_STATUS> ros=null; - if(aDenial) { + if (aDenial) { // Note: Denial will be Audit-logged. // for (ApprovalDAO.Data ad : allApprovalsForTicket.value) { // q.approvalDAO.delete(trans, ad, false); // } ros = OP_STATUS.RD; - if(q.futureDAO.delete(trans, curr, false).notOK()) { + if (q.futureDAO.delete(trans, curr, false).notOK()) { trans.info().printf("Future %s could not be deleted", curr.id.toString()); } else { if (FOP_USER_ROLE.equalsIgnoreCase(curr.target)) { // A Denial means we must remove UserRole - if(fop.equals(FUTURE_OP.U) || fop.equals(FUTURE_OP.A)) { + if (fop.equals(FUTURE_OP.U) || fop.equals(FUTURE_OP.A)) { UserRoleDAO.Data data = new UserRoleDAO.Data(); try { data.reconstitute(curr.construct); @@ -1631,7 +1631,7 @@ public class Function { // Decision: If not Denied, and at least owner, if exists, and at least one Super, if exists boolean goDecision = (cntOwner>0?appOwner>0:true) && (cntSuper>0?appSuper>0:true); - if(goDecision) { + if (goDecision) { // should check if any other pendings before performing // actions try { @@ -1684,7 +1684,7 @@ public class Function { default: } } else if (FOP_USER_ROLE.equalsIgnoreCase(curr.target)) { - if(urdd==null) { + if (urdd==null) { urdd = new UserRoleDAO.Data(); urdd.reconstitute(curr.construct); } @@ -1737,7 +1737,7 @@ public class Function { } q.futureDAO.delete(trans, curr, false); } // end for goDecision - if(ros==null) { + if (ros==null) { //return Result.err(Status.ACC_Future, "Full Approvals not obtained: No action taken"); ros = OP_STATUS.RP; } @@ -1747,7 +1747,7 @@ public class Function { // Convenience method for setting OPSTatus Results private Result<OP_STATUS> set(Result<OP_STATUS> rs, Result<?> orig) { - if(orig.isOK()) { + if (orig.isOK()) { return rs; } else { return Result.err(orig); @@ -1767,8 +1767,8 @@ public class Function { ad.operation = op.name(); // Note ad.updated is created in System Result<ApprovalDAO.Data> r = q.approvalDAO.create(trans,ad); - if(r.isOK()) { - if(first[0]) { + if (r.isOK()) { + if (first[0]) { first[0] = false; } else { sb.append(", "); diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java index 6bb440ad..98621457 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/PermLookup.java @@ -75,17 +75,17 @@ class PermLookup { } public Result<List<UserRoleDAO.Data>> getUserRoles() { - if(userRoles==null) { + if (userRoles==null) { userRoles = q.userRoleDAO.readByUser(trans,user); - if(userRoles.isOKhasData()) { + if (userRoles.isOKhasData()) { List<UserRoleDAO.Data> lurdd = new ArrayList<>(); Date now = new Date(); - for(UserRoleDAO.Data urdd : userRoles.value) { - if(urdd.expires.after(now)) { // Remove Expired + for (UserRoleDAO.Data urdd : userRoles.value) { + if (urdd.expires.after(now)) { // Remove Expired lurdd.add(urdd); } } - if(lurdd.size()==0) { + if (lurdd.size()==0) { return userRoles = Result.err(Status.ERR_UserNotFound, "%s not found or not associated with any Roles: ", user); @@ -101,18 +101,18 @@ class PermLookup { } public Result<List<RoleDAO.Data>> getRoles() { - if(roles==null) { + if (roles==null) { Result<List<UserRoleDAO.Data>> rur = getUserRoles(); - if(rur.isOK()) { + if (rur.isOK()) { List<RoleDAO.Data> lrdd = new ArrayList<>(); for (UserRoleDAO.Data urdata : rur.value) { // Gather all permissions from all Roles - if(urdata.ns==null || urdata.rname==null) { + if (urdata.ns==null || urdata.rname==null) { return Result.err(Status.ERR_BadData,"DB Content Error: nulls in User Role %s %s", urdata.user,urdata.role); } else { Result<List<RoleDAO.Data>> rlrd = q.roleDAO.read( trans, urdata.ns, urdata.rname); - if(rlrd.isOK()) { + if (rlrd.isOK()) { lrdd.addAll(rlrd.value); } } @@ -127,7 +127,7 @@ class PermLookup { } public Result<Set<String>> getPermNames() { - if(permNames==null) { + if (permNames==null) { Result<List<RoleDAO.Data>> rlrd = getRoles(); if (rlrd.isOK()) { Set<String> pns = new TreeSet<>(); @@ -144,16 +144,16 @@ class PermLookup { } public Result<List<PermDAO.Data>> getPerms(boolean lookup) { - if(perms==null) { + if (perms==null) { // Note: It should be ok for a Valid user to have no permissions - // Jonathan 8/12/2013 Result<Set<String>> rss = getPermNames(); - if(rss.isOK()) { + if (rss.isOK()) { List<PermDAO.Data> lpdd = new ArrayList<>(); for (String perm : rss.value) { - if(lookup) { + if (lookup) { Result<String[]> ap = PermDAO.Data.decodeToArray(trans, q, perm); - if(ap.isOK()) { + if (ap.isOK()) { Result<List<PermDAO.Data>> rlpd = q.permDAO.read(perm,trans,ap.value); if (rlpd.isOKhasData()) { diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java index 152412a2..e63bc52a 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/dao/hl/Question.java @@ -166,17 +166,17 @@ public class Question { // Only want to aggressively cleanse User related Caches... The others, // just normal refresh - if(startClean) { + if (startClean) { CachedDAO.startCleansing(trans.env(), credDAO, userRoleDAO); CachedDAO.startRefresh(trans.env(), cacheInfoDAO); } // Set a Timer to Check Caches to send messages for Caching changes - if(specialLogSlot==null) { + if (specialLogSlot==null) { specialLogSlot = trans.slot(AuthzTransFilter.SPECIAL_LOG_SLOT); } - if(transIDSlot==null) { + if (transIDSlot==null) { transIDSlot = trans.slot(AuthzTransFilter.TRANS_ID_SLOT); } @@ -226,25 +226,25 @@ public class Question { public Result<List<PermDAO.Data>> getPermsByUserFromRolesFilter(AuthzTrans trans, String user, String forUser) { PermLookup plUser = PermLookup.get(trans, this, user); Result<Set<String>> plPermNames = plUser.getPermNames(); - if(plPermNames.notOK()) { + if (plPermNames.notOK()) { return Result.err(plPermNames); } Set<String> nss; - if(forUser.equals(user)) { + if (forUser.equals(user)) { nss = null; } else { // Setup a TreeSet to check on Namespaces to nss = new TreeSet<>(); PermLookup fUser = PermLookup.get(trans, this, forUser); Result<Set<String>> forUpn = fUser.getPermNames(); - if(forUpn.notOK()) { + if (forUpn.notOK()) { return Result.err(forUpn); } - for(String pn : forUpn.value) { + for (String pn : forUpn.value) { Result<String[]> decoded = PermDAO.Data.decodeToArray(trans, this, pn); - if(decoded.isOKhasData()) { + if (decoded.isOKhasData()) { nss.add(decoded.value[0]); } else { trans.error().log(pn,", derived from a Role, is invalid:",decoded.errorString()); @@ -255,11 +255,11 @@ public class Question { List<PermDAO.Data> rlpUser = new ArrayList<>(); Result<PermDAO.Data> rpdd; PermDAO.Data pdd; - for(String pn : plPermNames.value) { + for (String pn : plPermNames.value) { rpdd = PermDAO.Data.decode(trans, this, pn); - if(rpdd.isOKhasData()) { + if (rpdd.isOKhasData()) { pdd=rpdd.value; - if(nss==null || nss.contains(pdd.ns)) { + if (nss==null || nss.contains(pdd.ns)) { rlpUser.add(pdd); } } else { @@ -314,7 +314,7 @@ public class Question { return Result.err(pr); } - if(lookup) { + if (lookup) { Result<List<PermDAO.Data>> rlpd = permDAO.read(trans, pr.value); if (rlpd.isOKhasData()) { for (PermDAO.Data pData : rlpd.value) { @@ -368,7 +368,7 @@ public class Question { return Result.ok(r.value.get(0)); } else { int dot; - if(child==null) { + if (child==null) { return Result.err(Status.ERR_NsNotFound, "No Namespace"); } else { dot = child.lastIndexOf('.'); @@ -384,12 +384,12 @@ public class Question { public Result<NsDAO.Data> deriveFirstNsForType(AuthzTrans trans, String str, NsType type) { NsDAO.Data nsd; - for(String lookup = str;!".".equals(lookup) && lookup!=null;) { + for (String lookup = str;!".".equals(lookup) && lookup!=null;) { Result<List<NsDAO.Data>> rld = nsDAO.read(trans, lookup); - if(rld.isOKhasData()) { + if (rld.isOKhasData()) { nsd=rld.value.get(0); lookup = nsd.parent; - if(type.type == nsd.type) { + if (type.type == nsd.type) { return Result.ok(nsd); } } else { @@ -455,13 +455,13 @@ public class Question { public Result<NsDAO.Data> validNSOfDomain(AuthzTrans trans, String id) { // Take domain, reverse order, and check on NS String ns; - if(id.indexOf('@')<0) { // it's already an ns, not an ID + if (id.indexOf('@')<0) { // it's already an ns, not an ID ns = id; } else { ns = domain2ns(id); } if (ns.length() > 0) { - if(!trans.org().getDomain().equals(ns)) { + if (!trans.org().getDomain().equals(ns)) { Result<List<NsDAO.Data>> rlnsd = nsDAO.read(trans, ns); if (rlnsd.isOKhasData()) { return Result.ok(rlnsd.value.get(0)); @@ -490,7 +490,7 @@ public class Question { Result<NsDAO.Data> rv = mayUserVirtueOfNS(trans, user, ndd, ":" + ndd.name + ":ns", access.name()); if (rv.isOK()) { return rv; - } else if(rv.status==Result.ERR_Backend) { + } else if (rv.status==Result.ERR_Backend) { return Result.err(rv); } else { return Result.err(Status.ERR_Denied, "[%s] may not %s in NS [%s]", @@ -532,7 +532,7 @@ public class Question { + rdd.ns + roleInst, access.name()); if (rnsd.isOK()) { return rnsd; - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } @@ -543,7 +543,7 @@ public class Question { ":" + rdd.ns + ":ns", access.name()); if (rv.isOK()) { return rv; - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } else { return Result.err(Status.ERR_Denied, "[%s] may not %s Role [%s]", @@ -582,7 +582,7 @@ public class Question { Result<NsDAO.Data> rnsd = mayUserVirtueOfNS(trans, user, ndd, ":" + pdd.ns + permInst, access.name()); if (rnsd.isOK()) { return rnsd; - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } @@ -603,7 +603,7 @@ public class Question { public Result<Void> mayUser(AuthzTrans trans, DelegateDAO.Data dd, Access access) { try { Result<NsDAO.Data> rnsd = deriveNs(trans, domain2ns(trans.user())); - if(rnsd.isOKhasData() && mayUserVirtueOfNS(trans,trans.user(),rnsd.value, ":" + rnsd.value.name + ":ns", access.name()).isOK()) { + if (rnsd.isOKhasData() && mayUserVirtueOfNS(trans,trans.user(),rnsd.value, ":" + rnsd.value.name + ":ns", access.name()).isOK()) { return Result.ok(); } boolean isUser = trans.user().equals(dd.user); @@ -663,7 +663,7 @@ public class Question { Result<List<UserRoleDAO.Data>> rurd; if ((rurd = userRoleDAO.readUserInRole(trans, user, ns+DOT_ADMIN)).isOKhasData()) { return Result.ok(nsd); - } else if(rurd.status==Result.ERR_Backend) { + } else if (rurd.status==Result.ERR_Backend) { return Result.err(rurd); } @@ -679,12 +679,12 @@ public class Question { Result<NsDAO.Data> rnsd = deriveNs(trans, ns.substring(0, dot)); if (rnsd.isOK()) { rnsd = mayUserVirtueOfNS(trans, user, rnsd.value, ns_and_type,access); - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } if (rnsd.isOK()) { return Result.ok(nsd); - } else if(rnsd.status==Result.ERR_Backend) { + } else if (rnsd.status==Result.ERR_Backend) { return Result.err(rnsd); } } @@ -712,7 +712,7 @@ public class Question { if (ns.equals(pd.ns)) { if (type.equals(pd.type)) { if (PermEval.evalInstance(pd.instance, instance)) { - if(PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action + if (PermEval.evalAction(pd.action, action)) { // don't return action here, might miss other action return true; } } @@ -733,7 +733,7 @@ public class Question { } Result<Date> rv = null; - if(result.isOK()) { + if (result.isOK()) { if (result.isEmpty()) { rv = Result.err(Status.ERR_UserNotFound, user); if (willSpecialLog(trans,user)) { @@ -743,14 +743,14 @@ public class Question { Date now = new Date();//long now = System.currentTimeMillis(); // Bug noticed 6/22. Sorting on the result can cause Concurrency Issues. List<CredDAO.Data> cddl; - if(result.value.size() > 1) { + if (result.value.size() > 1) { cddl = new ArrayList<>(result.value.size()); - for(CredDAO.Data old : result.value) { - if(old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) { + for (CredDAO.Data old : result.value) { + if (old.type==CredDAO.BASIC_AUTH || old.type==CredDAO.BASIC_AUTH_SHA256) { cddl.add(old); } } - if(cddl.size()>1) { + if (cddl.size()>1) { Collections.sort(cddl,new Comparator<CredDAO.Data>() { @Override public int compare(org.onap.aaf.auth.dao.cass.CredDAO.Data a, @@ -766,7 +766,7 @@ public class Question { Date expired = null; StringBuilder debug = willSpecialLog(trans,user)?new StringBuilder():null; for (CredDAO.Data cdd : cddl) { - if(!cdd.id.equals(user)) { + if (!cdd.id.equals(user)) { trans.error().log("doesUserCredMatch DB call does not match for user: " + user); } if (cdd.expires.after(now)) { @@ -776,7 +776,7 @@ public class Question { switch(cdd.type) { case CredDAO.BASIC_AUTH: byte[] md5=Hash.hashMD5(cred); - if(Hash.compareTo(md5,dbcred)==0) { + if (Hash.compareTo(md5,dbcred)==0) { checkLessThanDays(trans,7,now,cdd); return Result.ok(cdd.expires); } else if (debug!=null) { @@ -789,7 +789,7 @@ public class Question { bb.put(cred); byte[] hash = Hash.hashSHA256(bb.array()); - if(Hash.compareTo(hash,dbcred)==0) { + if (Hash.compareTo(hash,dbcred)==0) { checkLessThanDays(trans,7,now,cdd); return Result.ok(cdd.expires); } else if (debug!=null) { @@ -803,17 +803,17 @@ public class Question { trans.error().log(e); } } else { - if(expired==null || expired.before(cdd.expires)) { + if (expired==null || expired.before(cdd.expires)) { expired = cdd.expires; } } } // end for each - if(debug==null) { + if (debug==null) { trans.audit().printf("No cred matches ip=%s, user=%s\n",trans.ip(),user); } else { trans.audit().printf("No cred matches ip=%s, user=%s %s\n",trans.ip(),user,debug.toString()); } - if(expired!=null) { + if (expired!=null) { // Note: this is only returned if there are no good Credentials rv = Result.err(Status.ERR_Security, "Credentials %s from %s expired %s",trans.user(), trans.ip(), Chrono.dateTime(expired)); @@ -840,7 +840,7 @@ public class Question { private void checkLessThanDays(AuthzTrans trans, int days, Date now, Data cdd) { long close = now.getTime() + (days * 86400000); long cexp=cdd.expires.getTime(); - if(cexp<close) { + if (cexp<close) { int daysLeft = days-(int)((close-cexp)/86400000); trans.audit().printf("user=%s,ip=%s,expires=%s,days=%d,msg=\"Password expires in less than %d day%s\"", cdd.id,trans.ip(),Chrono.dateOnlyStamp(cdd.expires),daysLeft, daysLeft,daysLeft==1?"":"s"); @@ -849,7 +849,7 @@ public class Question { public Result<CredDAO.Data> userCredSetup(AuthzTrans trans, CredDAO.Data cred) { - if(cred.type==CredDAO.RAW) { + if (cred.type==CredDAO.RAW) { TimeTaken tt = trans.start("Hash Cred", Env.SUB); try { cred.type = CredDAO.BASIC_AUTH_SHA256; @@ -935,32 +935,32 @@ public class Question { if (all || NsDAO.TABLE.equals(cname)) { int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, NsDAO.TABLE,i);} + for (int i: seg) {cacheClear(trans, NsDAO.TABLE,i);} rv = cacheInfoDAO.touch(trans, NsDAO.TABLE, seg); } if (all || PermDAO.TABLE.equals(cname)) { int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, PermDAO.TABLE,i);} + for (int i: seg) {cacheClear(trans, PermDAO.TABLE,i);} rv = cacheInfoDAO.touch(trans, PermDAO.TABLE,seg); } if (all || RoleDAO.TABLE.equals(cname)) { int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, RoleDAO.TABLE,i);} + for (int i: seg) {cacheClear(trans, RoleDAO.TABLE,i);} rv = cacheInfoDAO.touch(trans, RoleDAO.TABLE,seg); } if (all || UserRoleDAO.TABLE.equals(cname)) { int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, UserRoleDAO.TABLE,i);} + for (int i: seg) {cacheClear(trans, UserRoleDAO.TABLE,i);} rv = cacheInfoDAO.touch(trans, UserRoleDAO.TABLE,seg); } if (all || CredDAO.TABLE.equals(cname)) { int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, CredDAO.TABLE,i);} + for (int i: seg) {cacheClear(trans, CredDAO.TABLE,i);} rv = cacheInfoDAO.touch(trans, CredDAO.TABLE,seg); } if (all || CertDAO.TABLE.equals(cname)) { int seg[] = series(NsDAO.CACHE_SEG); - for(int i: seg) {cacheClear(trans, CertDAO.TABLE,i);} + for (int i: seg) {cacheClear(trans, CertDAO.TABLE,i);} rv = cacheInfoDAO.touch(trans, CertDAO.TABLE,seg); } @@ -999,11 +999,11 @@ public class Question { public boolean isDelegated(AuthzTrans trans, String user, String approver, Map<String,Result<List<DelegateDAO.Data>>> rldd ) { Result<List<DelegateDAO.Data>> userDelegatedFor = rldd.get(user); - if(userDelegatedFor==null) { + if (userDelegatedFor==null) { userDelegatedFor=delegateDAO.readByDelegate(trans, user); rldd.put(user, userDelegatedFor); } - if(userDelegatedFor.isOKhasData()) { + if (userDelegatedFor.isOKhasData()) { for (DelegateDAO.Data curr : userDelegatedFor.value) { if (curr.user.equals(approver) && curr.delegate.equals(user) && curr.expires.after(new Date())) { @@ -1016,8 +1016,8 @@ public class Question { public static boolean willSpecialLog(AuthzTrans trans, String user) { Boolean b = trans.get(specialLogSlot, null); - if(b==null) { // we haven't evaluated in this trans for Special Log yet - if(specialLog==null) { + if (b==null) { // we haven't evaluated in this trans for Special Log yet + if (specialLog==null) { return false; } else { b = specialLog.contains(user); @@ -1042,21 +1042,21 @@ public class Question { specialLog = new HashSet<>(); } boolean rc = specialLog.add(id); - if(rc) { + if (rc) { trans.trace().printf("Trace on for %s requested by %s",id,trans.user()); } return rc; } public static synchronized boolean specialLogOff(AuthzTrans trans, String id) { - if(specialLog==null) { + if (specialLog==null) { return false; } boolean rv = specialLog.remove(id); if (specialLog.isEmpty()) { specialLog = null; } - if(rv) { + if (rv) { trans.trace().printf("Trace off for %s requested by %s",id,trans.user()); } return rv; @@ -1086,8 +1086,8 @@ public class Question { public boolean isAdmin(AuthzTrans trans, String user, String ns) { Date now = new Date(); Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN); - if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ - if(urdd.expires.after(now)) { + if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){ + if (urdd.expires.after(now)) { return true; } }}; @@ -1097,8 +1097,8 @@ public class Question { public boolean isOwner(AuthzTrans trans, String user, String ns) { Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_OWNER); Date now = new Date(); - if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ - if(urdd.expires.after(now)) { + if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){ + if (urdd.expires.after(now)) { return true; } }}; @@ -1109,8 +1109,8 @@ public class Question { Result<List<UserRoleDAO.Data>> rur = userRoleDAO.readByRole(trans,ns+DOT_OWNER); Date now = new Date(); int count = 0; - if(rur.isOKhasData()) {for(UserRoleDAO.Data urdd : rur.value){ - if(urdd.expires.after(now)) { + if (rur.isOKhasData()) {for (UserRoleDAO.Data urdd : rur.value){ + if (urdd.expires.after(now)) { ++count; } }}; @@ -1129,7 +1129,7 @@ public class Question { byte[] from = name.getBytes(); StringBuilder sb = new StringBuilder(); byte f; - for(int i=0;i<from.length;++i) { + for (int i=0;i<from.length;++i) { f=(byte)(from[i]); // printables; sb.append((char)((f>>4)+0x61)); sb.append((char)((f&0x0F)+0x61)); @@ -1141,7 +1141,7 @@ public class Question { byte[] from = name.getBytes(); StringBuilder sb = new StringBuilder(); char c; - for(int i=0;i<from.length;++i) { + for (int i=0;i<from.length;++i) { c = (char)((from[i]-0x61)<<4); c |= (from[++i]-0x61); sb.append(c); diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLocator.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLocator.java index 1fb050b8..93fab977 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLocator.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLocator.java @@ -57,13 +57,13 @@ public class DirectAAFLocator extends AbsAAFLocator<AuthzTrans> { super(env.access(), name, 1000L /* Don't hit DB more than once a second */); this.env = env; this.ldao = ldao; - if(version!=null) { + if (version!=null) { try { String[] v = Split.split('.',version); - if(v.length>0) {major = Integer.parseInt(v[0]);} - if(v.length>1) {minor = Integer.parseInt(v[1]);} - if(v.length>2) {patch = Integer.parseInt(v[2]);} - if(v.length>3) {pkg = Integer.parseInt(v[3]);} + if (v.length>0) {major = Integer.parseInt(v[0]);} + if (v.length>1) {minor = Integer.parseInt(v[1]);} + if (v.length>2) {patch = Integer.parseInt(v[2]);} + if (v.length>3) {pkg = Integer.parseInt(v[3]);} } catch (NumberFormatException e) { throw new LocatorException("Invalid Version String: " + version); } @@ -83,13 +83,13 @@ public class DirectAAFLocator extends AbsAAFLocator<AuthzTrans> { public boolean refresh() { AuthzTrans trans = env.newTransNoAvg(); Result<List<Data>> rl = ldao.readByName(trans, name); - if(rl.isOK()) { + if (rl.isOK()) { LinkedList<EP> epl = new LinkedList<>(); - for(Data d : rl.value) { -// if(myhostname!=null && d.port==myport && d.hostname.equals(myhostname)) { + for (Data d : rl.value) { +// if (myhostname!=null && d.port==myport && d.hostname.equals(myhostname)) { // continue; // } - if((major<0 || major==d.major) && + if ((major<0 || major==d.major) && (minor<0 || minor<=d.minor) && (patch<0 || patch==d.patch) && (pkg<0 || pkg ==d.pkg)) { @@ -104,7 +104,7 @@ public class DirectAAFLocator extends AbsAAFLocator<AuthzTrans> { endpoint.setLatitude(d.latitude); endpoint.setLongitude(d.longitude); endpoint.setProtocol(d.protocol); - for(String s : d.subprotocol(false)) { + for (String s : d.subprotocol(false)) { endpoint.getSubprotocol().add(s); } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java index 75f6c7a5..59613961 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFLur.java @@ -61,10 +61,10 @@ public class DirectAAFLur implements Lur { Result<List<Data>> pdr = question.getPermsByUser(trans, bait.getName(),false); switch(pdr.status) { case OK: - for(PermDAO.Data d : pdr.value) { - if(!rv) { + for (PermDAO.Data d : pdr.value) { + if (!rv) { for (Permission p : pond) { - if(new PermPermission(d).match(p)) { + if (new PermPermission(d).match(p)) { rv=true; break; } @@ -86,7 +86,7 @@ public class DirectAAFLur implements Lur { Result<List<Data>> pdr = question.getPermsByUser(env.newTrans(), bait.getName(),false); switch(pdr.status) { case OK: - for(PermDAO.Data d : pdr.value) { + for (PermDAO.Data d : pdr.value) { permissions.add(new PermPermission(d)); } break; @@ -135,23 +135,23 @@ public class DirectAAFLur implements Lur { @Override public boolean match(Permission p) { - if(p==null) { + if (p==null) { return false; } PermDAO.Data pd; - if(p instanceof DirectAAFLur.PermPermission) { + if (p instanceof DirectAAFLur.PermPermission) { pd = ((DirectAAFLur.PermPermission)p).data; - if(data.ns.equals(pd.ns)) - if(data.type.equals(pd.type)) - if(data.instance!=null && (data.instance.equals(pd.instance) || "*".equals(data.instance))) - if(data.action!=null && (data.action.equals(pd.action) || "*".equals(data.action))) + if (data.ns.equals(pd.ns)) + if (data.type.equals(pd.type)) + if (data.instance!=null && (data.instance.equals(pd.instance) || "*".equals(data.instance))) + if (data.action!=null && (data.action.equals(pd.action) || "*".equals(data.action))) return true; } else{ String[] lp = p.getKey().split("\\|"); - if(lp.length<3)return false; - if(data.fullType().equals(lp[0])) - if(data.instance!=null && (data.instance.equals(lp[1]) || "*".equals(data.instance))) - if(data.action!=null && (data.action.equals(lp[2]) || "*".equals(data.action))) + if (lp.length<3)return false; + if (data.fullType().equals(lp[0])) + if (data.instance!=null && (data.instance.equals(lp[1]) || "*".equals(data.instance))) + if (data.action!=null && (data.action.equals(lp[2]) || "*".equals(data.action))) return true; } return false; @@ -180,9 +180,9 @@ public class DirectAAFLur implements Lur { @Override public Permission createPerm(String p) { String[] params = Split.split('|', p); - if(params.length==3) { + if (params.length==3) { Result<NsSplit> nss = question.deriveNsSplit(NullTrans.singleton(), params[0]); - if(nss.isOK()) { + if (nss.isOK()) { return new PermPermission(nss.value.ns,nss.value.name,params[1],params[2]); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java index 9d4cd05f..3ef532b4 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectAAFUserPass.java @@ -54,12 +54,12 @@ public class DirectAAFUserPass implements CredVal { public boolean validate(String user, Type type, byte[] pass, Object state) { try { AuthzTrans trans; - if(state !=null) { - if(state instanceof AuthzTrans) { + if (state !=null) { + if (state instanceof AuthzTrans) { trans = (AuthzTrans)state; } else { trans = env.newTransNoAvg(); - if(state instanceof HttpServletRequest) { + if (state instanceof HttpServletRequest) { trans.set((HttpServletRequest)state); } } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java index 6dd5e006..f3351dae 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectCertIdentity.java @@ -53,10 +53,10 @@ public class DirectCertIdentity implements CertIdentity { @Override public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] _certBytes) throws CertificateException { byte[] certBytes = _certBytes; - if(cert==null && certBytes==null) { + if (cert==null && certBytes==null) { return null; } - if(certBytes==null) { + if (certBytes==null) { certBytes = cert.getEncoded(); } byte[] fingerprint = X509Taf.getFingerPrint(certBytes); @@ -64,7 +64,7 @@ public class DirectCertIdentity implements CertIdentity { AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); Result<List<Data>> cresp = certDAO.read(trans, ByteBuffer.wrap(fingerprint)); - if(cresp.isOKhasData()) { + if (cresp.isOKhasData()) { Data cdata = cresp.value.get(0); return new X509Principal(cdata.id,cert,certBytes,null); } diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java index caededa2..aa6bf8c5 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectLocatorCreator.java @@ -40,7 +40,7 @@ public class DirectLocatorCreator implements AbsAAFLocator.LocatorCreator { @Override public AbsAAFLocator<?> create(String key, String version) throws LocatorException { DirectAAFLocator dal = new DirectAAFLocator(env,locateDAO,key,version); - if(myhostname!=null) { + if (myhostname!=null) { dal.setSelf(myhostname, myport); } return dal; diff --git a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java index da7044cf..9eea77e3 100644 --- a/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java +++ b/auth/auth-cass/src/main/java/org/onap/aaf/auth/direct/DirectRegistrar.java @@ -45,14 +45,14 @@ public class DirectRegistrar implements Registrant<AuthzEnv> { try { String latitude = access.getProperty(Config.CADI_LATITUDE, null); - if(latitude==null) { + if (latitude==null) { latitude = access.getProperty("AFT_LATITUDE", null); } String longitude = access.getProperty(Config.CADI_LONGITUDE, null); - if(longitude==null) { + if (longitude==null) { longitude = access.getProperty("AFT_LONGITUDE", null); } - if(latitude==null || longitude==null) { + if (latitude==null || longitude==null) { throw new CadiException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " is required"); } else { locate.latitude = Float.parseFloat(latitude); @@ -64,18 +64,18 @@ public class DirectRegistrar implements Registrant<AuthzEnv> { locate.minor = split.length>1?Integer.parseInt(split[1]):0; locate.major = split.length>0?Integer.parseInt(split[0]):0; locate.hostname = access.getProperty(Config.AAF_REGISTER_AS, null); - if(locate.hostname==null) { + if (locate.hostname==null) { locate.hostname = access.getProperty(Config.HOSTNAME, null); } - if(locate.hostname==null) { + if (locate.hostname==null) { locate.hostname = Inet4Address.getLocalHost().getHostName(); } String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); - if(subprotocols==null) { + if (subprotocols==null) { locate.protocol="http"; } else { locate.protocol="https"; - for(String s : Split.split(',', subprotocols)) { + for (String s : Split.split(',', subprotocols)) { locate.subprotocol(true).add(s); } } @@ -87,7 +87,7 @@ public class DirectRegistrar implements Registrant<AuthzEnv> { @Override public Result<Void> update(AuthzEnv env) { org.onap.aaf.auth.layer.Result<Void> dr = ldao.update(env.newTransNoAvg(), locate); - if(dr.isOK()) { + if (dr.isOK()) { return Result.ok(200, null); } else { return Result.err(503, dr.errorString()); @@ -100,7 +100,7 @@ public class DirectRegistrar implements Registrant<AuthzEnv> { @Override public Result<Void> cancel(AuthzEnv env) { org.onap.aaf.auth.layer.Result<Void> dr = ldao.delete(env.newTransNoAvg(), locate, false); - if(dr.isOK()) { + if (dr.isOK()) { return Result.ok(200, null); } else { return Result.err(503, dr.errorString()); diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java index 0dd03da4..7cc8bd67 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_Cached.java @@ -121,14 +121,14 @@ public class JU_Cached { // Date dbStamp = info.get(trans, name,cacheIdx); // // // Check for cache Entry and whether it is still good (a good Cache Entry is same or after DBEntry, so we use "before" syntax) -// if(cached!=null && dbStamp.before(cached.timestamp)) { +// if (cached!=null && dbStamp.before(cached.timestamp)) { // ld = (List<DATA>)cached.data; // rld = Result.ok(ld); // } else { // rld = getter.get(); -// if(rld.isOK()) { // only store valid lists +// if (rld.isOK()) { // only store valid lists // map.put(key, new Dated(rld.value)); // successful item found gets put in cache -//// } else if(rld.status == Result.ERR_Backend){ +//// } else if (rld.status == Result.ERR_Backend){ //// map.remove(key); // } // } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java index 692c3a82..dea2ccdd 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/AbsJUCass.java @@ -67,13 +67,13 @@ public class AbsJUCass { @BeforeClass public static void startup() throws APIException, IOException { synchronized(AUTHZ) { - if(env==null) { + if (env==null) { final String resource = "cadi.properties"; File f = new File("etc" + resource); InputStream is=null; Properties props = new Properties(); try { - if(f.exists()) { + if (f.exists()) { is = new FileInputStream(f); } else { URL rsrc = ClassLoader.getSystemResource(resource); @@ -81,7 +81,7 @@ public class AbsJUCass { } props.load(is); } finally { - if(is==null) { + if (is==null) { env= new AuthzEnv(); Assert.fail(resource + " must exist in etc dir, or in Classpath"); } @@ -95,7 +95,7 @@ public class AbsJUCass { env.info().log("Connecting to Cluster"); try { cluster.connect(AUTHZ); - } catch(Exception e) { + } catch (Exception e) { cluster=null; env.error().log(e); Assert.fail("Not able to connect to DB: " + e.getLocalizedMessage()); @@ -114,7 +114,7 @@ public class AbsJUCass { @AfterClass public static void shutdown() { - if(cluster!=null) { + if (cluster!=null) { cluster.close(); cluster = null; } @@ -129,10 +129,10 @@ public class AbsJUCass { @After public void auditTrail() { - if(totals==0) { // "updateTotals()" was not called... just do one Trans + if (totals==0) { // "updateTotals()" was not called... just do one Trans StringBuilder sb = new StringBuilder(); Metric metric = trans.auditTrail(4, sb, Env.JSON, Env.REMOTE); - if(details) { + if (details) { env.info().log( sb, "Total time:", @@ -159,7 +159,7 @@ public class AbsJUCass { @AfterClass public static void print() { float transTime; - if(iterations==0) { + if (iterations==0) { transTime=totals; } else { transTime=totals/iterations; diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java index c91bfe1e..7e460899 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_Bytification.java @@ -78,12 +78,12 @@ public class JU_Bytification { assertEquals(a.type,b.type); // assertEquals(a.admin.size(),b.admin.size()); -// for(String s: a.admin) { +// for (String s: a.admin) { // assertTrue(b.admin.contains(s)); // } // // assertEquals(a.responsible.size(),b.responsible.size()); -// for(String s: a.responsible) { +// for (String s: a.responsible) { // assertTrue(b.responsible.contains(s)); // } } @@ -105,7 +105,7 @@ public class JU_Bytification { // Overshoot Buffer StringBuilder sb = new StringBuilder(300); sb.append("role|instance|veryLongAction..."); - for(int i=0;i<280;++i) { + for (int i=0;i<280;++i) { sb.append('a'); } rd1.perms(true).add(sb.toString()); @@ -123,7 +123,7 @@ public class JU_Bytification { check(rd1,rd2); // 1000 Perms - for(int i=0;i<1000;++i) { + for (int i=0;i<1000;++i) { rd1.perms(true).add("com|inst|action"+ i); } @@ -139,7 +139,7 @@ public class JU_Bytification { assertEquals(a.name,b.name); assertEquals(a.perms.size(),b.perms.size()); - for(String s: a.perms) { + for (String s: a.perms) { assertTrue(b.perms.contains(s)); } } @@ -169,7 +169,7 @@ public class JU_Bytification { check(pd1,rd2); // 1000 Perms - for(int i=0;i<1000;++i) { + for (int i=0;i<1000;++i) { pd1.roles(true).add("org.osaaf.<pass>.my.Role"+ i); } @@ -187,7 +187,7 @@ public class JU_Bytification { assertEquals(a.action,b.action); assertEquals(a.roles.size(),b.roles.size()); - for(String s: a.roles) { + for (String s: a.roles) { assertTrue(b.roles.contains(s)); } } @@ -252,7 +252,7 @@ public class JU_Bytification { assertEquals(a.id,b.id); assertEquals(a.ns,b.ns); assertEquals(a.type,b.type); - if(a.cred==null) { + if (a.cred==null) { assertEquals(a.cred,b.cred); } else { int l = a.cred.limit(); diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java index 33b67429..05195eeb 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/aaf/test/JU_NsType.java @@ -38,7 +38,7 @@ public class JU_NsType { public void test() { NsType nt,nt2; String[] tests = new String[] {"DOT","ROOT","COMPANY","APP","STACKED_APP","STACK"}; - for(String s : tests) { + for (String s : tests) { nt = NsType.valueOf(s); assertEquals(s,nt.name()); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java index d80b085b..15e298b7 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/AAF_CM.java @@ -97,7 +97,7 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { aafAuthn = aafCon().newAuthn(aafLurPerm); String aaf_env = env.getProperty(Config.AAF_ENV); - if(aaf_env==null) { + if (aaf_env==null) { throw new APIException("aaf_env needs to be set"); } @@ -112,17 +112,17 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { // Load Supported Certificate Authorities by property // Note: Some will be dynamic Properties, so we need to look through all - for(Entry<Object, Object> es : env.access().getProperties().entrySet()) { + for (Entry<Object, Object> es : env.access().getProperties().entrySet()) { String key = es.getKey().toString(); - if(key.startsWith(CA.CM_CA_PREFIX)) { + if (key.startsWith(CA.CM_CA_PREFIX)) { int idx = key.indexOf('.'); - if(idx==key.lastIndexOf('.')) { // else it's a regular property + if (idx==key.lastIndexOf('.')) { // else it's a regular property env.log(Level.INIT, "Loading Certificate Authority Module: " + key.substring(idx+1)); String[] segs = Split.split(',', env.getProperty(key)); - if(segs.length>0) { + if (segs.length>0) { String[][] multiParams = new String[segs.length-1][]; - for(int i=0;i<multiParams.length;++i) { + for (int i=0;i<multiParams.length;++i) { multiParams[i]=Split.split(';',segs[1+i]); } @SuppressWarnings("unchecked") @@ -141,7 +141,7 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { } } } - if(certAuths.size()==0) { + if (certAuths.size()==0) { throw new APIException("No Certificate Authorities have been configured in CertMan"); } @@ -152,7 +152,7 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { synchronized(env) { - if(cacheUser == null) { + if (cacheUser == null) { cacheUser = Cache.obtain(USER_PERMS); Cache.startCleansing(env, USER_PERMS); } @@ -184,7 +184,7 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { String version = "1.0"; // Get Correct API Class from Mapper Class<?> respCls = facade1_0.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + if (respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); // setup Application API HTML ContentTypes for JSON and Route String application = applicationJSON(respCls, version); route(env,meth,path,code,application,"application/json;version="+version,"*/*"); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java index 34f7927e..a3a30607 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Artifact.java @@ -52,7 +52,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.createArtifacts(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.CREATED_201); } else { context.error(trans,resp,r); @@ -67,7 +67,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.readArtifacts(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -81,7 +81,7 @@ public class API_Artifact { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.readArtifacts(trans, resp, pathParam(req,":mechid"), pathParam(req,":machine")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -94,7 +94,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.updateArtifacts(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -107,7 +107,7 @@ public class API_Artifact { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.deleteArtifacts(trans, resp, pathParam(req, ":mechid"), pathParam(req,":machine")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -120,7 +120,7 @@ public class API_Artifact { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.deleteArtifacts(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java index 625fed62..68354413 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/api/API_Cert.java @@ -63,12 +63,12 @@ public class API_Cert { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String key = pathParam(req, ":ca"); CA ca; - if((ca = aafCM.getCA(key))==null) { + if ((ca = aafCM.getCA(key))==null) { context.error(trans,resp,Result.ERR_BadData,"CA %s is not supported",key); } else { trans.put(sCertAuth, ca); Result<Void> r = context.requestCert(trans, req, resp, ca); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -82,12 +82,12 @@ public class API_Cert { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String key = pathParam(req, ":ca"); CA ca; - if((ca = aafCM.getCA(key))==null) { + if ((ca = aafCM.getCA(key))==null) { context.error(trans,resp,Result.ERR_BadData,"CA %s is not supported",key); } else { trans.put(sCertAuth, ca); Result<Void> r = context.requestPersonalCert(trans, req, resp, ca); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -104,7 +104,7 @@ public class API_Cert { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.check(trans, resp, pathParam(req,"perm")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { trans.checkpoint(r.errorString()); @@ -125,7 +125,7 @@ public class API_Cert { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.readCertsByMechID(trans, resp, pathParam(req,"id")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java index 820f02d1..881c9bea 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/CA.java @@ -71,7 +71,7 @@ public abstract class CA { this.env = env; permNS = CM_CA_PREFIX + name; permType = access.getProperty(permNS + ".perm_type",null); - if(permType==null) { + if (permType==null) { throw new CertException(permNS + ".perm_type" + MUST_EXIST_TO_CREATE_CSRS_FOR + caName); } caIssuerDNs = Split.splitTrim(':', access.getProperty(Config.CADI_X509_ISSUERS, null)); @@ -79,22 +79,22 @@ public abstract class CA { String tag = CA.CM_CA_PREFIX+caName+CA.CM_CA_BASE_SUBJECT; String fields = access.getProperty(tag, null); - if(fields==null) { + if (fields==null) { throw new CertException(tag + MUST_EXIST_TO_CREATE_CSRS_FOR + caName); } access.log(Level.INFO, tag, "=",fields); rdns = RDN.parse('/',fields); - for(RDN rdn : rdns) { - if(rdn.aoi==BCStyle.EmailAddress) { // Cert Specs say Emails belong in Subject + for (RDN rdn : rdns) { + if (rdn.aoi==BCStyle.EmailAddress) { // Cert Specs say Emails belong in Subject throw new CertException("email address is not allowed in " + CM_CA_BASE_SUBJECT); } } idDomains = new ArrayList<>(); StringBuilder sb = null; - for(String s : Split.splitTrim(',', access.getProperty(CA.CM_CA_PREFIX+caName+".idDomains", ""))) { - if(s.length()>0) { - if(sb==null) { + for (String s : Split.splitTrim(',', access.getProperty(CA.CM_CA_PREFIX+caName+".idDomains", ""))) { + if (s.length()>0) { + if (sb==null) { sb = new StringBuilder(); } else { sb.append(", "); @@ -103,31 +103,31 @@ public abstract class CA { sb.append(s); } } - if(sb!=null) { + if (sb!=null) { access.printf(Level.INIT, "CA '%s' supports Personal Certificates for %s", caName, sb); } String dataDir = access.getProperty(CM_PUBLIC_DIR,null); - if(dataDir!=null) { + if (dataDir!=null) { File data = new File(dataDir); byte[] bytes; - if(data.exists()) { + if (data.exists()) { String trustCas = access.getProperty(CM_TRUST_CAS,null); - if(trustCas!=null) { - for(String fname : Split.splitTrim(',', trustCas)) { + if (trustCas!=null) { + for (String fname : Split.splitTrim(',', trustCas)) { File crt; - if(fname.contains("/")) { + if (fname.contains("/")) { crt = new File(fname); } else { crt = new File(data,fname); } - if(crt.exists()) { + if (crt.exists()) { access.printf(Level.INIT, "Loading CA Cert from %s", crt.getAbsolutePath()); bytes = new byte[(int)crt.length()]; FileInputStream fis = new FileInputStream(crt); try { int read = fis.read(bytes); - if(read>0) { + if (read>0) { addTrustedCA(new String(bytes)); } } finally { @@ -148,13 +148,13 @@ public abstract class CA { protected void addCaIssuerDN(String issuerDN) { boolean changed = true; - for(String id : caIssuerDNs) { - if(id.equals(issuerDN)) { + for (String id : caIssuerDNs) { + if (id.equals(issuerDN)) { changed = false; break; } } - if(changed) { + if (changed) { String[] newsa = new String[caIssuerDNs.length+1]; newsa[0]=issuerDN; System.arraycopy(caIssuerDNs, 0, newsa, 1, caIssuerDNs.length); @@ -164,13 +164,13 @@ public abstract class CA { protected synchronized void addTrustedCA(final String crtString) { String crt; - if(crtString.endsWith("\n")) { + if (crtString.endsWith("\n")) { crt = crtString; } else { crt = crtString + '\n'; } - for(int i=0;i<trustedCAs.length;++i) { - if(trustedCAs[i]==null) { + for (int i=0;i<trustedCAs.length;++i) { + if (trustedCAs[i]==null) { trustedCAs[i]=crt; return; } @@ -221,7 +221,7 @@ public abstract class CA { */ public boolean inPersonalDomains(Principal p) { int at = p.getName().indexOf('@'); - if(at>=0) { + if (at>=0) { return idDomains.contains(p.getName().substring(at+1)); } else { return false; diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java index 000b6dd5..bc81fc43 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/JscepCA.java @@ -75,10 +75,10 @@ public class JscepCA extends CA { mxcwiS = new ConcurrentHashMap<>(); mxcwiC = new ConcurrentHashMap<>(); - if(params.length<2) { + if (params.length<2) { throw new CertException("No Trust Chain parameters are included"); } - if(params[0].length<2) { + if (params[0].length<2) { throw new CertException("User/Password required for JSCEP"); } final String id = params[0][0]; @@ -98,21 +98,21 @@ public class JscepCA extends CA { StringBuilder urlstr = new StringBuilder(); - for(int i=1;i<params.length;++i) { // skip first section, which is user/pass + for (int i=1;i<params.length;++i) { // skip first section, which is user/pass // Work - if(i>1) { + if (i>1) { urlstr.append(','); // delimiter } urlstr.append(params[i][0]); String dir = access.getProperty(CM_PUBLIC_DIR, ""); - if(!"".equals(dir) && !dir.endsWith("/")) { + if (!"".equals(dir) && !dir.endsWith("/")) { dir = dir + '/'; } String path; List<FileReader> frs = new ArrayList<>(params.length-1); try { - for(int j=1; j<params[i].length; ++j) { // first 3 taken up, see above + for (int j=1; j<params[i].length; ++j) { // first 3 taken up, see above path = !params[i][j].contains("/")?dir+params[i][j]:params[i][j]; access.printf(Level.INIT, "Loading a TrustChain Member for %s from %s",name, path); frs.add(new FileReader(path)); @@ -121,8 +121,8 @@ public class JscepCA extends CA { addCaIssuerDN(xcwi.getIssuerDN()); mxcwiS.put(params[i][0],xcwi); } finally { - for(FileReader fr : frs) { - if(fr!=null) { + for (FileReader fr : frs) { + if (fr!=null) { fr.close(); } } @@ -139,10 +139,10 @@ public class JscepCA extends CA { PKCS10CertificationRequest csr; try { csr = csrmeta.generateCSR(trans); - if(trans.info().isLoggable()) { + if (trans.info().isLoggable()) { trans.info().log(BCFactory.toString(csr)); } - if(trans.info().isLoggable()) { + if (trans.info().isLoggable()) { trans.info().log(csr); } } finally { @@ -152,7 +152,7 @@ public class JscepCA extends CA { tt = trans.start("Enroll CSR", Env.SUB); Client client = null; Item item = null; - for(int i=0; i<MAX_RETRY;++i) { + for (int i=0; i<MAX_RETRY;++i) { try { item = clients.best(); client = clients.get(item); @@ -163,12 +163,12 @@ public class JscepCA extends CA { csr, MS_PROFILE /* profile... MS can't deal with blanks*/); - while(true) { - if(er.isSuccess()) { + while (true) { + if (er.isSuccess()) { trans.checkpoint("Cert from " + clients.info(item)); X509Certificate x509 = null; - for( Certificate cert : er.getCertStore().getCertificates(null)) { - if(x509==null) { + for ( Certificate cert : er.getCertStore().getCertificates(null)) { + if (x509==null) { x509 = (X509Certificate)cert; break; } @@ -183,14 +183,14 @@ public class JscepCA extends CA { throw new CertException(clients.info(item)+':'+er.getFailInfo().toString()); } } - } catch(LocatorException e) { + } catch (LocatorException e) { trans.error().log(e); i=MAX_RETRY; } catch (ClientException e) { trans.error().log(e,"SCEP Client Error, Temporarily Invalidating Client: " + clients.info(item)); try { clients.invalidate(client); - if(!clients.hasItems()) { + if (!clients.hasItems()) { clients.refresh(); } } catch (LocatorException e1) { diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java index b7d78f05..2a3ce537 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/LocalCA.java @@ -92,55 +92,55 @@ public class LocalCA extends CA { serial = new BigInteger(64,random); - if(params.length<1 || params[0].length<2) { + if (params.length<1 || params[0].length<2) { throw new IOException("LocalCA expects cm_ca.<ca name>=org.onap.aaf.auth.cm.ca.LocalCA,<full path to key file>[;<Full Path to Trust Chain, ending with actual CA>]+"); } // Read in the Private Key String configured; File f = new File(params[0][0]); - if(f.exists() && f.isFile()) { + if (f.exists() && f.isFile()) { String fileName = f.getName(); - if(fileName.endsWith(".key")) { + if (fileName.endsWith(".key")) { caKey = Factory.toPrivateKey(NullTrans.singleton(),f); List<FileReader> frs = new ArrayList<>(params.length-1); try { String dir = access.getProperty(CM_PUBLIC_DIR, ""); - if(!"".equals(dir) && !dir.endsWith("/")) { + if (!"".equals(dir) && !dir.endsWith("/")) { dir = dir + '/'; } String path; - for(int i=1; i<params[0].length; ++i) { // first param is Private Key, remainder are TrustChain + for (int i=1; i<params[0].length; ++i) { // first param is Private Key, remainder are TrustChain path = !params[0][i].contains("/")?dir+params[0][i]:params[0][i]; access.printf(Level.INIT, "Loading a TrustChain Member for %s from %s\n",name, path); frs.add(new FileReader(path)); } x509cwi = new X509ChainWithIssuer(frs); } finally { - for(FileReader fr : frs) { - if(fr!=null) { + for (FileReader fr : frs) { + if (fr!=null) { fr.close(); } } } configured = "Configured with " + fileName; } else { - if(params.length<1 || params[0].length<3) { + if (params.length<1 || params[0].length<3) { throw new CertException("LocalCA parameters must be <keystore [.p12|.pkcs12|.jks|.pkcs11(sun only)]; <alias>; enc:<encrypted Keystore Password>>"); } try { Provider p; KeyStore keyStore; FileInputStream fis = null; - if(fileName.endsWith(".pkcs11")) { + if (fileName.endsWith(".pkcs11")) { String ksType="PKCS11"; p = Factory.getSecurityProvider(ksType,params); keyStore = KeyStore.getInstance(ksType,p); - } else if(fileName.endsWith(".jks")) { + } else if (fileName.endsWith(".jks")) { keyStore = KeyStore.getInstance("JKS"); fis = new FileInputStream(f); - } else if(fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) { + } else if (fileName.endsWith(".p12") || fileName.endsWith(".pkcs12")) { keyStore = KeyStore.getInstance("PKCS12"); fis = new FileInputStream(f); } else { @@ -151,7 +151,7 @@ public class LocalCA extends CA { try { String pass = access.decrypt(params[0][2]/*encrypted passcode*/, true); - if(pass==null) { + if (pass==null) { throw new CertException("Passcode for " + fileName + " cannot be decrypted."); } char[] ksPass = pass.toCharArray(); @@ -164,12 +164,12 @@ public class LocalCA extends CA { fis.close(); } Entry entry; - if(fileName.endsWith(".pkcs11")) { + if (fileName.endsWith(".pkcs11")) { entry = keyStore.getEntry(params[0][1]/*alias*/, null); } else { entry = keyStore.getEntry(params[0][1]/*alias*/, keyPass); } - if(entry==null) { + if (entry==null) { throw new CertException("There is no Keystore entry with name '" + params[0][1] +'\''); } PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry)entry; @@ -188,7 +188,7 @@ public class LocalCA extends CA { X500NameBuilder xnb = new X500NameBuilder(); List<RDN> rp = RDN.parse(',', x509cwi.getIssuerDN()); Collections.reverse(rp); - for(RDN rnd : rp) { + for (RDN rnd : rp) { xnb.addRDN(rnd.aoi,rnd.value); } issuer = xnb.build(); @@ -226,7 +226,7 @@ public class LocalCA extends CA { // new SubjectPublicKeyInfo(ASN1Sequence.getInstance(caCert.getPublicKey().getEncoded())) ); List<GeneralName> lsan = new ArrayList<>(); - for(String s : csrmeta.sans()) { + for (String s : csrmeta.sans()) { lsan.add(new GeneralName(GeneralName.dNSName,s)); } GeneralName[] sans = new GeneralName[lsan.size()]; diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java index e51f2faa..2ef6da55 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509ChainWithIssuer.java @@ -45,8 +45,8 @@ public class X509ChainWithIssuer extends X509andChain { // Trust Chain. Last one should be the CA Collection<? extends Certificate> certs; X509Certificate x509; - for(Reader rdr : rdrs) { - if(rdr==null) { // cover for badly formed array + for (Reader rdr : rdrs) { + if (rdr==null) { // cover for badly formed array continue; } @@ -56,13 +56,13 @@ public class X509ChainWithIssuer extends X509andChain { } catch (CertificateException e) { throw new CertException(e); } - for(Certificate c : certs) { + for (Certificate c : certs) { x509=(X509Certificate)c; Principal subject = x509.getSubjectDN(); - if(subject==null) { + if (subject==null) { continue; } - if(cert==null) { // first in Trust Chain + if (cert==null) { // first in Trust Chain issuerDN = subject.toString(); cert=x509; // adding each time makes sure last one is signer. } @@ -73,12 +73,12 @@ public class X509ChainWithIssuer extends X509andChain { public X509ChainWithIssuer(Certificate[] certs) throws IOException, CertException { X509Certificate x509; - for(int i=certs.length-1; i>=0; --i) { + for (int i=certs.length-1; i>=0; --i) { x509=(X509Certificate)certs[i]; Principal subject = x509.getSubjectDN(); - if(subject!=null) { + if (subject!=null) { addTrustChainEntry(x509); - if(i==0) { // last one is signer + if (i==0) { // last one is signer cert=x509; issuerDN= subject.toString(); } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java index 3c684db2..7eb88bd2 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/ca/X509andChain.java @@ -58,7 +58,7 @@ public class X509andChain { public void addTrustChainEntry(X509Certificate x509) throws IOException, CertException { - if(trustChain==null) { + if (trustChain==null) { trustChain = new String[] {Factory.toString(NullTrans.singleton(),x509)}; } else { String[] temp = new String[trustChain.length+1]; diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java index 8edfa634..b84816ab 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/BCFactory.java @@ -65,7 +65,7 @@ public class BCFactory extends Factory { } public static String toString(PKCS10CertificationRequest csr) throws IOException, CertException { - if(csr==null) { + if (csr==null) { throw new CertException("x509 Certificate Request not built"); } return textBuilder("CERTIFICATE REQUEST",csr.getEncoded()); @@ -94,8 +94,8 @@ public class BCFactory extends Factory { CSRMeta csr = ca.newCSRMeta(); boolean first = true; // Set CN (and SAN) - for(String fqdn : fqdns) { - if(first) { + for (String fqdn : fqdns) { + if (first) { first = false; csr.cn(fqdn); } @@ -106,7 +106,7 @@ public class BCFactory extends Factory { csr.mechID(mechid); csr.email(sponsorEmail); String errs; - if((errs=validateApp(csr))!=null) { + if ((errs=validateApp(csr))!=null) { throw new CertException(errs); } return csr; @@ -114,7 +114,7 @@ public class BCFactory extends Factory { private static String validateApp(CSRMeta csr) { CertmanValidator v = new CertmanValidator(); - if(v.nullOrBlank("cn", csr.cn()) + if (v.nullOrBlank("cn", csr.cn()) .nullOrBlank("mechID", csr.mechID()) // .nullOrBlank("email", csr.email()) .err()) { @@ -130,7 +130,7 @@ public class BCFactory extends Factory { csr.challenge(new String(Symm.randomGen(24))); csr.email(email); String errs; - if((errs=validatePersonal(csr))!=null) { + if ((errs=validatePersonal(csr))!=null) { throw new CertException(errs); } return csr; @@ -138,7 +138,7 @@ public class BCFactory extends Factory { private static String validatePersonal(CSRMeta csr) { CertmanValidator v = new CertmanValidator(); - if(v.nullOrBlank("cn", csr.cn()) + if (v.nullOrBlank("cn", csr.cn()) .nullOrBlank("email", csr.email()) .err()) { return v.errs(); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java index 5df439ab..a3740bfe 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/CSRMeta.java @@ -70,18 +70,18 @@ public class CSRMeta { } public X500Name x500Name() { - if(name==null) { + if (name==null) { X500NameBuilder xnb = new X500NameBuilder(); xnb.addRDN(BCStyle.CN,cn); xnb.addRDN(BCStyle.E,email); - if(mechID!=null) { - if(environment==null) { + if (mechID!=null) { + if (environment==null) { xnb.addRDN(BCStyle.OU,mechID); } else { xnb.addRDN(BCStyle.OU,mechID+':'+environment); } } - for(RDN rdn : rdns) { + for (RDN rdn : rdns) { xnb.addRDN(rdn.aoi,rdn.value); } name = xnb.build(); @@ -92,16 +92,16 @@ public class CSRMeta { public PKCS10CertificationRequest generateCSR(Trans trans) throws IOException, CertException { PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name(),keypair(trans).getPublic()); - if(challenge!=null) { + if (challenge!=null) { DERPrintableString password = new DERPrintableString(challenge); builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, password); } int plus = email==null?0:1; - if(!sanList.isEmpty()) { + if (!sanList.isEmpty()) { GeneralName[] gna = new GeneralName[sanList.size()+plus]; int i=-1; - for(String s : sanList) { + for (String s : sanList) { gna[++i]=new GeneralName(GeneralName.dNSName,s); } gna[++i]=new GeneralName(GeneralName.rfc822Name,email); @@ -132,17 +132,17 @@ public class CSRMeta { Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0)); GeneralNames gns = GeneralNames.fromExtensions(extensions,Extension.subjectAlternativeName); GeneralName[] names = gns.getNames(); - for(int k=0; k < names.length; k++) { + for (int k=0; k < names.length; k++) { String title = ""; - if(names[k].getTagNo() == GeneralName.dNSName) { + if (names[k].getTagNo() == GeneralName.dNSName) { title = "dNSName"; - } else if(names[k].getTagNo() == GeneralName.iPAddress) { + } else if (names[k].getTagNo() == GeneralName.iPAddress) { title = "iPAddress"; // Deprecated, but I don't see anything better to use. names[k].toASN1Object(); - } else if(names[k].getTagNo() == GeneralName.otherName) { + } else if (names[k].getTagNo() == GeneralName.otherName) { title = "otherName"; - } else if(names[k].getTagNo() == GeneralName.rfc822Name) { + } else if (names[k].getTagNo() == GeneralName.rfc822Name) { title = "email"; } @@ -180,7 +180,7 @@ public class CSRMeta { public KeyPair keypair(Trans trans) { - if(keyPair == null) { + if (keyPair == null) { keyPair = Factory.generateKeyPair(trans); } return keyPair; diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java index c39ba6d3..f57c837a 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/cert/RDN.java @@ -69,19 +69,19 @@ public class RDN { List<RDN> lrnd = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean inQuotes = false; - for(int i=0;i<dnString.length();++i) { + for (int i=0;i<dnString.length();++i) { char c = dnString.charAt(i); - if(inQuotes) { - if('"' == c) { + if (inQuotes) { + if ('"' == c) { inQuotes=false; } else { sb.append(dnString.charAt(i)); } } else { - if('"' == c) { + if ('"' == c) { inQuotes=true; - } else if(delim==c) { - if(sb.length()>0) { + } else if (delim==c) { + if (sb.length()>0) { lrnd.add(new RDN(sb.toString())); sb.setLength(0); } @@ -90,7 +90,7 @@ public class RDN { } } } - if(sb.indexOf("=")>0) { + if (sb.indexOf("=")>0) { lrnd.add(new RDN(sb.toString())); } return lrnd; diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java index 310ea8b2..e05b2a27 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/facade/FacadeImpl.java @@ -115,7 +115,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. (certDF = env.newDataFactory(mapper.getClass(API.CERT))).in(dataType).out(dataType); (artiDF = env.newDataFactory(mapper.getClass(API.ARTIFACTS))).in(dataType).out(dataType); // sCertAuth = env.slot(API_Cert.CERT_AUTH); - if(artiDF.getOutType().name().contains("xml")) { + if (artiDF.getOutType().name().contains("xml")) { voidResp = "application/Void+xml;charset=utf-8;version=1.0,application/xml;version=1.0,*/*"; } else { voidResp = "application/Void+json;charset=utf-8;version=1.0,application/json;version=1.0,*/*"; @@ -206,7 +206,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. "] " + holder.toString(), Env.ALWAYS); - if(hidemsg) { + if (hidemsg) { holder.setLength(0); em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); } @@ -231,7 +231,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. default: return Result.err(Result.ERR_BadData,"Invalid Perm String"); } - if(certman.aafLurPerm.fish(trans.getUserPrincipal(), ap)) { + if (certman.aafLurPerm.fish(trans.getUserPrincipal(), ap)) { resp.setContentType(voidResp); resp.getOutputStream().write(0); return Result.ok(); @@ -253,13 +253,13 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. try { Data<REQ> rd = certRequestDF.newData().load(req.getInputStream()); request = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,REQUEST_CERT); return Result.err(Result.ERR_BadData,"Invalid Input"); } Result<CertResp> rcr = service.requestCert(trans,mapper.toReq(trans,request), ca); - if(rcr.notOK()) { + if (rcr.notOK()) { return Result.err(rcr); } @@ -291,7 +291,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. public Result<Void> requestPersonalCert(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, CA ca) { return Result.err(Result.ERR_NotImplemented,"not implemented yet"); // Result<CertResp> rcr = service.requestPersonalCert(trans,ca); -// if(rcr.notOK()) { +// if (rcr.notOK()) { // return Result.err(rcr); // } else { // try { @@ -308,17 +308,17 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. // zos.closeEntry(); // // String wt; -// if((wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt)) { +// if ((wt=req.getParameter("withTrust"))!=null || TRUE.equalsIgnoreCase(wt)) { // zos.putNextEntry(new ZipEntry(trans.user()+".trustCrts")); -// for(String s : ca.getTrustChain()) { +// for (String s : ca.getTrustChain()) { // ps.println(s); // } // zos.closeEntry(); // } // // boolean withJKS = (wt=req.getParameter("withJKS"))!=null || TRUE.equalsIgnoreCase(wt); -// if(withJKS) { -// if(trans.getUserPrincipal() instanceof BasicPrincipal) { +// if (withJKS) { +// if (trans.getUserPrincipal() instanceof BasicPrincipal) { // char[] cap = new String(((BasicPrincipal)trans.getUserPrincipal()).getCred()).toCharArray(); // KeyStore ks = keystore(trans, rcr.value, ca.getTrustChain(), trans.user(), cap); // zos.putNextEntry(new ZipEntry(trans.user()+".jks")); @@ -337,7 +337,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. // ps.println("echo \"Deploying to `pwd`\""); // ps.println("jar -xvf $THE_PWD/$1 " + trans.user()); // ps.println("chmod 600 " + trans.user() + ".key"); -// if(withJKS) { +// if (withJKS) { // ps.println("chmod 600 " + trans.user() + ".jks"); // } // ps.println("cd $THE_PWD"); @@ -362,7 +362,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. // // Get the Cert(s)... Might include Trust store // List<String> lcerts = new ArrayList<>(); // lcerts.add(cr.asCertString()); -// for(String s : trustChain) { +// for (String s : trustChain) { // lcerts.add(s); // } // @@ -377,7 +377,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. // jks.setEntry(name, pkEntry, protParam); // // int i=0; -// for(X509Certificate x509 : certs) { +// for (X509Certificate x509 : certs) { // jks.setCertificateEntry("cert_"+ ++i, x509); // } // return jks; @@ -391,7 +391,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. try { Data<REQ> rd = certRenewDF.newData().load(req.getInputStream()); request = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,RENEW_CERT); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -427,7 +427,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. try { Data<REQ> rd = certDropDF.newData().load(req.getInputStream()); request = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,DROP_CERT); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -485,7 +485,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. try { Data<ARTIFACTS> rd = artiDF.newData().load(req.getInputStream()); arti = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,CREATE_ARTIFACTS); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -509,23 +509,23 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. String ns = req.getParameter("ns"); Result<ARTIFACTS> ra; - if( machine !=null && mechid == null) { + if ( machine !=null && mechid == null) { ra = mapper.fromArtifacts(service.readArtifactsByMachine(trans, machine)); - } else if(mechid!=null && machine==null) { + } else if (mechid!=null && machine==null) { ra = mapper.fromArtifacts(service.readArtifactsByMechID(trans, mechid)); - } else if(mechid!=null && machine!=null) { + } else if (mechid!=null && machine!=null) { ArtiDAO.Data add = new ArtiDAO.Data(); add.mechid = mechid; add.machine = machine; add.ns = ns; ra = mapper.fromArtifacts(service.readArtifacts(trans,add)); - } else if(ns!=null) { + } else if (ns!=null) { ra = mapper.fromArtifacts(service.readArtifactsByNs(trans, ns)); } else { ra = Result.err(Status.ERR_BadData,"Invalid request inputs"); } - if(ra.isOK()) { + if (ra.isOK()) { RosettaData<ARTIFACTS> data = artiDF.newData(trans).load(ra.value); data.to(resp.getOutputStream()); setContentType(resp,artiDF.getOutType()); @@ -550,7 +550,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. add.mechid = mechid; add.machine = machine; Result<ARTIFACTS> ra = mapper.fromArtifacts(service.readArtifacts(trans,add)); - if(ra.isOK()) { + if (ra.isOK()) { RosettaData<ARTIFACTS> data = artiDF.newData(trans).load(ra.value); data.to(resp.getOutputStream()); setContentType(resp,artiDF.getOutType()); @@ -575,7 +575,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. try { Data<ARTIFACTS> rd = artiDF.newData().load(req.getInputStream()); arti = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,UPDATE_ARTIFACTS); return Result.err(Result.ERR_BadData,"Invalid Input"); } @@ -597,7 +597,7 @@ public abstract class FacadeImpl<REQ,CERT,ARTIFACTS,ERROR> extends org.onap.aaf. try { Data<ARTIFACTS> rd = artiDF.newData().load(req.getInputStream()); arti = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,DELETE_ARTIFACTS); return Result.err(Result.ERR_BadData,"Invalid Input"); } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java index 53b97626..99d0c478 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper1_0.java @@ -86,7 +86,7 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { err.setMessageId(msgID); // AT&T Restful Error Format requires numbers "%" placements err.setText(Vars.convert(holder, text, var)); - for(String s : var) { + for (String s : var) { err.getVariables().add(s); } return err; @@ -97,7 +97,7 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { */ @Override public Result<CertInfo> toCert(AuthzTrans trans, Result<CertResp> in, boolean withTrustChain) throws IOException { - if(!in.isOK()) { + if (!in.isOK()) { return Result.err(in); } @@ -105,15 +105,15 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { CertInfo cout = newInstance(API.CERT); cout.setPrivatekey(cin.privateString()); String value; - if((value=cin.challenge())!=null) { + if ((value=cin.challenge())!=null) { cout.setChallenge(value); } // In Version 1, Cert is always first cout.getCerts().add(cin.asCertString()); // Follow with Trust Chain - if(cin.trustChain()!=null) { - for(String c : cin.trustChain()) { - if(c!=null) { + if (cin.trustChain()!=null) { + for (String c : cin.trustChain()) { + if (c!=null) { cout.getCerts().add(c); } } @@ -121,20 +121,20 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { // Adding all the Certs in one response is a mistake. Makes it very hard for Agent to setup // Certs in keystore versus Truststore. Separate in Version 2_0 - if(cin.trustCAs()!=null) { - for(String c : cin.trustCAs()) { - if(c!=null) { - if(!cout.getCerts().contains(c)) { + if (cin.trustCAs()!=null) { + for (String c : cin.trustCAs()) { + if (c!=null) { + if (!cout.getCerts().contains(c)) { cout.getCerts().add(c); } } } } - if(cin.notes()!=null) { + if (cin.notes()!=null) { boolean first = true; StringBuilder sb = new StringBuilder(); - for(String n : cin.notes()) { - if(first) { + for (String n : cin.notes()) { + if (first) { first = false; } else { sb.append('\n'); @@ -144,7 +144,7 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { cout.setNotes(sb.toString()); } List<String> caIssuerDNs = cout.getCaIssuerDNs(); - for(String s : cin.caIssuerDNs()) { + for (String s : cin.caIssuerDNs()) { caIssuerDNs.add(s); } cout.setEnv(cin.env()); @@ -154,10 +154,10 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { @Override public Result<CertInfo> toCert(AuthzTrans trans, Result<List<CertDAO.Data>> in) { - if(in.isOK()) { + if (in.isOK()) { CertInfo cout = newInstance(API.CERT); List<String> certs = cout.getCerts(); - for(CertDAO.Data cdd : in.value) { + for (CertDAO.Data cdd : in.value) { certs.add(cdd.x509); } return Result.ok(cout); @@ -174,7 +174,7 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { CertificateRequest in; try { in = (CertificateRequest)req; - } catch(ClassCastException e) { + } catch (ClassCastException e) { return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); } @@ -184,7 +184,7 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { out.fqdns=in.getFqdns(); v.isNull("CertRequest", req).nullOrBlank("MechID", out.mechid); v.nullBlankMin("FQDNs", out.fqdns,1); - if(v.err()) { + if (v.err()) { return Result.err(Result.ERR_BadData, v.errs()); } out.emails = in.getEmail(); @@ -217,7 +217,7 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { @Override public List<ArtiDAO.Data> toArtifact(AuthzTrans trans, Artifacts artifacts) { List<ArtiDAO.Data> ladd = new ArrayList<>(); - for(Artifact arti : artifacts.getArtifact()) { + for (Artifact arti : artifacts.getArtifact()) { ArtiDAO.Data data = new ArtiDAO.Data(); data.mechid = arti.getMechid(); data.machine = arti.getMachine(); @@ -235,11 +235,11 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { data.expires = null; // Derive Optional Data from Machine (Domain) if exists - if(data.machine!=null) { - if(data.ca==null && data.machine.endsWith(".att.com")) { + if (data.machine!=null) { + if (data.ca==null && data.machine.endsWith(".att.com")) { data.ca = "aaf"; // default } - if(data.ns==null ) { + if (data.ns==null ) { data.ns=FQI.reverseDomain(data.machine); } } @@ -254,9 +254,9 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { */ @Override public Result<Artifacts> fromArtifacts(Result<List<Data>> lArtiDAO) { - if(lArtiDAO.isOK()) { + if (lArtiDAO.isOK()) { Artifacts artis = new Artifacts(); - for(ArtiDAO.Data arti : lArtiDAO.value) { + for (ArtiDAO.Data arti : lArtiDAO.value) { Artifact a = new Artifact(); a.setMechid(arti.mechid); a.setMachine(arti.machine); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java index d85ea2ca..55a292e0 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/mapper/Mapper2_0.java @@ -86,7 +86,7 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { err.setMessageId(msgID); // AT&T Restful Error Format requires numbers "%" placements err.setText(Vars.convert(holder, text, var)); - for(String s : var) { + for (String s : var) { err.getVariables().add(s); } return err; @@ -100,25 +100,25 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { */ @Override public Result<CertInfo> toCert(AuthzTrans trans, Result<CertResp> in, boolean withTrustChain) throws IOException { - if(!in.isOK()) { + if (!in.isOK()) { CertResp cin = in.value; CertInfo cout = newInstance(API.CERT); cout.setPrivatekey(cin.privateString()); String value; - if((value=cin.challenge())!=null) { + if ((value=cin.challenge())!=null) { cout.setChallenge(value); } cout.getCerts().add(cin.asCertString()); - if(cin.trustChain()!=null) { - for(String c : cin.trustChain()) { + if (cin.trustChain()!=null) { + for (String c : cin.trustChain()) { cout.getCerts().add(c); } } - if(cin.notes()!=null) { + if (cin.notes()!=null) { boolean first = true; StringBuilder sb = new StringBuilder(); - for(String n : cin.notes()) { - if(first) { + for (String n : cin.notes()) { + if (first) { first = false; } else { sb.append('\n'); @@ -129,7 +129,7 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { } List<String> caIssuerDNs = cout.getCaIssuerDNs(); - for(String s : cin.caIssuerDNs()) { + for (String s : cin.caIssuerDNs()) { caIssuerDNs.add(s); } @@ -143,10 +143,10 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { @Override public Result<CertInfo> toCert(AuthzTrans trans, Result<List<CertDAO.Data>> in) { - if(in.isOK()) { + if (in.isOK()) { CertInfo cout = newInstance(API.CERT); List<String> certs = cout.getCerts(); - for(CertDAO.Data cdd : in.value) { + for (CertDAO.Data cdd : in.value) { certs.add(cdd.x509); } return Result.ok(cout); @@ -163,7 +163,7 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { CertificateRequest in; try { in = (CertificateRequest)req; - } catch(ClassCastException e) { + } catch (ClassCastException e) { return Result.err(Result.ERR_BadData,"Request is not a CertificateRequest"); } @@ -172,7 +172,7 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { v.isNull("CertRequest", req) .nullOrBlank("MechID", out.mechid=in.getMechid()); v.nullBlankMin("FQDNs", out.fqdns=in.getFqdns(),1); - if(v.err()) { + if (v.err()) { return Result.err(Result.ERR_BadData, v.errs()); } @@ -206,7 +206,7 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { @Override public List<ArtiDAO.Data> toArtifact(AuthzTrans trans, Artifacts artifacts) { List<ArtiDAO.Data> ladd = new ArrayList<>(); - for(Artifact arti : artifacts.getArtifact()) { + for (Artifact arti : artifacts.getArtifact()) { ArtiDAO.Data data = new ArtiDAO.Data(); data.mechid = arti.getMechid(); data.machine = arti.getMachine(); @@ -224,13 +224,13 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { data.expires = null; // Derive Optional Data from Machine (Domain) if exists - if(data.machine!=null) { - if(data.ca==null) { - if(data.machine.endsWith(".att.com")) { + if (data.machine!=null) { + if (data.ca==null) { + if (data.machine.endsWith(".att.com")) { data.ca = "aaf"; // default } } - if(data.ns==null ) { + if (data.ns==null ) { data.ns=FQI.reverseDomain(data.machine); } } @@ -245,9 +245,9 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { */ @Override public Result<Artifacts> fromArtifacts(Result<List<Data>> lArtiDAO) { - if(lArtiDAO.isOK()) { + if (lArtiDAO.isOK()) { Artifacts artis = new Artifacts(); - for(ArtiDAO.Data arti : lArtiDAO.value) { + for (ArtiDAO.Data arti : lArtiDAO.value) { Artifact a = new Artifact(); a.setMechid(arti.mechid); a.setMachine(arti.machine); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java index 62f0d680..89824a47 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/service/CMService.java @@ -164,7 +164,7 @@ public class CMService { } else { for (String cn : req.value.fqdns) { - if(!ignoreIPs) { + if (!ignoreIPs) { try { InetAddress[] ias = InetAddress.getAllByName(cn); Set<String> potentialSanNames = new HashSet<>(); @@ -186,7 +186,7 @@ public class CMService { } final String host; - if(ignoreIPs) { + if (ignoreIPs) { host = req.value.fqdns.get(0); } else if (primary == null) { return Result.err(Result.ERR_Denied, "Request not made from matching IP (%s)", trans.ip()); @@ -271,7 +271,7 @@ public class CMService { // Make sure Primary is the first in fqdns if (fqdns.size() > 1) { for (int i = 0; i < fqdns.size(); ++i) { - if(primary==null) { + if (primary==null) { trans.error().log("CMService var primary is null"); } else { String fg = fqdns.get(i); diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java index ea97dd0d..1a27b41f 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/validation/CertmanValidator.java @@ -49,13 +49,13 @@ public class CertmanValidator extends Validator{ private static final String ARTIFACTS_MUST_HAVE_AT_LEAST = "Artifacts must have at least "; public CertmanValidator nullBlankMin(String name, List<String> list, int min) { - if(list==null) { + if (list==null) { msg(name + IS_NULL); } else { - if(list.size()<min) { + if (list.size()<min) { msg(name + MUST_HAVE_AT_LEAST + min + ENTR + (min==1?Y:IES)); } else { - for(String s : list) { + for (String s : list) { nullOrBlank("List Item",s); } } @@ -64,13 +64,13 @@ public class CertmanValidator extends Validator{ } public CertmanValidator artisRequired(List<ArtiDAO.Data> list, int min) { - if(list==null) { + if (list==null) { msg(ARTIFACT_LIST_IS_NULL); } else { - if(list.size()<min) { + if (list.size()<min) { msg(ARTIFACTS_MUST_HAVE_AT_LEAST + min + ENTR + (min==1?Y:IES)); } else { - for(ArtiDAO.Data a : list) { + for (ArtiDAO.Data a : list) { allRequired(a); } } @@ -79,13 +79,13 @@ public class CertmanValidator extends Validator{ } public CertmanValidator artisKeys(List<ArtiDAO.Data> list, int min) { - if(list==null) { + if (list==null) { msg(ARTIFACT_LIST_IS_NULL); } else { - if(list.size()<min) { + if (list.size()<min) { msg(ARTIFACTS_MUST_HAVE_AT_LEAST + min + ENTR + (min==1?Y:IES)); } else { - for(ArtiDAO.Data a : list) { + for (ArtiDAO.Data a : list) { keys(a); } } @@ -95,7 +95,7 @@ public class CertmanValidator extends Validator{ public CertmanValidator keys(ArtiDAO.Data add) { - if(add==null) { + if (add==null) { msg("Artifact is null."); } else { nullOrBlank(MECHID, add.mechid); @@ -105,7 +105,7 @@ public class CertmanValidator extends Validator{ } private CertmanValidator allRequired(Data a) { - if(a==null) { + if (a==null) { msg("Artifact is null."); } else { nullOrBlank(MECHID, a.mechid); diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java index 7e6c3647..2eab9b2b 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/test/CertmanTest.java @@ -76,7 +76,7 @@ public class CertmanTest { // } // // Locator<URI> loc = new DNSLocator(env, "https", "aaf.it.att.com", "8150"); -// for(Item item = loc.first(); item!=null; item=loc.next(item)) { +// for (Item item = loc.first(); item!=null; item=loc.next(item)) { // System.out.println(loc.get(item)); // } // @@ -111,7 +111,7 @@ public class CertmanTest { // @Test // public void testX500Name() throws Exception { // -// for( InetAddress ia : InetAddress.getAllByName("aaf.dev.att.com")) { +// for ( InetAddress ia : InetAddress.getAllByName("aaf.dev.att.com")) { // System.out.printf("%s - %s\n", ia.getHostName(), ia.getHostAddress()); // InetAddress ia1 = InetAddress.getByName(ia.getHostAddress()); // System.out.printf("%s - %s\n", ia1.getHostName(), ia1.getHostAddress()); @@ -133,12 +133,12 @@ public class CertmanTest { // try { // System.out.println(reqDF.newData().option(Data.PRETTY).load(cr).asString()); // Future<String> f = client.updateRespondString(path, reqDF, cr); -// if(f.get(10000)) { +// if (f.get(10000)) { // end = System.nanoTime(); // System.out.println(f.body()); // CertInfo capi = certDF.newData().in(Data.TYPE.JSON).load(f.body()).asObject(); -// for(String c :capi.getCerts()) { -// for( java.security.cert.Certificate x509 : Factory.toX509Certificate(c)) { +// for (String c :capi.getCerts()) { +// for ( java.security.cert.Certificate x509 : Factory.toX509Certificate(c)) { // System.out.println(x509.toString()); // } // } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java index c308e775..ea366576 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/AAFcli.java @@ -161,7 +161,7 @@ public class AAFcli { sb.append(largs[idx], e, v); if ((e = largs[idx].indexOf(']', v)) >= 0) { String p = access.getProperty(largs[idx].substring(v + 2, e),null); - if(p==null) { + if (p==null) { p = System.getProperty(largs[idx].substring(v+2,e)); } ++e; @@ -183,7 +183,7 @@ public class AAFcli { while (rv && idx < largs.length) { // Allow Script to change Credential if (!gui) { - if("as".equalsIgnoreCase(largs[idx])) { + if ("as".equalsIgnoreCase(largs[idx])) { if (largs.length > ++idx) { // get Password from Props with ID as Key String user = largs[idx++]; @@ -255,13 +255,13 @@ public class AAFcli { } - if("REQUEST".equalsIgnoreCase(largs[idx])) { + if ("REQUEST".equalsIgnoreCase(largs[idx])) { request=true; ++idx; - } else if("FORCE".equalsIgnoreCase(largs[idx])) { + } else if ("FORCE".equalsIgnoreCase(largs[idx])) { force="true"; ++idx; - } else if("DETAILS".equalsIgnoreCase(largs[idx])) { + } else if ("DETAILS".equalsIgnoreCase(largs[idx])) { showDetails=true; ++idx; } else if ("set".equalsIgnoreCase(largs[idx])) { @@ -271,11 +271,11 @@ public class AAFcli { if (equals < 0) { tag = largs[idx]; value = access.getProperty(Config.AAF_APPPASS,null); - if(value==null) { + if (value==null) { break; } else { value = access.decrypt(value, false); - if(value==null) { + if (value==null) { break; } access.getProperties().put(tag, value); @@ -287,11 +287,11 @@ public class AAFcli { pw.println("set " + tag + ' ' + value); } boolean isTrue = "TRUE".equalsIgnoreCase(value); - if("FORCE".equalsIgnoreCase(tag)) { + if ("FORCE".equalsIgnoreCase(tag)) { force = value; - } else if("REQUEST".equalsIgnoreCase(tag)) { + } else if ("REQUEST".equalsIgnoreCase(tag)) { request = isTrue; - } else if("DETAILS".equalsIgnoreCase(tag)) { + } else if ("DETAILS".equalsIgnoreCase(tag)) { showDetails = isTrue; } else { access.getProperties().put(tag, value); @@ -380,7 +380,7 @@ public class AAFcli { } else { quote = ch; } - } else if(ch=='|' && quote==0) { + } else if (ch=='|' && quote==0) { arr.add(sb.toString()); sb.setLength(0); start = true; @@ -437,7 +437,7 @@ public class AAFcli { try { PropAccess access = aafsso.access(); - if(aafsso.ok()) { + if (aafsso.ok()) { Define.set(access); AuthzEnv env = new AuthzEnv(access); @@ -450,7 +450,7 @@ public class AAFcli { for (int i = 0; i < args.length; ++i) { if ("-i".equalsIgnoreCase(args[i])) { rdr = new InputStreamReader(System.in); - // } else if("-o".equalsIgnoreCase(args[i])) { + // } else if ("-o".equalsIgnoreCase(args[i])) { // // shall we do something different? Output stream is // already done... } else if ("-f".equalsIgnoreCase(args[i])) { @@ -488,7 +488,7 @@ public class AAFcli { aafsso.setStdErrDefault(); // Note, with AAF Locator, this may not longer be necessary 3/2018 Jonathan - if(!aafsso.loginOnly()) { + if (!aafsso.loginOnly()) { // try { // loc = new AAFLocator(si,new URI(access.getProperty(Config.AAF_URL))); // } catch (Throwable t) { @@ -502,7 +502,7 @@ public class AAFcli { TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); // HMangr hman = new HMangr(access, loc).readTimeout(TIMEOUT).apiVersion(Config.AAF_DEFAULT_VERSION); - if(access.getProperty(Config.AAF_DEFAULT_REALM)==null) { + if (access.getProperty(Config.AAF_DEFAULT_REALM)==null) { access.setProperty(Config.AAF_DEFAULT_REALM, "people.osaaf.org"); aafsso.addProp(Config.AAF_DEFAULT_REALM, "people.osaaf.org"); } @@ -511,13 +511,13 @@ public class AAFcli { aafcon.hman(), aafcon.securityInfo(), aafcon.securityInfo().defSS); // new HBasicAuthSS(si,aafsso.user(), access.decrypt(aafsso.enc_pass(),false))); // } - if(!ignoreDelay) { + if (!ignoreDelay) { File delay = new File("aafcli.delay"); - if(delay.exists()) { + if (delay.exists()) { BufferedReader br = new BufferedReader(new FileReader(delay)); try { globalDelay = Integer.parseInt(br.readLine()); - } catch(Exception e) { + } catch (Exception e) { access.log(Level.DEBUG,e); } finally { br.close(); @@ -596,7 +596,7 @@ public class AAFcli { System.err.println(err); } } - if(noexit==null) { + if (noexit==null) { return; } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java index 168d2753..77d1894f 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/BaseCmd.java @@ -45,20 +45,20 @@ public class BaseCmd<CMD extends Cmd> extends Cmd { @Override public int _exec( int idx, final String ... args) throws CadiException, APIException, LocatorException { - if(args.length-idx<1) { + if (args.length-idx<1) { pw().println(build(new StringBuilder(),null).toString()); } else { String s = args[idx]; String name; Cmd empty = null; - for(Cmd c: cmds) { + for (Cmd c: cmds) { name = c.getName(); - if(name==null && empty==null) { // Mark with Command is null, and take the first one. + if (name==null && empty==null) { // Mark with Command is null, and take the first one. empty = c; - } else if(s.equalsIgnoreCase(c.getName())) + } else if (s.equalsIgnoreCase(c.getName())) return c.exec(idx+1, args); } - if(empty!=null) { + if (empty!=null) { return empty.exec(idx, args); // If name is null, don't account for it on command line. Jonathan 4-29 } pw().println("Instructions not understood."); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java index 9ec126b4..3a0c869b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Cmd.java @@ -92,21 +92,21 @@ public abstract class Cmd { this.aafcli = aafcli; this.env = aafcli.env; this.access = aafcli.access; - if(parent!=null) { + if (parent!=null) { parent.children.add(this); } children = new ArrayList<>(); this.params = params; this.name = name; required=0; - for(Param p : params) { - if(p.required) { + for (Param p : params) { + if (p.required) { ++required; } } String temp = access.getProperty(Config.AAF_DEFAULT_REALM,null); - if(temp!=null && !temp.startsWith("@")) { + if (temp!=null && !temp.startsWith("@")) { defaultRealm = '@' + temp; } else { defaultRealm="<Set Default Realm>"; @@ -114,7 +114,7 @@ public abstract class Cmd { } public final int exec(int idx, String ... args) throws CadiException, APIException, LocatorException { - if(args.length-idx<required) { + if (args.length-idx<required) { throw new CadiException(build(new StringBuilder("Too few args: "),null).toString()); } return _exec(idx,args); @@ -135,7 +135,7 @@ public abstract class Cmd { protected void api(StringBuilder sb, int indent, HttpMethods meth, String pathInfo, Class<?> cls,boolean head) { final String smeth = meth.name(); - if(head) { + if (head) { sb.append('\n'); detailLine(sb,indent,"APIs:"); } @@ -145,7 +145,7 @@ public abstract class Cmd { sb.append(' '); sb.append(pathInfo); String cliString = aafcli.typeString(cls,true); - if(indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) { + if (indent+smeth.length()+pathInfo.length()+cliString.length()+2>80) { sb.append(" ..."); multiChar(sb,indent+3+smeth.length(),' ',0); } else { // same line @@ -156,54 +156,54 @@ public abstract class Cmd { protected void multiChar(StringBuilder sb, int length, char c, int indent) { sb.append('\n'); - for(int i=0;i<indent;++i)sb.append(' '); - for(int i=indent;i<length;++i)sb.append(c); + for (int i=0;i<indent;++i)sb.append(' '); + for (int i=indent;i<length;++i)sb.append(c); } public StringBuilder build(StringBuilder sb, StringBuilder detail) { - if(name!=null) { + if (name!=null) { sb.append(name); sb.append(' '); } int line = sb.lastIndexOf("\n")+1; - if(line<0) { + if (line<0) { line=0; } int indent = sb.length()-line; - for(Param p : params) { + for (Param p : params) { sb.append(p.required?'<':'['); sb.append(p.tag); sb.append(p.required?"> ": "] "); } boolean first = true; - for(Cmd child : children) { - if(!(child instanceof DeprecatedCMD)) { - if(first) { + for (Cmd child : children) { + if (!(child instanceof DeprecatedCMD)) { + if (first) { first = false; - } else if(detail==null) { + } else if (detail==null) { multiChar(sb,indent,' ',0); } else { // Write parents for Detailed Report Stack<String> stack = new Stack<String>(); - for(Cmd c = child.parent;c!=null;c=c.parent) { - if(c.name!=null) { + for (Cmd c = child.parent;c!=null;c=c.parent) { + if (c.name!=null) { stack.push(c.name); } } - if(!stack.isEmpty()) { + if (!stack.isEmpty()) { sb.append(" "); - while(!stack.isEmpty()) { + while (!stack.isEmpty()) { sb.append(stack.pop()); sb.append(' '); } } } child.build(sb,detail); - if(detail!=null) { + if (detail!=null) { child.detailedHelp(4, detail); // If Child wrote something, then add, bracketing by lines - if(detail.length()>0) { + if (detail.length()>0) { multiChar(sb,80,'-',2); sb.append(detail); sb.append('\n'); @@ -223,9 +223,9 @@ public abstract class Cmd { StringBuilder sb = new StringBuilder("Failed"); String desc = future.body(); int code = future.code(); - if(desc==null || desc.length()==0) { + if (desc==null || desc.length()==0) { withCode(sb,code); - } else if(desc.startsWith("{")) { + } else if (desc.startsWith("{")) { StringReader sr = new StringReader(desc); try { // Note: 11-18-2013, JonathanGathman. This rather convoluted Message Structure required by TSS Restful Specs, reflecting "Northbound" practices. @@ -240,7 +240,7 @@ public abstract class Cmd { String var = vars.get(varCounter); ++varCounter; if (messageBody.indexOf("%" + varCounter) >= 0) { - if((pipe = var.indexOf('|'))>=0) { // In AAF, we use a PIPE for Choice + if ((pipe = var.indexOf('|'))>=0) { // In AAF, we use a PIPE for Choice if (aafcli.isTest()) { String expiresStr = var.substring(pipe); var = var.replace(expiresStr, "[Placeholder]"); @@ -260,7 +260,7 @@ public abstract class Cmd { withCode(sb,code); sb.append(" (Note: Details cannot be obtained from Error Structure)"); } - } else if(desc.startsWith("<html>")){ // Core Jetty, etc sends HTML for Browsers + } else if (desc.startsWith("<html>")){ // Core Jetty, etc sends HTML for Browsers withCode(sb,code); } else { sb.append(" with code "); @@ -296,11 +296,11 @@ public abstract class Cmd { protected void setStartEnd(Request req) { // Set Start/End Dates, if exist String str; - if((str = access.getProperty(Cmd.STARTDATE,null))!=null) { + if ((str = access.getProperty(Cmd.STARTDATE,null))!=null) { req.setStart(Chrono.timeStamp(Date.valueOf(str))); } - if((str = access.getProperty(Cmd.ENDDATE,null))!=null) { + if ((str = access.getProperty(Cmd.ENDDATE,null))!=null) { req.setEnd(Chrono.timeStamp(Date.valueOf(str))); } } @@ -326,7 +326,7 @@ public abstract class Cmd { @SuppressWarnings("unchecked") public static <T> RosettaDF<T> getDF(AuthzEnv env, Class<T> cls) throws APIException { RosettaDF<T> rdf = (RosettaDF<T>)dfs.get(cls); - if(rdf == null) { + if (rdf == null) { rdf = env.newDataFactory(cls); dfs.put(cls, rdf); } @@ -341,11 +341,11 @@ public abstract class Cmd { } } else { pw().println(header); - for(int i=0;i<lineLength;++i)pw().print('-'); + for (int i=0;i<lineLength;++i)pw().print('-'); pw().println(); pw().format(hformat,"Date","Table","User","Memo"); - for(int i=0;i<lineLength;++i)pw().print('-'); + for (int i=0;i<lineLength;++i)pw().print('-'); pw().println(); // Save Server time by Sorting locally @@ -357,7 +357,7 @@ public abstract class Cmd { } }); - for(History.Item item : items) { + for (History.Item item : items) { GregorianCalendar gc = item.getTimestamp().toGregorianCalendar(); pw().format(hformat, dateFmt.format(gc.getTime()), @@ -376,8 +376,8 @@ public abstract class Cmd { public static String optionsToString(String[] options) { StringBuilder sb = new StringBuilder(); boolean first = true; - for(String s : options) { - if(first) { + for (String s : options) { + if (first) { first = false; } else { sb.append('|'); @@ -398,8 +398,8 @@ public abstract class Cmd { * @throws Exception */ public int whichOption(String[] options, String test) throws CadiException { - for(int i=0;i<options.length;++i) { - if(options[i].equals(test)) { + for (int i=0;i<options.length;++i) { + if (options[i].equals(test)) { return i; } } @@ -416,7 +416,7 @@ public abstract class Cmd { public<RET> RET same(Retryable<RET> retryable) throws APIException, CadiException, LocatorException { // We're storing in AAFCli, because we know it's always the same, and single threaded - if(aafcli.prevCall!=null) { + if (aafcli.prevCall!=null) { retryable.item(aafcli.prevCall.item()); retryable.lastClient=aafcli.prevCall.lastClient; } @@ -450,9 +450,9 @@ public abstract class Cmd { pw().println(); boolean first = true; int i=0; - for(String s : str) { - if(first) { - if(++i>1) { + for (String s : str) { + if (first) { + if (++i>1) { first = false; pw().print("["); } @@ -461,7 +461,7 @@ public abstract class Cmd { } pw().print(s); } - if(!first) { + if (!first) { pw().print(']'); } pw().println(); @@ -475,25 +475,25 @@ public abstract class Cmd { } public void reportLine() { - for(int i=0;i<lineLength;++i)pw().print('-'); + for (int i=0;i<lineLength;++i)pw().print('-'); pw().println(); } protected void setQueryParamsOn(Rcli<?> rcli) { StringBuilder sb=null; String force; - if((force=aafcli.forceString())!=null) { + if ((force=aafcli.forceString())!=null) { sb = new StringBuilder("force="); sb.append(force); } - if(aafcli.addRequest()) { - if(sb==null) { + if (aafcli.addRequest()) { + if (sb==null) { sb = new StringBuilder("future=true"); } else { sb.append("&future=true"); } } - if(sb!=null && rcli!=null) { + if (sb!=null && rcli!=null) { rcli.setQueryParams(sb.toString()); } } @@ -504,7 +504,7 @@ public abstract class Cmd { // * @return // */ // protected String checkForce() { -// if(TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) { +// if (TRUE.equalsIgnoreCase(env.getProperty(FORCE, FALSE))) { // env.setProperty(FORCE, FALSE); // return "true"; // } @@ -513,7 +513,7 @@ public abstract class Cmd { public String toString() { StringBuilder sb = new StringBuilder(); - if(parent==null) { // ultimate parent + if (parent==null) { // ultimate parent build(sb,null); return sb.toString(); } else { @@ -530,7 +530,7 @@ public abstract class Cmd { * @throws OrganizationException */ public String fullID(String id) { - if(id != null) { + if (id != null) { if (id.indexOf('@') < 0) { id+=defaultRealm; } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java index bd70d9e5..66a3355a 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Help.java @@ -53,27 +53,27 @@ public class Help extends Cmd { details = aafcli.isDetailed()?new StringBuilder():null; String comp = args.length>idx?args[idx++]:null; - if("help".equalsIgnoreCase(comp)) { + if ("help".equalsIgnoreCase(comp)) { build(sb,null); detailedHelp(4, sb); sb.append('\n'); } else { - for(Cmd c : cmds) { - if(!(c instanceof DeprecatedCMD)) { - if(comp!=null) { - if(comp.equals(c.getName())) { + for (Cmd c : cmds) { + if (!(c instanceof DeprecatedCMD)) { + if (comp!=null) { + if (comp.equals(c.getName())) { multiChar(sb,2,' ',0); c.build(sb,details); } } else { - if(first) { + if (first) { first=false; } else { multiChar(sb,80,'-',2); } multiChar(sb,2,' ',0); c.build(sb,details); - if(details!=null) { + if (details!=null) { c.detailedHelp(4, sb); // multiChar(sb,80,'-',2); } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java index ca8a72ca..5c74dda8 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Clear.java @@ -48,7 +48,7 @@ public class Clear extends Cmd { public int _exec(int _idx, String ... args) throws CadiException, APIException, LocatorException { int idx = _idx; int rv=409; - for(final String name : args[idx++].split(COMMA)) { + for (final String name : args[idx++].split(COMMA)) { rv = all(new Retryable<Integer>() { @Override public Integer code(Rcli<?> client) throws APIException, CadiException { @@ -57,11 +57,11 @@ public class Clear extends Cmd { "/mgmt/cache/"+name, Void.class ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Cleared Cache for " + name + " on " + client); rv=200; } else { - if(rv==409)rv = fp.code(); + if (rv==409)rv = fp.code(); error(fp); } return rv; diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java index 17f23729..159a51bc 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Deny.java @@ -59,9 +59,9 @@ public class Deny extends BaseCmd<Mgmt> { String action = args[idx++]; final int option = whichOption(options, action); int rv=409; - for(final String name : args[idx++].split(COMMA)) { + for (final String name : args[idx++].split(COMMA)) { final String append; - if(isID && name.indexOf("@")<0) { + if (isID && name.indexOf("@")<0) { append='@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); } else { append = ""; @@ -82,11 +82,11 @@ public class Deny extends BaseCmd<Mgmt> { fp = client.delete(path, Void.class); resp = " deleted"; } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println(name + append + resp + " on " + client); rv=fp.code(); } else { - if(rv==409)rv = fp.code(); + if (rv==409)rv = fp.code(); error(fp); } return rv; diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java index 535de3bb..db59df0a 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/Log.java @@ -49,9 +49,9 @@ public class Log extends BaseCmd<Mgmt> { int idx = _idx; final int option = whichOption(options, args[idx++]); - for(String name : args[idx++].split(COMMA)) { + for (String name : args[idx++].split(COMMA)) { final String fname; - if(name.indexOf("@")<0) { + if (name.indexOf("@")<0) { fname=name+'@'+ access.getProperty(Config.AAF_DEFAULT_REALM,null); } else { fname = name; @@ -78,12 +78,12 @@ public class Log extends BaseCmd<Mgmt> { msg = "Ignored"; } - if(fp!=null) { - if(fp.get(AAFcli.timeout())) { + if (fp!=null) { + if (fp.get(AAFcli.timeout())) { pw().println(msg + " Special Log for " + fname + " on " + client); rv=200; } else { - if(rv==409)rv = fp.code(); + if (rv==409)rv = fp.code(); error(fp); } return rv; diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java index a52d5dc7..cd10ef60 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/mgmt/SessClear.java @@ -56,11 +56,11 @@ public class SessClear extends Cmd { "/mgmt/dbsession", Void.class ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Cleared DBSession on " + client); rv=200; } else { - if(rv==409)rv = fp.code(); + if (rv==409)rv = fp.code(); error(fp); } return rv; diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java index f1952fa9..90141819 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Admin.java @@ -54,7 +54,7 @@ public class Admin extends BaseCmd<NS> { @Override public Integer code(Rcli<?> client) throws CadiException, APIException { Future<Void> fp = null; - for(String id : ids) { + for (String id : ids) { id = fullID(id); String verb; switch(option) { @@ -70,7 +70,7 @@ public class Admin extends BaseCmd<NS> { throw new CadiException("Bad Argument"); }; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().append("Admin "); pw().append(id); pw().append(verb); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java index f1b2621d..31dad45c 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Attrib.java @@ -50,8 +50,8 @@ public class Attrib extends BaseCmd<NS> { final String ns = args[idx+1]; final String key = args[idx+2]; final String value; - if(option!=2) { - if(args.length<=idx+3) { + if (option!=2) { + if (args.length<=idx+3) { throw new CadiException("Not added: Need more Data"); } value = args[idx+3]; @@ -83,10 +83,10 @@ public class Attrib extends BaseCmd<NS> { default: throw new CadiException("Bad Argument"); }; - if(fp==null) { + if (fp==null) { return 500; } else { - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println(message); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java index 1719ada7..05d66881 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Create.java @@ -56,16 +56,16 @@ public class Create extends Cmd { nr.setName(args[idx++]); String[] responsible = args[idx++].split(COMMA); - for(String s : responsible) { + for (String s : responsible) { nr.getResponsible().add(fullID(s)); } String[] admin; - if(args.length>idx) { + if (args.length>idx) { admin = args[idx++].split(COMMA); } else { admin = responsible; } - for(String s : admin) { + for (String s : admin) { nr.getAdmin().add(fullID(s)); } @@ -82,10 +82,10 @@ public class Create extends Cmd { getDF(NsRequest.class), nr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Created Namespace"); } else { - if(fp.code()==202) { + if (fp.code()==202) { pw().println("Namespace Creation Accepted, but requires Approvals before actualizing"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java index 99ac7ed2..7da6c26b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Delete.java @@ -56,7 +56,7 @@ public class Delete extends Cmd { setQueryParamsOn(client); Future<Void> fp = client.delete(path.toString(),Void.class); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Deleted Namespace"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java index 18823297..e521d616 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Describe.java @@ -70,11 +70,11 @@ public class Describe extends Cmd { nsr ); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { rv=fn.code(); pw().println("Description added to Namespace"); } else { - if((rv=fn.code())==202) { + if ((rv=fn.code())==202) { pw().print("Adding description"); pw().println(" Accepted, but requires Approvals before actualizing"); } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java index 01b3ad14..8fc79401 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/List.java @@ -58,34 +58,34 @@ public class List extends BaseCmd<NS> { public void report(Future<Nss> fp, String ... str) { reportHead(str); - if(fp==null) { + if (fp==null) { pw().println(" *** Namespace Not Found ***"); } - if(fp!=null && fp.value!=null) { - for(Ns ns : fp.value.getNs()) { + if (fp!=null && fp.value!=null) { + for (Ns ns : fp.value.getNs()) { pw().println(ns.getName()); if (this.aafcli.isDetailed()) { pw().println(" Description"); pw().format(sformat,ns.getDescription()==null?"":ns.getDescription()); } - if(ns.getAdmin().size()>0) { + if (ns.getAdmin().size()>0) { pw().println(" Administrators"); - for(String admin : ns.getAdmin()) { + for (String admin : ns.getAdmin()) { pw().format(sformat,admin); } } - if(ns.getResponsible().size()>0) { + if (ns.getResponsible().size()>0) { pw().println(" Owners (Responsible for Namespace)"); - for(String responsible : ns.getResponsible()) { + for (String responsible : ns.getResponsible()) { pw().format(sformat,responsible); } } - if(ns.getAttrib().size()>0) { + if (ns.getAttrib().size()>0) { pw().println(" Namespace Attributes"); - for( Ns.Attrib attr : ns.getAttrib()) { + for ( Ns.Attrib attr : ns.getAttrib()) { StringBuilder sb = new StringBuilder(attr.getKey()); - if(attr.getValue()==null || attr.getValue().length()>0) { + if (attr.getValue()==null || attr.getValue().length()>0) { sb.append('='); sb.append(attr.getValue()); } @@ -99,7 +99,7 @@ public class List extends BaseCmd<NS> { public void reportName(Future<Nss> fp, String ... str) { reportHead(str); - if(fp!=null && fp.value!=null) { + if (fp!=null && fp.value!=null) { java.util.List<Ns> nss = fp.value.getNs(); Collections.sort(nss, new Comparator<Ns>() { @Override @@ -108,7 +108,7 @@ public class List extends BaseCmd<NS> { } }); - for(Ns ns : nss) { + for (Ns ns : nss) { pw().println(ns.getName()); if (this.aafcli.isDetailed() && ns.getDescription() != null) { pw().println(" " + ns.getDescription()); @@ -118,9 +118,9 @@ public class List extends BaseCmd<NS> { } public void reportRole(Future<Roles> fr) { - if(fr!=null && fr.value!=null && fr.value.getRole().size()>0) { + if (fr!=null && fr.value!=null && fr.value.getRole().size()>0) { pw().println(" Roles"); - for(aaf.v2_0.Role r : fr.value.getRole()) { + for (aaf.v2_0.Role r : fr.value.getRole()) { pw().format(sformat,r.getName()); } } @@ -128,9 +128,9 @@ public class List extends BaseCmd<NS> { private static final String pformat = " %-30s %-24s %-15s\n"; public void reportPerm(Future<Perms> fp) { - if(fp!=null && fp.value!=null && fp.value.getPerm().size()>0) { + if (fp!=null && fp.value!=null && fp.value.getPerm().size()>0) { pw().println(" Permissions"); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { + for (aaf.v2_0.Perm p : fp.value.getPerm()) { pw().format(pformat,p.getType(),p.getInstance(),p.getAction()); } } @@ -139,7 +139,7 @@ public class List extends BaseCmd<NS> { private static final String cformat = " %-30s %-6s %-24s\n"; public void reportCred(Future<Users> fc) { - if(fc!=null && fc.value!=null && fc.value.getUser().size()>0) { + if (fc!=null && fc.value!=null && fc.value.getUser().size()>0) { pw().println(" Credentials"); java.util.List<User> users = fc.value.getUser(); Collections.sort(users, new Comparator<User>() { @@ -148,7 +148,7 @@ public class List extends BaseCmd<NS> { return u1.getId().compareTo(u2.getId()); } }); - for(aaf.v2_0.Users.User u : users) { + for (aaf.v2_0.Users.User u : users) { if (this.aafcli.isTest()) { pw().format(sformat,u.getId()); } else { @@ -160,7 +160,7 @@ public class List extends BaseCmd<NS> { public static String getType(User u) { Integer type; - if((type=u.getType())==null) { + if ((type=u.getType())==null) { type = 9999; } switch(type) { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java index 52b9a108..f8f82466 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListActivity.java @@ -59,7 +59,7 @@ public class ListActivity extends Cmd { getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value, HEADER + " [ " + ns + " ]"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java index 06de6cab..e62207a0 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListAdminResponsible.java @@ -56,9 +56,9 @@ public class ListAdminResponsible extends Cmd { String apipart = "owner".equals(title)?"responsible":title; Future<Nss> fn = client.read("/authz/nss/"+apipart+"/"+user,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { ((List)parent).reportName(fn,HEADER + title + " privileges for ",user); - } else if(fn.code()==404) { + } else if (fn.code()==404) { ((List)parent).report(null,HEADER + title + " privileges for ",user); return 200; } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java index ffd3cf01..3189b88b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListByName.java @@ -59,29 +59,29 @@ public class ListByName extends Cmd { @Override public Integer code(Rcli<?> client) throws CadiException, APIException { Future<Nss> fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { ((List)parent).report(fn,HEADER,ns); - if(fn.value!=null) { - for(Ns n : fn.value.getNs()) { + if (fn.value!=null) { + for (Ns n : fn.value.getNs()) { Future<Roles> fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); - if(fr.get(AAFcli.timeout())) { + if (fr.get(AAFcli.timeout())) { ((List)parent).reportRole(fr); } } - for(Ns n : fn.value.getNs()) { + for (Ns n : fn.value.getNs()) { Future<Perms> fp = client.read("/authz/perms/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":""), getDF(Perms.class)); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { ((List)parent).reportPerm(fp); } } - for(Ns n : fn.value.getNs()) { + for (Ns n : fn.value.getNs()) { Future<Users> fu = client.read("/authn/creds/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":""), getDF(Users.class)); - if(fu.get(AAFcli.timeout())) { + if (fu.get(AAFcli.timeout())) { ((List)parent).reportCred(fu); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { ((List)parent).report(null,HEADER,ns); return 200; } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java index 6d514df8..b3b0bcfc 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListChildren.java @@ -56,12 +56,12 @@ public class ListChildren extends Cmd { @Override public Integer code(Rcli<?> client) throws CadiException, APIException { Future<Nss> fn = client.read("/authz/nss/children/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { parent.reportHead(HEADER); - for(Ns ns : fn.value.getNs()) { + for (Ns ns : fn.value.getNs()) { pw().format(List.kformat, ns.getName()); } - } else if(fn.code()==404) { + } else if (fn.code()==404) { ((List)parent).report(null,HEADER,ns); return 200; } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java index df72ff08..01b0f21c 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListNsKeysByAttrib.java @@ -58,12 +58,12 @@ public class ListNsKeysByAttrib extends Cmd { @Override public Integer code(Rcli<?> client) throws CadiException, APIException { Future<Keys> fn = client.read("/authz/ns/attrib/"+attrib,getDF(Keys.class)); - if(fn.get(AAFcli.timeout())) { + if (fn.get(AAFcli.timeout())) { parent.reportHead(HEADER); - for(String key : fn.value.getKey()) { + for (String key : fn.value.getKey()) { pw().printf(List.kformat, key); } - } else if(fn.code()==404) { + } else if (fn.code()==404) { parent.reportHead(HEADER); pw().println(" *** No Namespaces Found ***"); return 200; diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java index 1347b918..eadf1c97 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersContact.java @@ -65,42 +65,42 @@ public class ListUsersContact extends Cmd { public Integer code(Rcli<?> client) throws CadiException, APIException { ((ListUsers)parent).report(HEADER,ns); Future<Nss> fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - if(fn.value!=null) { + if (fn.get(AAFcli.timeout())) { + if (fn.value!=null) { Set<String> uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { + for (Ns n : fn.value.getNs()) { Future<Roles> fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); - if(fr.get(AAFcli.timeout())) { - for(Role r : fr.value.getRole()) { - if(detail) { + if (fr.get(AAFcli.timeout())) { + for (Role r : fr.value.getRole()) { + if (detail) { ((ListUsers)parent).report(r.getName()); } Future<Users> fus = client.read( "/authz/users/role/"+r.getName(), getDF(Users.class) ); - if(fus.get(AAFcli.timeout())) { - for(User u : fus.value.getUser()) { - if(detail) { + if (fus.get(AAFcli.timeout())) { + for (User u : fus.value.getUser()) { + if (detail) { ((ListUsers)parent).report(" ",u); } else { uset.add(u.getId()); } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } } } } - if(uset!=null) { - for(String u : uset) { + if (uset!=null) { + for (String u : uset) { pw().print(" "); pw().println(u); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } else { error(fn); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java index 301e1508..c0838cb7 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersInRole.java @@ -65,42 +65,42 @@ public class ListUsersInRole extends Cmd { public Integer code(Rcli<?> client) throws CadiException, APIException { ((ListUsers)parent).report(HEADER,ns); Future<Nss> fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - if(fn.value!=null) { + if (fn.get(AAFcli.timeout())) { + if (fn.value!=null) { Set<String> uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { + for (Ns n : fn.value.getNs()) { Future<Roles> fr = client.read("/authz/roles/ns/"+n.getName(), getDF(Roles.class)); - if(fr.get(AAFcli.timeout())) { - for(Role r : fr.value.getRole()) { - if(detail) { + if (fr.get(AAFcli.timeout())) { + for (Role r : fr.value.getRole()) { + if (detail) { ((ListUsers)parent).report(r.getName()); } Future<Users> fus = client.read( "/authz/users/role/"+r.getName(), getDF(Users.class) ); - if(fus.get(AAFcli.timeout())) { - for(User u : fus.value.getUser()) { - if(detail) { + if (fus.get(AAFcli.timeout())) { + for (User u : fus.value.getUser()) { + if (detail) { ((ListUsers)parent).report(" ",u); } else { uset.add(u.getId()); } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } } } } - if(uset!=null) { - for(String u : uset) { + if (uset!=null) { + for (String u : uset) { pw().print(" "); pw().println(u); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } else { error(fn); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java index 472070d9..96ca95ee 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/ListUsersWithPerm.java @@ -65,42 +65,42 @@ public class ListUsersWithPerm extends Cmd { public Integer code(Rcli<?> client) throws CadiException, APIException { ((ListUsers)parent).report(HEADER,ns); Future<Nss> fn = client.read("/authz/nss/"+ns,getDF(Nss.class)); - if(fn.get(AAFcli.timeout())) { - if(fn.value!=null) { + if (fn.get(AAFcli.timeout())) { + if (fn.value!=null) { Set<String> uset = detail?null:new HashSet<>(); - for(Ns n : fn.value.getNs()) { + for (Ns n : fn.value.getNs()) { Future<Perms> fp = client.read("/authz/perms/ns/"+n.getName()+(aafcli.isDetailed()?"?ns":"") , getDF(Perms.class)); - if(fp.get(AAFcli.timeout())) { - for(Perm p : fp.value.getPerm()) { + if (fp.get(AAFcli.timeout())) { + for (Perm p : fp.value.getPerm()) { String perm = p.getType()+'/'+p.getInstance()+'/'+p.getAction(); - if(detail)((ListUsers)parent).report(perm); + if (detail)((ListUsers)parent).report(perm); Future<Users> fus = client.read( "/authz/users/perm/"+perm, getDF(Users.class) ); - if(fus.get(AAFcli.timeout())) { - for(User u : fus.value.getUser()) { - if(detail) + if (fus.get(AAFcli.timeout())) { + for (User u : fus.value.getUser()) { + if (detail) ((ListUsers)parent).report(" ",u); else uset.add(u.getId()); } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } } } } - if(uset!=null) { - for(String u : uset) { + if (uset!=null) { + for (String u : uset) { pw().print(" "); pw().println(u); } } } - } else if(fn.code()==404) { + } else if (fn.code()==404) { return 200; } else { error(fn); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java index e5e50187..35dd6b96 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/ns/Owner.java @@ -55,7 +55,7 @@ public class Owner extends BaseCmd<NS> { @Override public Integer code(Rcli<?> client) throws CadiException, APIException { Future<Void> fp=null; - for(String id : ids) { + for (String id : ids) { id=fullID(id); String verb; switch(option) { @@ -71,7 +71,7 @@ public class Owner extends BaseCmd<NS> { throw new CadiException("Bad Argument"); }; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().append(id); pw().append(verb); pw().append("responsible for "); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java index 1f123cff..be49cf28 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Create.java @@ -65,9 +65,9 @@ public class Create extends Cmd { boolean force = aafcli.forceString()!=null; int rv; - if(roles!=null && force) { // Make sure Roles are Created + if (roles!=null && force) { // Make sure Roles are Created RoleRequest rr = new RoleRequest(); - for(String role : roles) { + for (String role : roles) { rr.setName(role);; Future<RoleRequest> fr = client.create( "/authz/role", @@ -96,13 +96,13 @@ public class Create extends Cmd { getDF(PermRequest.class), pr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv = fp.code(); pw().println("Created Permission"); - if(roles!=null) { - if(aafcli.forceString()!=null) { // Make sure Roles are Created + if (roles!=null) { + if (aafcli.forceString()!=null) { // Make sure Roles are Created RoleRequest rr = new RoleRequest(); - for(String role : roles) { + for (String role : roles) { rr.setName(role);; Future<RoleRequest> fr = client.create( "/authz/role", @@ -120,7 +120,7 @@ public class Create extends Cmd { } try { - if(201!=(rv=((Perm)parent)._exec(0, + if (201!=(rv=((Perm)parent)._exec(0, new String[] {"grant",pr.getType(),pr.getInstance(),pr.getAction(),roleCommas}))) { rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; } @@ -130,9 +130,9 @@ public class Create extends Cmd { } } else { rv = fp.code(); - if(rv==409 && force) { + if (rv==409 && force) { rv = 201; - } else if(rv==202) { + } else if (rv==202) { pw().println("Permission Creation Accepted, but requires Approvals before actualizing"); if (roles!=null) pw().println("You need to grant the roles after approval."); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java index ed52a071..0f0c0011 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Delete.java @@ -65,10 +65,10 @@ public class Delete extends Cmd { "/authz/perm", getDF(PermRequest.class), pk); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Deleted Permission"); } else { - if(fp.code()==202) { + if (fp.code()==202) { pw().println("Permission Deletion Accepted, but requires Approvals before actualizing"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java index 8396f7d3..bb894ca7 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Describe.java @@ -76,11 +76,11 @@ public class Describe extends Cmd { pr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv=fp.code(); pw().println("Description added to Permission"); } else { - if((rv=fp.code())==202) { + if ((rv=fp.code())==202) { pw().print("Adding description"); pw().println(" Accepted, but requires Approvals before actualizing"); } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java index 4ed411ba..dd45fb4b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Grant.java @@ -75,9 +75,9 @@ public class Grant extends Cmd { if (option != 2) { String[] roles = args[idx++].split(","); String strA,strB; - for(String role : roles) { + for (String role : roles) { rpr.setRole(role); - if(option==0) { + if (option==0) { // You can request to Grant Permission to a Role setQueryParamsOn(client); frpr = client.create( @@ -98,7 +98,7 @@ public class Grant extends Cmd { strA = "UnGranted Permission ["; strB = "] from Role ["; } - if(frpr.get(AAFcli.timeout())) { + if (frpr.get(AAFcli.timeout())) { pw().println(strA + pk.getType() + '|' + pk.getInstance() + '|' + pk.getAction() + strB + role +']'); } else { @@ -122,7 +122,7 @@ public class Grant extends Cmd { "/authz/role/perm", getDF(RolePermRequest.class), rpr); - if(frpr.get(AAFcli.timeout())) { + if (frpr.get(AAFcli.timeout())) { pw().println("Set Permission's Roles to [" + allRoles + "]"); } else { error(frpr); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java index 48b8a488..5df2afa2 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/List.java @@ -48,7 +48,7 @@ public class List extends BaseCmd<Perm> { // Package Level on purpose abstract class ListPerms extends Retryable<Integer> { protected int list(Future<Perms> fp,String header, String parentPerm) throws CadiException, APIException { - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { report(fp,header, parentPerm); } else { error(fp); @@ -61,10 +61,10 @@ public class List extends BaseCmd<Perm> { @Override public int compare(aaf.v2_0.Perm a, aaf.v2_0.Perm b) { int rc; - if((rc=a.getType().compareTo(b.getType()))!=0) { + if ((rc=a.getType().compareTo(b.getType()))!=0) { return rc; } - if((rc=a.getInstance().compareTo(b.getInstance()))!=0) { + if ((rc=a.getInstance().compareTo(b.getInstance()))!=0) { return rc; } return a.getAction().compareTo(b.getAction()); @@ -80,9 +80,9 @@ public class List extends BaseCmd<Perm> { String descFmt = " %-75s\n"; reportColHead(format + descFmt,"[PERM NS].Type","Instance","Action", "Description"); Collections.sort(fp.value.getPerm(),permCompare); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { + for (aaf.v2_0.Perm p : fp.value.getPerm()) { String pns = p.getNs(); - if(pns==null) { + if (pns==null) { pw().format(format, p.getType(), p.getInstance(), @@ -94,7 +94,7 @@ public class List extends BaseCmd<Perm> { p.getAction()); } String desc = p.getDescription(); - if(desc!=null && desc.length()>0) { + if (desc!=null && desc.length()>0) { pw().format(descFmt,p.getDescription()); } } @@ -103,7 +103,7 @@ public class List extends BaseCmd<Perm> { String format = reportColHead(permFormat,"PERM Type","Instance","Action"); Collections.sort(fp.value.getPerm(),permCompare); - for(aaf.v2_0.Perm p : fp.value.getPerm()) { + for (aaf.v2_0.Perm p : fp.value.getPerm()) { pw().format(format, p.getType(), p.getInstance(), diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java index c59e9b5a..c96220a5 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListActivity.java @@ -57,7 +57,7 @@ public class ListActivity extends Cmd { "/authz/hist/perm/"+type, getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value, HEADER + " [ " + type + " ]"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java index 550386cf..325f45db 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/ListByUser.java @@ -51,12 +51,12 @@ public class ListByUser extends Cmd { @Override public Integer code(Rcli<?> client) throws CadiException, APIException { StringBuilder sb = null; - if("true".equalsIgnoreCase(aafcli.forceString())) { + if ("true".equalsIgnoreCase(aafcli.forceString())) { sb = new StringBuilder(); sb.append("?force"); } - if(aafcli.isDetailed()) { - if(sb==null) { + if (aafcli.isDetailed()) { + if (sb==null) { sb = new StringBuilder('?'); } else { sb.append('&'); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java index 620e1e04..dbadd8a0 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/perm/Rename.java @@ -71,12 +71,12 @@ public class Rename extends Cmd { pr ); int rv; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv = fp.code(); pw().println("Updated Permission"); } else { rv = fp.code(); - if(rv==202) { + if (rv==202) { pw().println("Permission Update Accepted, but requires Approvals before actualizing"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java index f9dcbcd8..320bac5b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/CreateDelete.java @@ -90,17 +90,17 @@ public class CreateDelete extends Cmd { } boolean rolesSupplied = (args.length>idx); - if(fp == null) {// This useless code brought to you by Sonar. + if (fp == null) {// This useless code brought to you by Sonar. throw new CadiException("No call made."); } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv=fp.code(); pw().print(verb); pw().println("d Role"); - if(rolesSupplied) { - for(;args.length>idx;++idx ) { + if (rolesSupplied) { + for (;args.length>idx;++idx ) { try { - if(201!=(rv=((Role)parent)._exec(0,new String[] {"user","add",rr.getName(),args[idx]}))) { + if (201!=(rv=((Role)parent)._exec(0,new String[] {"user","add",rr.getName(),args[idx]}))) { rv = 206 /*HttpStatus.PARTIAL_CONTENT_206*/; } } catch (LocatorException e) { @@ -109,7 +109,7 @@ public class CreateDelete extends Cmd { } } } else { - if((rv=fp.code())==202) { + if ((rv=fp.code())==202) { pw().print("Role "); pw().print(verb); pw().println(" Accepted, but requires Approvals before actualizing"); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java index e8001040..f4d24fb1 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/Describe.java @@ -70,11 +70,11 @@ public class Describe extends Cmd { rr ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { rv=fp.code(); pw().println("Description added to role"); } else { - if((rv=fp.code())==202) { + if ((rv=fp.code())==202) { pw().print("Adding description"); pw().println(" Accepted, but requires Approvals before actualizing"); } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java index ec8d8ee3..f8a633af 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/List.java @@ -61,16 +61,16 @@ public class List extends BaseCmd<Role> { // Package Level on purpose abstract class ListRoles extends Retryable<Integer> { protected int list(Future<Roles> fr,Rcli<?> client, String header) throws APIException, CadiException { - if(fr.get(AAFcli.timeout())) { + if (fr.get(AAFcli.timeout())) { Perms perms=null; if (aafcli.isDetailed()) { - for(aaf.v2_0.Role r : fr.value.getRole()) { + for (aaf.v2_0.Role r : fr.value.getRole()) { Future<Perms> fp = client.read( "/authz/perms/role/"+r.getName()+(aafcli.isDetailed()?"?ns":""), getDF(Perms.class) ); - if(fp.get(AAFcli.timeout())) { - if(perms==null) { + if (fp.get(AAFcli.timeout())) { + if (perms==null) { perms = fp.value; } else { perms.getPerm().addAll(fp.value.getPerm()); @@ -101,7 +101,7 @@ public class List extends BaseCmd<Role> { public void report(Roles roles, Perms perms, UserRoles urs, String ... str) { reportHead(str); XMLGregorianCalendar now = Chrono.timeStamp().normalize(); - if(roles==null || roles.getRole().isEmpty()) { + if (roles==null || roles.getRole().isEmpty()) { pw().println("<No Roles Found>"); } else if (aafcli.isDetailed()){ if (aafcli.isDetailed() && str[0].toLowerCase().contains(LIST_ROLES_BY_NAME)) { @@ -113,25 +113,25 @@ public class List extends BaseCmd<Role> { String fullFormat = roleFormat+permFormat; reportColHead(fullFormat,"[ROLE NS].Name","","[PERM NS].Type","Instance","Action"); Collections.sort(roles.getRole(),roleCompare); - for(aaf.v2_0.Role r : roles.getRole()) { + for (aaf.v2_0.Role r : roles.getRole()) { String roleName = r.getName(); String ns = r.getNs(); - if(aafcli.isTest()) { - if(ns==null) { + if (aafcli.isTest()) { + if (ns==null) { pw().format(roleFormat, roleName,XXXX_XX_XX); } else { pw().format(roleFormat, "["+ns+"]"+roleName.substring(ns.length()),XXXX_XX_XX); } } else { UserRole ur = get(roleName,urs); - if(ur!=null && now.compare(ur.getExpires().normalize())>0) { - if(ns==null) { + if (ur!=null && now.compare(ur.getExpires().normalize())>0) { + if (ns==null) { pw().format(roleExpiredFormat, roleName,Chrono.dateOnlyStamp(ur.getExpires())); } else { pw().format(roleExpiredFormat, "["+ns+"]"+roleName.substring(ns.length()),Chrono.dateOnlyStamp(ur.getExpires())); } } else { - if(ns==null) { + if (ns==null) { pw().format(roleFormat, roleName,ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); } else { pw().format(roleFormat, "["+ns+"]"+roleName.substring(ns.length()),ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); @@ -139,9 +139,9 @@ public class List extends BaseCmd<Role> { } } - for(Pkey pkey : r.getPerms()) { + for (Pkey pkey : r.getPerms()) { Perm perm = get(pkey,perms); - if(perm==null || perm.getNs()==null) { + if (perm==null || perm.getNs()==null) { pw().format(permFormat, pkey.getType(), pkey.getInstance(), @@ -159,12 +159,12 @@ public class List extends BaseCmd<Role> { String fullFormat = roleFormat; reportColHead(fullFormat,"ROLE Name","","PERM Type","Instance","Action"); Collections.sort(roles.getRole(),roleCompare); - for(aaf.v2_0.Role r : roles.getRole()) { + for (aaf.v2_0.Role r : roles.getRole()) { if (urs != null) { String roleName = r.getName(); - if(!aafcli.isTest()) { + if (!aafcli.isTest()) { UserRole ur = get(roleName,urs); - if(ur!=null && now.compare(ur.getExpires().normalize())>0) { + if (ur!=null && now.compare(ur.getExpires().normalize())>0) { pw().format(roleExpiredFormat, roleName+"*",Chrono.dateOnlyStamp(ur.getExpires())); } else { pw().format(roleFormat, roleName,ur!=null?Chrono.dateOnlyStamp(ur.getExpires()):""); @@ -174,7 +174,7 @@ public class List extends BaseCmd<Role> { } } else { pw().format(roleFormatNoDate, r.getName()); - for(Pkey perm : r.getPerms()) { + for (Pkey perm : r.getPerms()) { pw().format(permFormat, perm.getType(), perm.getInstance(), @@ -185,9 +185,9 @@ public class List extends BaseCmd<Role> { } } private Perm get(Pkey pkey, Perms perms) { - if(perms!=null) { - for(Perm p : perms.getPerm()) { - if(pkey.getAction().equals(p.getAction()) && + if (perms!=null) { + for (Perm p : perms.getPerm()) { + if (pkey.getAction().equals(p.getAction()) && pkey.getInstance().equals(p.getInstance()) && pkey.getType().equals(p.getType())) { return p; @@ -198,9 +198,9 @@ public class List extends BaseCmd<Role> { } // The assumption is that these UserRoles are already pulled in by User... no need to check private UserRole get(String roleName, UserRoles urs) { - if(urs!=null) { - for(UserRole ur : urs.getUserRole()) { - if(roleName.equals(ur.getRole())) { + if (urs!=null) { + for (UserRole ur : urs.getUserRole()) { + if (roleName.equals(ur.getRole())) { return ur; } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java index 1f6f18f7..603ec33b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListActivity.java @@ -57,7 +57,7 @@ public class ListActivity extends Cmd { "/authz/hist/role/"+role, getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value,HEADER + " [ " + role + " ]"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java index c9ed37a4..bdcf1e50 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/ListByUser.java @@ -68,13 +68,13 @@ public class ListByUser extends Cmd { "/authz/userRoles/user/"+user, getDF(UserRoles.class) ); - if(fr.get(AAFcli.timeout())) { + if (fr.get(AAFcli.timeout())) { if (aafcli.isDetailed()) { Future<Perms> fp = client.read( "/authz/perms/user/"+user+(aafcli.isDetailed()?"?ns":""), getDF(Perms.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { perms = fp.value; } } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java index c628eb17..364b3980 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/role/User.java @@ -69,7 +69,7 @@ public class User extends Cmd { // You can request to be added or removed from role. setQueryParamsOn(client); - for(String id: ids) { + for (String id: ids) { id=fullID(id); urr.setUser(id); switch(option) { @@ -97,7 +97,7 @@ public class User extends Cmd { default: // actually, should never get here... throw new CadiException("Invalid action [" + action + ']'); } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().print(verb); pw().print(" User ["); pw().print(urr.getUser()); @@ -112,7 +112,7 @@ public class User extends Cmd { pw().println(" is Accepted, but requires Approvals before actualizing"); break; case 404: - if(option==3) { + if (option==3) { pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); break; } @@ -139,7 +139,7 @@ public class User extends Cmd { "/authz/userRole/role", getDF(UserRoleRequest.class), urr); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().println("Set the Role to Users [" + allUsers + "]"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java index 40447c19..cc9ccf98 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Cred.java @@ -57,11 +57,11 @@ public class Cred extends Cmd { final CredRequest cr = new CredRequest(); cr.setId(args[idx++]); - if(option!=1 && option!=3) { - if(idx>=args.length) throw new CadiException("Password Required"); + if (option!=1 && option!=3) { + if (idx>=args.length) throw new CadiException("Password Required"); cr.setPassword(args[idx++]); } - if(args.length>idx) + if (args.length>idx) cr.setEntry(args[idx++]); // Set Start/End commands @@ -82,7 +82,7 @@ public class Cred extends Cmd { verb = "Added Credential ["; break; case 1: -// if(aafcli.addForce())cr.setForce("TRUE"); +// if (aafcli.addForce())cr.setForce("TRUE"); setQueryParamsOn(client); fp = client.delete(CRED_PATH, getDF(CredRequest.class), @@ -109,16 +109,16 @@ public class Cred extends Cmd { // case 4: // return clean.exec(cleanIDX, args); } - if(fp==null) { + if (fp==null) { return null; // get by Sonar check. } - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().print(verb); pw().print(cr.getId()); pw().println(']'); - } else if(fp.code()==202) { + } else if (fp.code()==202) { pw().println("Credential Action Accepted, but requires Approvals before actualizing"); - } else if(fp.code()==406 && option==1) { + } else if (fp.code()==406 && option==1) { pw().println("You cannot delete this Credential"); } else { pw().println(ATTEMPT_FAILED_SPECIFICS_WITHELD); @@ -126,7 +126,7 @@ public class Cred extends Cmd { return fp.code(); } }); - if(ret==null)ret = -1; + if (ret==null)ret = -1; return ret; } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java index 8587ac3d..3cb9fb04 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Delg.java @@ -64,10 +64,10 @@ public class Delg extends BaseCmd<User> { int option= whichOption(options, args[idx++]); String user = fullID(args[idx++]); dr.setUser(user); - if(option<2) { + if (option<2) { String delegate = fullID(args[idx++]); dr.setDelegate(delegate); - if(option<2 && args.length>idx) { + if (option<2 && args.length>idx) { Date date; try { date = Chrono.dateOnlyFmt.parse(args[idx++]); @@ -100,7 +100,7 @@ public class Delg extends BaseCmd<User> { throw new CadiException("Bad Argument"); }; - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { pw().append("Delegate "); pw().println(verb); } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java index 03148ce5..3074ab86 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/List.java @@ -53,7 +53,7 @@ public class List extends BaseCmd<User> { Collections.sort(sorted, new Comparator<aaf.v2_0.Users.User>() { @Override public int compare(aaf.v2_0.Users.User u1, aaf.v2_0.Users.User u2) { - if(u1==null || u2 == null) { + if (u1==null || u2 == null) { return -1; } return u1.getId().compareTo(u2.getId()); @@ -61,8 +61,8 @@ public class List extends BaseCmd<User> { }); String format = reportColHead("%-40s %-10s %-30s\n","User","Type","Expires"); String date = "XXXX-XX-XX"; - for(aaf.v2_0.Users.User user : sorted) { - if(!aafcli.isTest()) { + for (aaf.v2_0.Users.User user : sorted) { + if (!aafcli.isTest()) { date = Chrono.dateOnlyStamp(user.getExpires()); } pw().format(format, @@ -84,9 +84,9 @@ public class List extends BaseCmd<User> { } } ); String ticket = null, prev = null; - for(Approval app : lapp ) { + for (Approval app : lapp ) { ticket = app.getTicket(); - if(!ticket.equals(prev)) { + if (!ticket.equals(prev)) { pw().print("Ticket: "); pw().println(ticket); } @@ -106,8 +106,8 @@ public class List extends BaseCmd<User> { reportHead(title,id); String format = reportColHead(" %-25s %-25s %-10s\n","User","Delegate","Expires"); String date = "XXXX-XX-XX"; - for(Delg delg : delgs.getDelgs()) { - if(!this.aafcli.isTest()) + for (Delg delg : delgs.getDelgs()) { + if (!this.aafcli.isTest()) date = Chrono.dateOnlyStamp(delg.getExpires()); pw().printf(format, delg.getUser(), diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java index 4bb87374..162dadac 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListActivity.java @@ -58,7 +58,7 @@ public class ListActivity extends Cmd { "/authz/hist/user/"+user, getDF(History.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { activity(fp.value,HEADER + " [ " + user + " ]"); } else { error(fp); diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java index d9379174..068aacb1 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListApprovals.java @@ -67,9 +67,9 @@ public class ListApprovals extends Cmd { "/authz/approval/"+type+'/'+fullValue, getDF(Approvals.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { ((List)parent).report(fp.value,HEADER + " by " + type,fullValue); - if(fp.code()==404) { + if (fp.code()==404) { return 200; } } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java index 5cc7a52b..28b5c9e7 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListDelegates.java @@ -61,9 +61,9 @@ public class ListDelegates extends Cmd { "/authz/delegates/" + key + '/' + id, getDF(Delgs.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { ((List)parent).report(fp.value,HEADER + " by " + key, id); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java index a71090ea..4977b752 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForCreds.java @@ -66,7 +66,7 @@ public class ListForCreds extends Cmd { "/authn/creds/"+which+'/'+value, getDF(Users.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { if (aafcli.isTest()) Collections.sort(fp.value.getUser(), new Comparator<User>() { @Override @@ -75,7 +75,7 @@ public class ListForCreds extends Cmd { } }); ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,option==1,HEADER+which,value); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java index 439c8af6..516713ef 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForPermission.java @@ -60,14 +60,14 @@ public class ListForPermission extends Cmd { int idx = index; String type = args[idx++]; String instance = args[idx++]; - if("\\*".equals(instance))instance="*"; + if ("\\*".equals(instance))instance="*"; String action = args[idx++]; - if("\\*".equals(action))action="*"; + if ("\\*".equals(action))action="*"; Future<Users> fp = client.read( "/authz/users/perm/"+type+'/'+instance+'/'+action, getDF(Users.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { if (aafcli.isTest()) Collections.sort(fp.value.getUser(), new Comparator<User>() { @Override @@ -76,7 +76,7 @@ public class ListForPermission extends Cmd { } }); ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false,HEADER,type+"|"+instance+"|"+action); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java index 1d1b328a..b534240b 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/ListForRoles.java @@ -60,7 +60,7 @@ public class ListForRoles extends Cmd { "/authz/users/role/"+role, getDF(Users.class) ); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { if (aafcli.isTest()) Collections.sort(fp.value.getUser(), new Comparator<User>() { @Override @@ -69,7 +69,7 @@ public class ListForRoles extends Cmd { } }); ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false, HEADER,role); - if(fp.code()==404)return 200; + if (fp.code()==404)return 200; } else { error(fp); } diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java index 04b444a1..4bc99366 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/user/Role.java @@ -108,7 +108,7 @@ public class Role extends Cmd { pw().println(" Accepted, but requires Approvals before actualizing"); break; case 404: - if(option==3) { + if (option==3) { pw().println("Failed with code 404: UserRole is not found, or you do not have permission to view"); break; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java index 13aa04fd..9393e143 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/cache/Cache.java @@ -89,7 +89,7 @@ public class Cache<TRANS extends Trans, DATA> { public static Map<String,Dated> obtain(String key) { Map<String, Dated> m = cacheMap.get(key); - if(m==null) { + if (m==null) { m = new ConcurrentHashMap<>(); synchronized(cacheMap) { cacheMap.put(key, m); @@ -137,13 +137,13 @@ public class Cache<TRANS extends Trans, DATA> { Date now = new Date(System.currentTimeMillis() + advance); - for(String name : set) { + for (String name : set) { Map<String,Dated> map = cacheMap.get(name); - if(map==null) { + if (map==null) { continue; } - for(Map.Entry<String,Dated> me : map.entrySet()) { + for (Map.Entry<String,Dated> me : map.entrySet()) { ++total; if (me.getValue().timestamp.before(now)) { map.remove(me.getKey()); @@ -152,13 +152,13 @@ public class Cache<TRANS extends Trans, DATA> { } } - if(count>0) { + if (count>0) { env.info().log(Level.INFO, "Cache removed",count,"expired Cached Elements out of", total); } // If High (total) is reached during this period, increase the number of expired services removed for next time. // There's no point doing it again here, as there should have been cleaned items. - if(total>high) { + if (total>high) { // advance cleanup by 10%, without getting greater than timeInterval. advance = Math.min(timeInterval, advance+(timeInterval/10)); } else { @@ -169,20 +169,20 @@ public class Cache<TRANS extends Trans, DATA> { } public static synchronized void startCleansing(Env env, String ... keys) { - if(cleanseTimer==null) { + if (cleanseTimer==null) { cleanseTimer = new Timer("Cache Cleanup Timer"); int cleanInterval = Integer.parseInt(env.getProperty(CACHE_CLEAN_INTERVAL,"60000")); // 1 minute clean cycles int highCount = Integer.parseInt(env.getProperty(CACHE_HIGH_COUNT,"5000")); cleanseTimer.schedule(clean = new Clean(env, cleanInterval, highCount), cleanInterval, cleanInterval); } - for(String key : keys) { + for (String key : keys) { clean.add(key); } } public static void stopTimer() { - if(cleanseTimer!=null) { + if (cleanseTimer!=null) { cleanseTimer.cancel(); cleanseTimer = null; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java index 606e7735..7bc1fdc6 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/common/Define.java @@ -38,14 +38,14 @@ public class Define { private static final String ROOT_NS_TAG_DOT = ROOT_NS_TAG +"."; public static String ROOT_NS() { - if(ROOT_NS==null) { + if (ROOT_NS==null) { throw new RuntimeException(Define.class.getName() + MSG); } return ROOT_NS; } public static String ROOT_COMPANY() { - if(ROOT_NS==null) { + if (ROOT_NS==null) { throw new RuntimeException(Define.class.getName() + MSG); } return ROOT_COMPANY; @@ -54,17 +54,17 @@ public class Define { public static void set(Access access) throws CadiException { ROOT_NS = access.getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); ROOT_COMPANY = access.getProperty(Config.AAF_ROOT_COMPANY,null); - if(ROOT_COMPANY==null) { + if (ROOT_COMPANY==null) { int last = ROOT_NS.lastIndexOf('.'); - if(last>=0) { + if (last>=0) { ROOT_COMPANY = ROOT_NS.substring(0, last); } else { throw new CadiException(Config.AAF_ROOT_COMPANY + " or " + Config.AAF_ROOT_NS + " property with 3 positions is required."); } } - for( Entry<Object, Object> es : access.getProperties().entrySet()) { - if(es.getKey().toString().startsWith(ROOT_NS_TAG_DOT)) { + for ( Entry<Object, Object> es : access.getProperties().entrySet()) { + if (es.getKey().toString().startsWith(ROOT_NS_TAG_DOT)) { access.getProperties().setProperty(es.getKey().toString(),varReplace(es.getValue().toString())); } } @@ -74,7 +74,7 @@ public class Define { } public static String varReplace(final String potential) { - if(potential.startsWith(ROOT_NS_TAG_DOT)) { + if (potential.startsWith(ROOT_NS_TAG_DOT)) { return ROOT_NS + potential.substring(6); } else { return potential; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java index 70cee5c3..56db6f60 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzEnv.java @@ -120,7 +120,7 @@ public class AuthzEnv extends RosettaEnv implements Access { public AuthzTransImpl newTrans() { synchronized(this) { times[idx]=System.currentTimeMillis(); - if(++idx>=times.length)idx=0; + if (++idx>=times.length)idx=0; } return new AuthzTransImpl(this); } @@ -137,18 +137,18 @@ public class AuthzEnv extends RosettaEnv implements Access { int count = 0; long pot = 0; long prev = 0; - for(int i=idx;i<times.length;++i) { - if(times[i]>0) { - if(prev>0) { + for (int i=idx;i<times.length;++i) { + if (times[i]>0) { + if (prev>0) { ++count; pot += times[i]-prev; } prev = times[i]; } } - for(int i=0;i<idx;++i) { - if(times[i]>0) { - if(prev>0) { + for (int i=0;i<idx;++i) { + if (times[i]>0) { + if (prev>0) { ++count; pot += times[i]-prev; } @@ -199,11 +199,11 @@ public class AuthzEnv extends RosettaEnv implements Access { private static final byte[] ENC="enc:".getBytes(); public String decrypt(String encrypted, final boolean anytext) throws IOException { - if(encrypted==null) { + if (encrypted==null) { throw new IOException("Password to be decrypted is null"); } - if(anytext || encrypted.startsWith("enc:")) { - if(decryptor.equals(Decryptor.NULL) && getProperty(Config.CADI_KEYFILE)!=null) { + if (anytext || encrypted.startsWith("enc:")) { + if (decryptor.equals(Decryptor.NULL) && getProperty(Config.CADI_KEYFILE)!=null) { final Symm s; try { s = Symm.obtain(this); diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java index 06fd310e..b08e0240 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransFilter.java @@ -54,10 +54,10 @@ public class AuthzTransFilter extends TransFilter<AuthzTrans> { this.env = env; serviceMetric = new Metric(); serviceMetric.buckets = new float[BUCKETSIZE]; - if(transIDslot==null) { + if (transIDslot==null) { transIDslot = env.slot(TRANS_ID_SLOT); } - if(specialLogSlot==null) { + if (specialLogSlot==null) { specialLogSlot = env.slot(SPECIAL_LOG_SLOT); } } @@ -89,7 +89,7 @@ public class AuthzTransFilter extends TransFilter<AuthzTrans> { Boolean b = trans.get(specialLogSlot, false); LogTarget lt = b?trans.warn():trans.info(); - if(lt.isLoggable()) { + if (lt.isLoggable()) { // Transaction is done, now post full Audit Trail StringBuilder sb = new StringBuilder("AuditTrail\n"); // We'll grabAct sub-metrics for Remote Calls and JSON @@ -98,12 +98,12 @@ public class AuthzTransFilter extends TransFilter<AuthzTrans> { // Add current Metrics to total metrics serviceMetric.total+= m.total; - for(int i=0;i<serviceMetric.buckets.length;++i) { + for (int i=0;i<serviceMetric.buckets.length;++i) { serviceMetric.buckets[i]+=m.buckets[i]; } Long tsi; - if((tsi=trans.get(transIDslot, null))!=null) { + if ((tsi=trans.get(transIDslot, null))!=null) { sb.append(" TraceID="); sb.append(Long.toHexString(tsi)); sb.append('\n'); @@ -123,24 +123,24 @@ public class AuthzTransFilter extends TransFilter<AuthzTrans> { Metric m = trans.auditTrail(lt,1, content, Env.REMOTE,Env.JSON); // Add current Metrics to total metrics serviceMetric.total+= m.total; - for(int i=0;i<serviceMetric.buckets.length;++i) { + for (int i=0;i<serviceMetric.buckets.length;++i) { serviceMetric.buckets[i]+=m.buckets[i]; } StringBuilder sb = new StringBuilder(); sb.append("user="); Principal p = trans.getUserPrincipal(); - if(p==null) { + if (p==null) { sb.append("n/a"); } else { sb.append(p.getName()); - if(p instanceof TrustPrincipal) { + if (p instanceof TrustPrincipal) { sb.append('('); sb.append(((TrustPrincipal)p).personalName()); // UserChain sb.append(')'); } else { sb.append('['); - if(p instanceof TaggedPrincipal) { + if (p instanceof TaggedPrincipal) { sb.append(((TaggedPrincipal)p).tag()); } else { sb.append(p.getClass().getSimpleName()); @@ -154,7 +154,7 @@ public class AuthzTransFilter extends TransFilter<AuthzTrans> { sb.append(trans.port()); // Current code won't ever get here... Always does a Full Audit Trail // Long tsi; -// if((tsi=trans.get(transIDslot, null))!=null) { +// if ((tsi=trans.get(transIDslot, null))!=null) { // sb.append(",TraceID="); // sb.append(Long.toHexString(tsi)); // } @@ -165,10 +165,10 @@ public class AuthzTransFilter extends TransFilter<AuthzTrans> { sb.append(",path="); sb.append(trans.path()); - if(content.length()>0) { + if (content.length()>0) { sb.append(",msg=\""); int start = content.lastIndexOf(",msg=\""); - if(start>=0) { + if (start>=0) { sb.append(content,start+6,content.length()-1); } else { sb.append(content); diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java index ee90f284..aa6b038b 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransImpl.java @@ -60,12 +60,12 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { meth = req.getMethod(); path = req.getPathInfo(); - for(REQD_TYPE rt : REQD_TYPE.values()) { + for (REQD_TYPE rt : REQD_TYPE.values()) { requested(rt,req); } // Handle alternate "request" for "future" String request = req.getParameter("request"); - if(request!=null) { + if (request!=null) { requested(REQD_TYPE.future,(request.length()==0 || "true".equalsIgnoreCase(request))); } @@ -146,7 +146,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { } public void requested(REQD_TYPE requested, boolean b) { - if(b) { + if (b) { mask|=requested.bit; } else { mask&=~requested.bit; @@ -155,7 +155,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { private void requested(REQD_TYPE reqtype, HttpServletRequest req) { String p = req.getParameter(reqtype.name()); - if(p!=null) { + if (p!=null) { requested(reqtype,p.length()==0 || "true".equalsIgnoreCase(p)); } } @@ -167,7 +167,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { @Override public boolean fish(Permission ... pond) { - if(lur!=null) { + if (lur!=null) { return lur.fish(user, pond); } return false; @@ -178,9 +178,9 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public Organization org() { - if(org==null) { + if (org==null) { try { - if((org = OrganizationFactory.obtain(env(), user()))==null) { + if ((org = OrganizationFactory.obtain(env(), user()))==null) { org = Organization.NULL; } } catch (Exception e) { @@ -196,7 +196,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public void logAuditTrail(LogTarget lt) { - if(lt.isLoggable()) { + if (lt.isLoggable()) { StringBuilder sb = new StringBuilder(); auditTrail(1, sb); lt.log(sb); @@ -208,7 +208,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public Date now() { - if(now==null) { + if (now==null) { now = new Date(); } return now; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java index d7b6f1da..b1111638 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTransOnlyFilter.java @@ -70,7 +70,7 @@ public class AuthzTransOnlyFilter extends TransOnlyFilter<AuthzTrans> { Metric m = trans.auditTrail(1, sb, Env.REMOTE,Env.JSON); // Add current Metrics to total metrics serviceMetric.total+= m.total; - for(int i=0;i<serviceMetric.buckets.length;++i) { + for (int i=0;i<serviceMetric.buckets.length;++i) { serviceMetric.buckets[i]+=m.buckets[i]; } // Log current info diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/NullTrans.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/NullTrans.java index 3b7ed6f0..d1c5d28c 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/NullTrans.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/NullTrans.java @@ -225,7 +225,7 @@ public class NullTrans implements AuthzTrans { @Override public Date now() { - if(now==null) { + if (now==null) { now = new Date(); } return now; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java index 92a8269a..edb1f242 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/layer/Result.java @@ -55,12 +55,12 @@ public class Result<RV> { protected Result(RV value, int status, String details, String[] variables) { this.value = value; - if(value==null) { + if (value==null) { specialCondition|=EMPTY_LIST; } this.status = status; this.details = details; - if(variables==null) { + if (variables==null) { this.variables = EMPTY_VARS; } else { this.variables=variables; @@ -290,17 +290,17 @@ public class Result<RV> { @Override public String toString() { - if(status==0) { + if (status==0) { return details; } else { StringBuilder sb = new StringBuilder(); sb.append(status); sb.append(':'); sb.append(String.format(details,((Object[])variables))); - if(isEmpty()) { + if (isEmpty()) { sb.append("{empty}"); } - if(value!=null) { + if (value!=null) { sb.append('-'); sb.append(value.toString()); } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java index 90857b42..6f644bd4 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/AbsData.java @@ -74,14 +74,14 @@ public abstract class AbsData implements Iterable<String> { TimeTaken tt = trans.start("Open Data File", Env.SUB); boolean first = true; try { - if(!dataf.exists()) { + if (!dataf.exists()) { throw new FileNotFoundException("Data File Missing:" + dataf.getCanonicalPath()); } long begin = System.currentTimeMillis(); long end = begin+timeout; boolean exists; - while((exists=lockf.exists()) && begin<end) { - if(first) { + while ((exists=lockf.exists()) && begin<end) { + if (first) { trans.warn().log("Waiting for",lockf.getCanonicalPath(),"to close"); first = false; } @@ -92,7 +92,7 @@ public abstract class AbsData implements Iterable<String> { } begin = System.currentTimeMillis(); } - if(exists) { + if (exists) { throw new IOException(lockf.getCanonicalPath() + "exists. May not open Datafile"); } data.open(); @@ -110,12 +110,12 @@ public abstract class AbsData implements Iterable<String> { } private synchronized void ensureIdxGood(AuthzTrans trans) throws IOException { - if(!idxf.exists() || idxf.length()==0 || dataf.lastModified()>idxf.lastModified()) { + if (!idxf.exists() || idxf.length()==0 || dataf.lastModified()>idxf.lastModified()) { trans.warn().log(idxf.getAbsolutePath(),"is missing, empty or out of date, creating"); RandomAccessFile raf = new RandomAccessFile(lockf, "rw"); try { ti.create(trans, data, maxLineSize, delim, fieldOffset, skipLines); - if(!idxf.exists() || (idxf.length()==0 && dataf.length()!=0)) { + if (!idxf.exists() || (idxf.length()==0 && dataf.length()!=0)) { throw new IOException("Data Index File did not create correctly"); } } finally { @@ -189,7 +189,7 @@ public abstract class AbsData implements Iterable<String> { @Override public String next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } reuse.reset(); diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java index 7e420df4..a65c13db 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/DataFile.java @@ -43,7 +43,7 @@ public class DataFile { this.access = access; } public void open() throws IOException { - if(!file.exists()) throw new FileNotFoundException(); + if (!file.exists()) throw new FileNotFoundException(); rafile = new RandomAccessFile(file,access); channel = rafile.getChannel(); mapBuff = channel.map("r".equals(access)?MapMode.READ_ONLY:MapMode.READ_WRITE,0,channel.size()); @@ -52,10 +52,10 @@ public class DataFile { return mapBuff!=null; } public void close() throws IOException { - if(channel!=null){ + if (channel!=null){ channel.close(); } - if(rafile!=null) { + if (rafile!=null) { rafile.close(); } mapBuff = null; @@ -67,7 +67,7 @@ public class DataFile { private synchronized int load(Token t) { int len = Math.min(mapBuff.limit()-t.next,t.buff.length); - if(len>0) { + if (len>0) { mapBuff.position(t.next); mapBuff.get(t.buff,0,len); } @@ -91,8 +91,8 @@ public class DataFile { public boolean nextLine() { end = load(this); pos = next; - for(int i=0;i<end;++i) { - if(buff[i]=='\n') { + for (int i=0;i<end;++i) { + if (buff[i]=='\n') { end = i; next += i+1; return true; @@ -126,16 +126,16 @@ public class DataFile { } public String next() { - if(idx>=end)return null; + if (idx>=end)return null; int start = idx; byte c=0; int endStr = -1; - while(idx<end && idx<buff.length && (c=buff[idx])!=delim && c!='\n') { // for DOS - if(c=='\r')endStr=idx; + while (idx<end && idx<buff.length && (c=buff[idx])!=delim && c!='\n') { // for DOS + if (c=='\r')endStr=idx; ++idx; } - if(endStr<0) { + if (endStr<0) { endStr=idx-start; } else { endStr=endStr-start; @@ -147,9 +147,9 @@ public class DataFile { public String at(int fieldOffset) { int start; byte c=0; - for(int count = idx = start = 0; idx<end && idx<buff.length; ++idx) { - if((c=buff[idx])==delim || c=='\n') { - if(count++ == fieldOffset) { + for (int count = idx = start = 0; idx<end && idx<buff.length; ++idx) { + if ((c=buff[idx])==delim || c=='\n') { + if (count++ == fieldOffset) { break; } start = idx+1; @@ -161,16 +161,16 @@ public class DataFile { public String atToEnd(int fieldOffset) { int start; byte c=0; - for(int count = idx = start = 0; idx<end && idx<buff.length; ++idx) { - if((c=buff[idx])==delim || c=='\n') { - if(count++ == fieldOffset) { + for (int count = idx = start = 0; idx<end && idx<buff.length; ++idx) { + if ((c=buff[idx])==delim || c=='\n') { + if (count++ == fieldOffset) { break; } start = idx+1; } } - for(; idx<end && idx<buff.length && (c=buff[idx])!='\n'; ++idx) { + for (; idx<end && idx<buff.length && (c=buff[idx])!='\n'; ++idx) { ++idx; } return new String(buff,start,(idx-start-((c=='\r' || idx>=end)?1:0))); diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java index bb1b6117..73ad07c7 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/local/TextIndex.java @@ -54,7 +54,7 @@ public class TextIndex { } public void close() throws IOException { - if(dataFile!=null) { + if (dataFile!=null) { dataFile.close(); dataFile=null; } @@ -65,7 +65,7 @@ public class TextIndex { } public int find(Object key, DataFile.Token dtok, Field df, int offset) throws IOException { - if(dataFile==null) { + if (dataFile==null) { throw new IOException("File not opened"); } long hash = hashToLong(key.hashCode()); @@ -74,13 +74,13 @@ public class TextIndex { IntBuffer tib = ttok.getIntBuffer(); long lhash; int curr; - while((max-min)>100) { + while ((max-min)>100) { ttok.pos((curr=(min+(max-min)/2))*REC_SIZE); tib.rewind(); lhash = hashToLong(tib.get()); - if(lhash<hash) { + if (lhash<hash) { min=curr+1; - } else if(lhash>hash) { + } else if (lhash>hash) { max=curr-1; } else { min=curr-40; @@ -90,20 +90,20 @@ public class TextIndex { } List<Integer> entries = new ArrayList<>(); - for(int i=min;i<=max;++i) { + for (int i=min;i<=max;++i) { ttok.pos(i*REC_SIZE); tib.rewind(); lhash = hashToLong(tib.get()); - if(lhash==hash) { + if (lhash==hash) { entries.add(tib.get()); - } else if(lhash>hash) { + } else if (lhash>hash) { break; } } - for(Integer i : entries) { + for (Integer i : entries) { dtok.pos(i); - if(df.at(offset).equals(key)) { + if (df.at(offset).equals(key)) { return i; } } @@ -116,7 +116,7 @@ public class TextIndex { */ private static long hashToLong(int hash) { long rv; - if(hash<0) { + if (hash<0) { rv = 0xFFFFFFFFL & hash; } else { rv = hash; @@ -145,15 +145,15 @@ public class TextIndex { Field f = t.new Field(delim); int count = 0; - if(skipLines>0) { + if (skipLines>0) { trans.info().log("Skipping",skipLines,"line"+(skipLines==1?" in":"s in"),data.file().getName()); } - for(int i=0;i<skipLines;++i) { + for (int i=0;i<skipLines;++i) { t.nextLine(); } tt2 = trans.start("Read", Env.SUB); try { - while(t.nextLine()) { + while (t.nextLine()) { list.add(new Idx(f.at(fieldOffset),t.pos())); ++count; } @@ -168,8 +168,8 @@ public class TextIndex { try { ByteBuffer bb = ByteBuffer.allocate(8*1024); IntBuffer ib = bb.asIntBuffer(); - for(Idx idx : list) { - if(!ib.hasRemaining()) { + for (Idx idx : list) { + if (!ib.hasRemaining()) { fos.write(bb); ib.clear(); bb.rewind(); @@ -186,7 +186,7 @@ public class TextIndex { fos.close(); } } finally { - if(raf!=null) { + if (raf!=null) { raf.close(); // closed by fos } } @@ -244,7 +244,7 @@ public class TextIndex { */ @Override public boolean equals(Object o) { - if(o!=null && o instanceof Idx) { + if (o!=null && o instanceof Idx) { return hash == ((Idx)o).hash; } return false; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java index 3ade1195..fd252fe4 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Organization.java @@ -161,8 +161,8 @@ public interface Organization { Notify(int id) {this.id = id;} public int getValue() {return id;} public static Notify from(int type) { - for(Notify t : Notify.values()) { - if(t.id==type) { + for (Notify t : Notify.values()) { + if (t.id==type) { return t; } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java index 3b97d6f3..80a382a8 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/OrganizationFactory.java @@ -53,39 +53,39 @@ public class OrganizationFactory { int idx = ORGANIZATION_DOT.length(); Organization org,firstOrg = null; - for(Entry<Object, Object> es : env.getProperties().entrySet()) { + for (Entry<Object, Object> es : env.getProperties().entrySet()) { String key = es.getKey().toString(); - if(key.startsWith(ORGANIZATION_DOT)) { + if (key.startsWith(ORGANIZATION_DOT)) { org = obtain(env,key.substring(idx)); - if(firstOrg==null) { + if (firstOrg==null) { firstOrg = org; } } } - if(defaultOrg == null) { + if (defaultOrg == null) { defaultOrg = firstOrg; } return defaultOrg; } public static Organization obtain(Env env,final String theNS) throws OrganizationException { String orgNS; - if(theNS.indexOf('@')>=0) { + if (theNS.indexOf('@')>=0) { orgNS=FQI.reverseDomain(theNS); } else { orgNS=theNS; } Organization org = orgs.get(orgNS); - if(org == null) { + if (org == null) { env.debug().printf("Attempting to instantiate Organization %s\n",orgNS); String orgClass = env.getProperty(ORGANIZATION_DOT+orgNS); - if(orgClass == null) { + if (orgClass == null) { env.warn().log("There is no Organization." + orgNS + " property"); } else { try { Class<?> orgCls = Class.forName(orgClass); - for(Organization o : orgs.values()) { - if(o.getClass().isAssignableFrom(orgCls)) { + for (Organization o : orgs.values()) { + if (o.getClass().isAssignableFrom(orgCls)) { org = o; } } @@ -93,15 +93,15 @@ public class OrganizationFactory { env.error().log(e1, orgClass + " is not on the Classpath."); throw new OrganizationException(e1); } - if(org==null) { + if (org==null) { try { @SuppressWarnings("unchecked") Class<Organization> cls = (Class<Organization>) Class.forName(orgClass); Constructor<Organization> cnst = cls.getConstructor(Env.class,String.class); org = cnst.newInstance(env,orgNS); String other_realms = env.getProperty(orgNS+".also_supports"); - if(other_realms!=null) { - for(String r : Split.splitTrim(',', other_realms)) { + if (other_realms!=null) { + for (String r : Split.splitTrim(',', other_realms)) { org.addSupportedRealm(r); } } @@ -114,13 +114,13 @@ public class OrganizationFactory { } orgs.put(orgNS, org); boolean isDefault; - if((isDefault="true".equalsIgnoreCase(env.getProperty(orgNS+".default")))) { + if ((isDefault="true".equalsIgnoreCase(env.getProperty(orgNS+".default")))) { defaultOrg = org; } env.init().printf("Instantiated %s with %s%s\n",orgNS,orgClass,(isDefault?" as default":"")); } - if(org==null) { - if(defaultOrg!=null) { + if (org==null) { + if (defaultOrg!=null) { org=defaultOrg; orgs.put(orgNS, org); } @@ -133,7 +133,7 @@ public class OrganizationFactory { public static Organization get(AuthzTrans trans) throws OrganizationException { String domain = FQI.reverseDomain(trans.user()); Organization org = orgs.get(domain); - if(org==null) { + if (org==null) { org = defaultOrg; // can be null, btw, unless set. } return org; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java index 30924dd5..0e70e25e 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Acceptor.java @@ -46,16 +46,16 @@ class Acceptor<TRANS extends Trans> { private boolean eval(HttpCode<TRANS,?> code, String str, List<String> props) { // int plus = str.indexOf('+'); -// if(plus<0) { +// if (plus<0) { boolean ok = false; boolean any = false; - for(Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type : types) { + for (Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type : types) { ok = true; - if(type.x.equals(str)) { - for(Iterator<String> iter = props.iterator();ok && iter.hasNext();) { + if (type.x.equals(str)) { + for (Iterator<String> iter = props.iterator();ok && iter.hasNext();) { ok = props(type,iter.next(),iter.next()); } - if(ok) { + if (ok) { any = true; acceptable.add(type); } @@ -65,11 +65,11 @@ class Acceptor<TRANS extends Trans> { // int prev = str.indexOf('/')+1; // String first = str.substring(0,prev); // String nstr; -// while(prev!=0) { +// while (prev!=0) { // nstr = first + (plus<0?str.substring(prev):str.substring(prev,plus)); // -// for(Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type : types) { -// if(type.x.equals(nstr)) { +// for (Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type : types) { +// if (type.x.equals(nstr)) { // acceptable.add(type); // return type; // } @@ -90,14 +90,14 @@ class Acceptor<TRANS extends Trans> { */ private boolean props(Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type, String tag, String value) { boolean rv = false; - if(type.y!=null) { - for(Pair<String,Object> prop : type.y.y){ - if(tag.equals(prop.x)) { - if(tag.equals("charset")) { + if (type.y!=null) { + for (Pair<String,Object> prop : type.y.y){ + if (tag.equals(prop.x)) { + if (tag.equals("charset")) { return prop.x==null?false:prop.y.equals(value.toLowerCase()); // return True if Matched - } else if(tag.equals("version")) { + } else if (tag.equals("version")) { return prop.y.equals(new Version(value)); // Note: Version Class knows Minor Version encoding - } else if(tag.equals(Content.Q)) { // replace Q value + } else if (tag.equals(Content.Q)) { // replace Q value try { type.y.y.get(0).y=Float.parseFloat(value); } catch (NumberFormatException e) { @@ -135,34 +135,34 @@ class Acceptor<TRANS extends Trans> { name=null; cis = cie+1; // find comma start - while(cis<bytes.length && Character.isSpaceChar(bytes[cis]))++cis; + while (cis<bytes.length && Character.isSpaceChar(bytes[cis]))++cis; cie = cntnt.indexOf(',',cis); // find comma end cend = cie<0?bytes.length:cie; // If no comma, set comma end to full length, else cie - while(cend>cis && Character.isSpaceChar(bytes[cend-1]))--cend; + while (cend>cis && Character.isSpaceChar(bytes[cend-1]))--cend; // Start SEMIS sie=cis-1; do { sis = sie+1; // semi start is one after previous end - while(sis<bytes.length && Character.isSpaceChar(bytes[sis]))++sis; + while (sis<bytes.length && Character.isSpaceChar(bytes[sis]))++sis; sie = cntnt.indexOf(';',sis); send = sie>cend || sie<0?cend:sie; // if the Semicolon is after the comma, or non-existent, use comma end, else keep - while(send>sis && Character.isSpaceChar(bytes[send-1]))--send; - if(name==null) { // first entry in Comma set is the name, not a property + while (send>sis && Character.isSpaceChar(bytes[send-1]))--send; + if (name==null) { // first entry in Comma set is the name, not a property name = new String(bytes,sis,send-sis); } else { // We've looped past the first Semi, now process as properties // If there are additional elements (more entities within Semi Colons) // apply Properties int eq = cntnt.indexOf('=',sis); - if(eq>sis && eq<send) { + if (eq>sis && eq<send) { props.add(new String(bytes,sis,eq-sis)); props.add(new String(bytes,eq+1,send-(eq+1))); } } // End Property - } while(sie<=cend && sie>=cis); // End SEMI processing + } while (sie<=cend && sie>=cis); // End SEMI processing // Now evaluate Comma set and return if true - if(eval(code,name,props))return true; // else loop again to check next comma - } while(cie>=0); // loop to next comma + if (eval(code,name,props))return true; // else loop again to check next comma + } while (cie>=0); // loop to next comma return false; // didn't get even one match } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java index 53511b40..9af11152 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/CachingFileAccess.java @@ -66,12 +66,12 @@ import org.onap.aaf.misc.env.Trans; */ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void> { public static void setEnv(Store store, String[] args) { - for(int i=0;i<args.length-1;i+=2) { // cover two parms required for each - if(CFA_WEB_PATH.equals(args[i])) { + for (int i=0;i<args.length-1;i+=2) { // cover two parms required for each + if (CFA_WEB_PATH.equals(args[i])) { store.put(store.staticSlot(CFA_WEB_PATH), args[i+1]); - } else if(CFA_CACHE_CHECK_INTERVAL.equals(args[i])) { + } else if (CFA_CACHE_CHECK_INTERVAL.equals(args[i])) { store.put(store.staticSlot(CFA_CACHE_CHECK_INTERVAL), Long.parseLong(args[i+1])); - } else if(CFA_MAX_SIZE.equals(args[i])) { + } else if (CFA_MAX_SIZE.equals(args[i])) { store.put(store.staticSlot(CFA_MAX_SIZE), Integer.parseInt(args[i+1])); } } @@ -144,11 +144,11 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void env.init().log("CachingFileAccess path: " + new File(web_path).getCanonicalPath()); Object obj; obj = env.get(env.staticSlot(CFA_CACHE_CHECK_INTERVAL),600000L); // Default is 10 mins - if(obj instanceof Long) {checkInterval=(Long)obj; + if (obj instanceof Long) {checkInterval=(Long)obj; } else {checkInterval=Long.parseLong((String)obj);} obj = env.get(env.staticSlot(CFA_MAX_SIZE), 512000); // Default is max file 500k - if(obj instanceof Integer) {maxItemSize=(Integer)obj; + if (obj instanceof Integer) {maxItemSize=(Integer)obj; } else {maxItemSize =Integer.parseInt((String)obj);} clear_command = env.getProperty(CFA_CLEAR_COMMAND,null); @@ -160,9 +160,9 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void public void handle(TRANS trans, HttpServletRequest req, HttpServletResponse resp) throws IOException { String key = pathParam(req, ":key"); String cmd = pathParam(req,":cmd"); - if(key.equals(clear_command)) { + if (key.equals(clear_command)) { resp.setHeader("Content-Type",typeMap.get("txt")); - if("clear".equals(cmd)) { + if ("clear".equals(cmd)) { content.clear(); resp.setStatus(200/*HttpStatus.OK_200*/); } else { @@ -171,7 +171,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void return; } Content c = load(logT , web_path,cmd!=null && cmd.length()>0?key+'/'+cmd:key, null, checkInterval); - if(c.attachmentOnly) { + if (c.attachmentOnly) { resp.setHeader("Content-disposition", "attachment"); } c.setHeader(resp); @@ -214,12 +214,12 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void */ public Content load(LogTarget logTarget, String dataRoot, String key, String mediaType, long _timeCheck) throws IOException { long timeCheck = _timeCheck; - if(timeCheck<0) { + if (timeCheck<0) { timeCheck=checkInterval; // if time < 0, then use default } boolean isRoot; String fileName; - if("-".equals(key)) { + if ("-".equals(key)) { fileName = dataRoot; isRoot = true; } else { @@ -229,30 +229,30 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void Content c = content.get(key); long systime = System.currentTimeMillis(); File f=null; - if(c!=null) { + if (c!=null) { // Don't check every hit... only after certain time value - if(c.date < systime + timeCheck) { + if (c.date < systime + timeCheck) { f = new File(fileName); - if(f.lastModified()>c.date) { + if (f.lastModified()>c.date) { c=null; } } } - if(c==null) { - if(logTarget!=null) { + if (c==null) { + if (logTarget!=null) { logTarget.log("File Read: ",key); } - if(f==null){ + if (f==null){ f = new File(fileName); } boolean cacheMe; - if(f.exists()) { - if(f.isDirectory()) { + if (f.exists()) { + if (f.isDirectory()) { cacheMe = false; c = new DirectoryContent(f,isRoot); } else { - if(f.length() > maxItemSize) { + if (f.length() > maxItemSize) { c = new DirectFileContent(f); cacheMe = false; } else { @@ -260,10 +260,10 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void cacheMe = checkInterval>0; } - if(mediaType==null) { // determine from file Ending + if (mediaType==null) { // determine from file Ending int idx = key.lastIndexOf('.'); String subkey = key.substring(++idx); - if((c.contentType = idx<0?null:typeMap.get(subkey))==null) { + if ((c.contentType = idx<0?null:typeMap.get(subkey))==null) { // if nothing else, just set to default type... c.contentType = "application/octet-stream"; } @@ -275,7 +275,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void c.date = f.lastModified(); - if(cacheMe) { + if (cacheMe) { content.put(key, c); } } @@ -283,7 +283,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void c=NULL; } } else { - if(logTarget!=null)logTarget.log("Cache Read: ",key); + if (logTarget!=null)logTarget.log("Cache Read: ",key); } // refresh hit time @@ -294,7 +294,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void public Content loadOrDefault(Trans trans, String targetDir, String targetFileName, String sourcePath, String mediaType) throws IOException { try { return load(trans.info(),targetDir,targetFileName,mediaType,0); - } catch(FileNotFoundException e) { + } catch (FileNotFoundException e) { String targetPath = targetDir + '/' + targetFileName; TimeTaken tt = trans.start("File doesn't exist; copy " + sourcePath + " to " + targetPath, Env.SUB); try { @@ -374,7 +374,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void char[] buff = new char[1024]; try { int read; - while((read = fr.read(buff,0,1024))>=0) { + while ((read = fr.read(buff,0,1024))>=0) { writer.write(buff,0,read); } } finally { @@ -387,7 +387,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void byte[] buff = new byte[1024]; try { int read; - while((read = fis.read(buff,0,1024))>=0) { + while ((read = fis.read(buff,0,1024))>=0) { os.write(buff,0,read); } } finally { @@ -415,13 +415,13 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void // See if there are Numbers in the name Matcher m1 = A_NUMBER.matcher(f1.getName()); Matcher m2 = A_NUMBER.matcher(f2.getName()); - if(m1.find() && m2.find()) { + if (m1.find() && m2.find()) { // if numbers, are the numbers in the same start position int i1 = m1.start(); int i2 = m2.start(); // If same start position and the text is the same, then reverse sort - if(i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) { + if (i1==i2 && f1.getName().startsWith(f2.getName().substring(0,i1))) { // reverse sort files that start similarly, but have numbers in them return f2.compareTo(f1); } @@ -443,7 +443,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void w.append(H2); for (File f : files) { w.append("<li><a href=\""); - if(notRoot) { + if (notRoot) { w.append(name); w.append('/'); } @@ -490,7 +490,7 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void public void write(Writer writer) throws IOException { synchronized(this) { // do the String Transformation once, and only if actually used - if(cdata==null) { + if (cdata==null) { cdata = new char[end]; new String(data).getChars(0, end, cdata, 0); } @@ -538,21 +538,21 @@ public class CachingFileAccess<TRANS extends Trans> extends HttpCode<TRANS, Void @Override public void run() { int size = content.size(); - if(size>maxSize) { + if (size>maxSize) { ArrayList<Comp> scont = new ArrayList<>(size); Object[] entries = content.entrySet().toArray(); - for(int i=0;i<size;++i) { + for (int i=0;i<size;++i) { scont.add(i, new Comp((Map.Entry<String,Content>)entries[i])); } Collections.sort(scont); int end = size - ((maxSize/4)*3); // reduce to 3/4 of max size //System.out.println("------ Cleanup Cycle ------ " + new Date().toString() + " -------"); - for(int i=0;i<end;++i) { + for (int i=0;i<end;++i) { Entry<String, Content> entry = scont.get(i).entry; content.remove(entry.getKey()); //System.out.println("removed Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString()); } -// for(int i=end;i<size;++i) { +// for (int i=end;i<size;++i) { // Entry<String, Content> entry = scont.get(i).entry; // //System.out.println("remaining Cache Item " + entry.getKey() + "/" + new Date(entry.getValue().access).toString()); // } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java index f8760ada..63a2eeaa 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Content.java @@ -80,13 +80,13 @@ public abstract class Content<TRANS extends Trans> { sis = sie+1; sie = cntnt.indexOf(';',sis); send = sie>cend || sie<0?cend:sie; - if(me==null) { + if (me==null) { String semi = new String(bytes,sis,send-sis); // trans.checkpoint(semi); // Look at first entity within comma group // Is this an acceptable Type? me=types(code, semi); - if(me==null) { + if (me==null) { sie=-1; // skip the rest of the processing... not a type } else { contType=true; @@ -95,20 +95,20 @@ public abstract class Content<TRANS extends Trans> { // If there are additional elements (more entities within Semi Colons) // apply Propertys int eq = cntnt.indexOf('=',sis); - if(eq>sis && eq<send) { + if (eq>sis && eq<send) { String tag = new String(bytes,sis,eq-sis); String value = new String(bytes,eq+1,send-(eq+1)); // trans.checkpoint(" Prop " + tag + "=" + value); boolean bool = props(me,tag,value); - if(!bool) { + if (!bool) { contProp=false; } } } // End Property - } while(sie<=cend && sie>=cis); + } while (sie<=cend && sie>=cis); // End SEMIS - } while(cie>=0); + } while (cie>=0); return contType && contProp; // for use in finds, True if a type found AND all props matched } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/HttpCode.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/HttpCode.java index c5739e35..0768145f 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/HttpCode.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/HttpCode.java @@ -55,8 +55,8 @@ public abstract class HttpCode<TRANS extends Trans, CONTEXT> { // Evaluate for "*" once... all = false; - for(String srole : roles) { - if("*".equals(srole)) { + for (String srole : roles) { + if ("*".equals(srole)) { all = true; break; } @@ -79,11 +79,11 @@ public abstract class HttpCode<TRANS extends Trans, CONTEXT> { */ public String pathParam(HttpServletRequest req, String key) { String rv = req.getParameter(key); - if(rv==null) { + if (rv==null) { rv = match.param(req.getPathInfo(), key); - if(rv!=null) { + if (rv!=null) { rv = rv.trim(); - if(rv.endsWith("/")) { + if (rv.endsWith("/")) { rv = rv.substring(0, rv.length()-1); } } @@ -102,10 +102,10 @@ public abstract class HttpCode<TRANS extends Trans, CONTEXT> { * @return */ public boolean isAuthorized(HttpServletRequest req) { - if(all)return true; - if(roles!=null) { - for(String srole : roles) { - if(req.isUserInRole(srole)) return true; + if (all)return true; + if (roles!=null) { + for (String srole : roles) { + if (req.isUserInRole(srole)) return true; } } return false; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java index 5a036551..599e45b2 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Match.java @@ -52,16 +52,16 @@ public class Match { public Match(String path) { // IF DEBUG: System.out.print("\n[" + path + "]"); params = new HashMap<>(); - if(path!=null) { + if (path!=null) { String[] pa = path.split("/"); values = new byte[pa.length][]; vars = new Integer[pa.length]; int val = 0; String key; - for(int i=0;i<pa.length && !wildcard;++i) { - if(pa[i].startsWith(":")) { - if(pa[i].endsWith("*")) { + for (int i=0;i<pa.length && !wildcard;++i) { + if (pa[i].startsWith(":")) { + if (pa[i].endsWith("*")) { val = i | pa.length<<16; // load end value in high order bits key = pa[i].substring(0, pa[i].length()-1);// remove * wildcard = true; @@ -75,9 +75,9 @@ public class Match { vars[i]=val; } else { values[i]=pa[i].getBytes(); - if(pa[i].endsWith("*")) { + if (pa[i].endsWith("*")) { wildcard = true; - if(pa[i].length()>1) { + if (pa[i].length()>1) { /* remove * from value */ int newlength = values[i].length-1; byte[] real = new byte[newlength]; @@ -107,25 +107,25 @@ public class Match { */ public String param(String path,String key) { Integer val = params.get(key); // :key or key - if(val!=null) { + if (val!=null) { int start = val & 0xFFFF; int end = (val >> 16) & 0xFFFF; int idx = -1; int i; - for(i=0;i<start;++i) { + for (i=0;i<start;++i) { idx = path.indexOf('/',idx+1); - if(idx<0)break; + if (idx<0)break; } - if(i==start) { + if (i==start) { ++idx; - if(end==0) { + if (end==0) { end = path.indexOf('/',idx); - if(end<0)end=path.length(); + if (end<0)end=path.length(); } else { end=path.length(); } return path.substring(idx,end); - } else if(i==start-1) { // if last spot was left blank, i.e. :key* + } else if (i==start-1) { // if last spot was left blank, i.e. :key* return ""; } } @@ -133,8 +133,8 @@ public class Match { } public boolean match(String path) { - if(path==null|| path.length()==0 || "/".equals(path) ) { - if(values==null)return true; + if (path==null|| path.length()==0 || "/".equals(path) ) { + if (values==null)return true; switch(values.length) { case 0: return true; case 1: return values[0].length==0; @@ -150,58 +150,58 @@ public class Match { int lastByte = pabytes.length; boolean fieldMatched = false; // = lastByte>0?(pabytes[0]=='/'):false; // IF DEBUG: System.out.println("\n -- " + path + " --"); - for(int i=0;rv && i<lastByte;++i) { - if(field>=lastField) { // checking here allows there to be a non-functional ending / + for (int i=0;rv && i<lastByte;++i) { + if (field>=lastField) { // checking here allows there to be a non-functional ending / rv = false; break; } - if(values[field]==null) { // it's a variable, just look for /s - if(wildcard && field==lastField-1) return true;// we've made it this far. We accept all remaining characters + if (values[field]==null) { // it's a variable, just look for /s + if (wildcard && field==lastField-1) return true;// we've made it this far. We accept all remaining characters Integer val = vars[field]; int start = val & 0xFFFF; int end = (val >> 16) & 0xFFFF; - if(end==0)end=start+1; + if (end==0)end=start+1; int k = i; - for(int j=start; j<end && k<lastByte; ++k) { + for (int j=start; j<end && k<lastByte; ++k) { // IF DEBUG: System.out.print((char)pabytes[k]); - if(pabytes[k]=='/') { + if (pabytes[k]=='/') { ++field; ++j; } } - if(k==lastByte && pabytes[k-1]!='/')++field; - if(k>i)i=k-1; // if we've incremented, have to accommodate the outer for loop incrementing as well + if (k==lastByte && pabytes[k-1]!='/')++field; + if (k>i)i=k-1; // if we've incremented, have to accommodate the outer for loop incrementing as well fieldMatched = false; // reset fieldIdx = 0; } else { // IF DEBUG: System.out.print((char)pabytes[i]); - if(pabytes[i]=='/') { // end of field, eval if Field is matched + if (pabytes[i]=='/') { // end of field, eval if Field is matched // if double slash, check if supposed to be empty - if(fieldIdx==0 && values[field].length==0) { + if (fieldIdx==0 && values[field].length==0) { fieldMatched = true; } rv = fieldMatched && ++field<lastField; // reset fieldMatched = false; fieldIdx = 0; - } else if(values[field].length==0) { + } else if (values[field].length==0) { // double slash in path, but content in field. We check specially here to avoid // Array out of bounds issues. rv = false; } else { - if(fieldMatched) { + if (fieldMatched) { rv =false; // field is already matched, now there's too many bytes } else { rv = pabytes[i]==values[field][fieldIdx++]; // compare expected (pabytes[i]) with value for particular field fieldMatched=values[field].length==fieldIdx; // are all the bytes match in the field? - if(fieldMatched && (i==lastByte-1 || (wildcard && field==lastField-1))) + if (fieldMatched && (i==lastByte-1 || (wildcard && field==lastField-1))) return true; // last field info } } } } - if(field!=lastField || pabytes.length!=lastByte) rv = false; // have we matched all the fields and all the bytes? + if (field!=lastField || pabytes.length!=lastByte) rv = false; // have we matched all the fields and all the bytes? return rv; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java index 03264d56..c1bfd6ad 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/RServlet.java @@ -64,7 +64,7 @@ public abstract class RServlet<TRANS extends Trans> implements Servlet { @SuppressWarnings("unchecked") TRANS trans = (TRANS)req.getAttribute(TransFilter.TRANS_TAG); - if(trans==null) { + if (trans==null) { response.setStatus(404); // Not Found, because it didn't go through TransFilter return; } @@ -79,7 +79,7 @@ public abstract class RServlet<TRANS extends Trans> implements Servlet { CodeSetter<TRANS> codesetter = new CodeSetter<TRANS>(trans,request,response); // Find declared route route = routes.derive(request, codesetter); - if(route==null) { + if (route==null) { String method = request.getMethod(); trans.checkpoint("No Route matches "+ method + ' ' + request.getPathInfo()); response.setStatus(404); // Not Found @@ -91,12 +91,12 @@ public abstract class RServlet<TRANS extends Trans> implements Servlet { tt.done(); } - if(route!=null && code!=null) { + if (route!=null && code!=null) { StringBuilder sb = new StringBuilder(72); sb.append(route.auditText); sb.append(','); sb.append(code.desc()); - if(ct!=null) { + if (ct!=null) { sb.append(", ContentType: "); sb.append(ct); } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java index 81b3d0a2..b11916ef 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Route.java @@ -67,18 +67,18 @@ public class Route<TRANS extends Trans> { // FYI, thought about this a long time before implementing this way. String compare; // String special[]; // todo, expose Charset (in special) to outside - if(isGet) { + if (isGet) { compare = req.getHeader("Accept"); // Accept is used for read, as we want to agree on what caller is ready to handle } else { compare = req.getContentType(); // Content type used to declare what data is being created, updated or deleted (might be used for key) } Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> hl = content.prep(trans, compare); - if(hl==null) { + if (hl==null) { resp.setStatus(406); // NOT_ACCEPTABLE } else { - if(isGet) { // Set Content Type to expected content - if("*".equals(hl.x) || "*/*".equals(hl.x)) {// if wild-card, then choose first kind of type + if (isGet) { // Set Content Type to expected content + if ("*".equals(hl.x) || "*/*".equals(hl.x)) {// if wild-card, then choose first kind of type resp.setContentType(content.first()); } else { resp.setContentType(hl.x); diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java index 7c69d9b7..de42e26b 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Routes.java @@ -47,12 +47,12 @@ public class Routes<TRANS extends Trans> { // Package on purpose synchronized Route<TRANS> findOrCreate(HttpMethods meth, String path) { Route<TRANS> rv = null; - for(int i=0;i<end;++i) { - if(routes[i].resolvesTo(meth,path))rv = routes[i]; + for (int i=0;i<end;++i) { + if (routes[i].resolvesTo(meth,path))rv = routes[i]; } - if(rv==null) { - if(end>=routes.length) { + if (rv==null) { + if (end>=routes.length) { @SuppressWarnings("unchecked") Route<TRANS>[] temp = new Route[end+10]; System.arraycopy(routes, 0, temp, 0, routes.length); @@ -69,9 +69,9 @@ public class Routes<TRANS extends Trans> { String path = req.getPathInfo(); String meth = req.getMethod(); //TODO a TREE would be better - for(int i=0;rv==null && i<end; ++i) { + for (int i=0;rv==null && i<end; ++i) { rv = routes[i].matches(meth,path); - if(rv!=null && !codeSetter.matches(rv)) { // potential match, check if has Code + if (rv!=null && !codeSetter.matches(rv)) { // potential match, check if has Code rv = null; // not quite, keep going } } @@ -81,7 +81,7 @@ public class Routes<TRANS extends Trans> { public List<RouteReport> routeReport() { ArrayList<RouteReport> ltr = new ArrayList<>(); - for(int i=0;i<end;++i) { + for (int i=0;i<end;++i) { ltr.add(routes[i].api()); } return ltr; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransFilter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransFilter.java index b36fd234..85b35ac7 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransFilter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TransFilter.java @@ -70,7 +70,7 @@ public abstract class TransFilter<TRANS extends TransStore> implements Filter { public TransFilter(Access access, Connector con, TrustChecker tc, Object ... additionalTafLurs) throws CadiException, LocatorException { cadi = new CadiHTTPManip(access, con, tc, additionalTafLurs); String no = access.getProperty(Config.CADI_NOAUTHN, null); - if(no!=null) { + if (no!=null) { no_authn = Split.split(':', no); } else { no_authn=null; @@ -101,9 +101,9 @@ public abstract class TransFilter<TRANS extends TransStore> implements Filter { try { request.setAttribute(TRANS_TAG, trans); - if(no_authn!=null) { - for(String prefix : no_authn) { - if(req.getPathInfo().startsWith(prefix)) { + if (no_authn!=null) { + for (String prefix : no_authn) { + if (req.getPathInfo().startsWith(prefix)) { chain.doFilter(request, response); return; } @@ -128,9 +128,9 @@ public abstract class TransFilter<TRANS extends TransStore> implements Filter { security.done(); } - if(r==RESP.IS_AUTHENTICATED) { + if (r==RESP.IS_AUTHENTICATED) { trans.checkpoint(resp.desc()); - if(cadi.notCadi(cw, res)) { + if (cadi.notCadi(cw, res)) { chain.doFilter(cw, response); } } else { @@ -138,10 +138,10 @@ public abstract class TransFilter<TRANS extends TransStore> implements Filter { // Would need Cached Counter objects that are cleaned up on // use trans.checkpoint(resp.desc(),Env.ALWAYS); - if(resp.isFailedAttempt()) + if (resp.isFailedAttempt()) trans.audit().log(resp.desc()); } - } catch(Exception e) { + } catch (Exception e) { trans.error().log(e); trans.checkpoint("Error: " + e.getClass().getSimpleName() + ": " + e.getMessage()); throw new ServletException(e); diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java index 8c57838d..1a66cf7d 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/TypedCode.java @@ -72,8 +72,8 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { public TypedCode<TRANS> add(HttpCode<TRANS,?> code, String ... others) { StringBuilder sb = new StringBuilder(); boolean first = true; - for(String str : others) { - if(first) { + for (String str : others) { + if (first) { first = false; } else { sb.append(','); @@ -94,7 +94,7 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { Pair<HttpCode<TRANS,?>, List<Pair<String,Object>>> cl = new Pair<HttpCode<TRANS,?>, List<Pair<String,Object>>>(code, props); // // breakup "plus" stuff, i.e. application/xaml+xml // int plus = str.indexOf('+'); -// if(plus<0) { +// if (plus<0) { type = new Pair<String, Pair<HttpCode<TRANS,?>,List<Pair<String,Object>>>>(str, cl); types.add(type); return type; @@ -102,7 +102,7 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { // int prev = str.indexOf('/')+1; // String first = str.substring(0,prev); // String nstr; -// while(prev!=0) { +// while (prev!=0) { // nstr = first + (plus>-1?str.substring(prev,plus):str.substring(prev)); // type = new Pair<String, Pair<HttpCode<TRANS,?>,List<Pair<String,Object>>>>(nstr, cl); // types.add(type); @@ -115,7 +115,7 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { @Override protected boolean props(Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type, String tag, String value) { - if(tag.equals(Q)) { // reset the Q value (first in array) + if (tag.equals(Q)) { // reset the Q value (first in array) boolean rv = true; try { type.y.y.get(0).y=Float.parseFloat(value); @@ -130,10 +130,10 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { public Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> prep(TRANS trans, String compare) throws IOException, ServletException { Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> c,rv=null; - if(types.size()==1 && "".equals((c=types.get(0)).x)) { // if there are no checks for type, skip + if (types.size()==1 && "".equals((c=types.get(0)).x)) { // if there are no checks for type, skip rv = c; } else { - if(compare==null || compare.length()==0) { + if (compare==null || compare.length()==0) { rv = types.get(0); // first code is used } else { Acceptor<TRANS> acc = new Acceptor<TRANS>(types); @@ -144,7 +144,7 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { } finally { tt.done(); } - if(accepted) { + if (accepted) { switch(acc.acceptable.size()) { case 0: // // TODO best Status Code? @@ -156,16 +156,16 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { default: // compare Q values to get Best Match float bestQ = -1.0f; Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> bestT = null; - for(Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type : acc.acceptable) { + for (Pair<String, Pair<HttpCode<TRANS,?>, List<Pair<String, Object>>>> type : acc.acceptable) { Float f = (Float)type.y.y.get(0).y; // first property is always Q - if(f>bestQ) { + if (f>bestQ) { bestQ=f; bestT = type; } } - if(bestT!=null) { + if (bestT!=null) { // When it is a GET, the matched type is what is returned, so set ContentType -// if(isGet)resp.setContentType(bestT.x); // set ContentType of Code<TRANS,?> +// if (isGet)resp.setContentType(bestT.x); // set ContentType of Code<TRANS,?> // rv = bestT.y.x; rv = bestT; } @@ -190,17 +190,17 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { */ public StringBuilder relatedTo(HttpCode<TRANS, ?> code, StringBuilder sb) { boolean first = true; - for(Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> pair : types) { - if(code==null || pair.y.x == code) { - if(first) { + for (Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> pair : types) { + if (code==null || pair.y.x == code) { + if (first) { first = false; } else { sb.append(','); } sb.append(pair.x); - for(Pair<String,Object> prop : pair.y.y) { + for (Pair<String,Object> prop : pair.y.y) { // Don't print "Q". it's there for internal use, but it is only meaningful for "Accepts" - if(!prop.x.equals(Q) || !prop.y.equals(1f) ) { + if (!prop.x.equals(Q) || !prop.y.equals(1f) ) { sb.append(';'); sb.append(prop.x); sb.append('='); @@ -213,8 +213,8 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { } public List<Pair<String, Object>> getContent(HttpCode<TRANS,?> code) { - for(Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> pair : types) { - if(pair.y.x == code) { + for (Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> pair : types) { + if (pair.y.x == code) { return pair.y.y; } } @@ -232,11 +232,11 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { tr.desc = null; // Read through Code/TypeCode trees for all accepted Typecodes - for(Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> tc : types) { + for (Pair<String, Pair<HttpCode<TRANS, ?>, List<Pair<String, Object>>>> tc : types) { // If new, then it's new Code set, create prefix content - if((temp=psb.get(tc.y.x))==null) { + if ((temp=psb.get(tc.y.x))==null) { psb.put(tc.y.x,temp=new StringBuilder()); - if(tr.desc==null) { + if (tr.desc==null) { tr.desc = tc.y.x.desc(); } } else { @@ -245,7 +245,7 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { temp.append(tc.x); // add all properties - for(Pair<String, Object> props : tc.y.y) { + for (Pair<String, Object> props : tc.y.y) { temp.append(';'); temp.append(props.x); temp.append('='); @@ -254,13 +254,13 @@ public class TypedCode<TRANS extends Trans> extends Content<TRANS> { } // Gather all ContentType possibilities for the same code together - for(StringBuilder sb : psb.values()) { + for (StringBuilder sb : psb.values()) { tr.contextTypes.add(sb.toString()); } } public String first() { - if(types.size()>0) { + if (types.size()>0) { return types.get(0).x; } return null; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java index f4818579..adf05380 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/rserv/Version.java @@ -35,7 +35,7 @@ public class Version { String sparts[] = v.split("\\."); parts = new Object[sparts.length]; System.arraycopy(sparts, 0, parts, 0, sparts.length); - if(parts.length>1) { // has at least a minor + if (parts.length>1) { // has at least a minor try { parts[1]=Integer.decode(sparts[1]); // minor elements need to be converted to Integer for comparison } catch (NumberFormatException e) { @@ -46,20 +46,20 @@ public class Version { } public boolean equals(Object obj) { - if(obj instanceof Version) { + if (obj instanceof Version) { Version ver = (Version)obj; int length = Math.min(parts.length, ver.parts.length); - for(int i=0;i<length;++i) { // match on declared parts - if(i==1) { - if(parts[1] instanceof Integer && ver.parts[1] instanceof Integer) { + for (int i=0;i<length;++i) { // match on declared parts + if (i==1) { + if (parts[1] instanceof Integer && ver.parts[1] instanceof Integer) { // Match on Minor version if this Version is less than Version to be checked - if(((Integer)parts[1])<((Integer)ver.parts[1])) { + if (((Integer)parts[1])<((Integer)ver.parts[1])) { return false; } continue; // don't match next line } } - if(!parts[i].equals(ver.parts[i])) { + if (!parts[i].equals(ver.parts[i])) { return false; // other spots exact match } } @@ -80,8 +80,8 @@ public class Version { public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; - for(Object obj : parts) { - if(first) { + for (Object obj : parts) { + if (first) { first = false; } else { sb.append('.'); diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsService.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsService.java index 497860af..f2495440 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsService.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsService.java @@ -65,17 +65,17 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte String component = access.getProperty(Config.AAF_COMPONENT, null); final String[] locator_deploy; - if(component == null) { + if (component == null) { locator_deploy = null; } else { locator_deploy = Split.splitTrim(':', component); } - if(component == null || locator_deploy==null || locator_deploy.length<2) { + if (component == null || locator_deploy==null || locator_deploy.length<2) { throw new CadiException("AAF Component must include the " + Config.AAF_COMPONENT + " property, <fully qualified service name>:<full deployed version (i.e. 2.1.3.13)"); } final String[] version = Split.splitTrim('.', locator_deploy[1]); - if(version==null || version.length<2) { + if (version==null || version.length<2) { throw new CadiException("AAF Component Version must have at least Major.Minor version"); } app_name = Define.varReplace(locator_deploy[0]); @@ -83,7 +83,7 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte app_interface_version = version[0]+'.'+version[1]; // Print Cipher Suites Available - if(access.willLog(Level.DEBUG)) { + if (access.willLog(Level.DEBUG)) { SSLContext context; try { context = SSLContext.getDefault(); @@ -94,11 +94,11 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte StringBuilder sb = new StringBuilder("Available Cipher Suites: "); boolean first = true; int count=0; - for( String cs : sf.getSupportedCipherSuites()) { - if(first)first = false; + for ( String cs : sf.getSupportedCipherSuites()) { + if (first)first = false; else sb.append(','); sb.append(cs); - if(++count%4==0){sb.append('\n');} + if (++count%4==0){sb.append('\n');} } access.log(Level.DEBUG,sb); } @@ -121,8 +121,8 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte // Lazy Instantiation public synchronized AAFConHttp aafCon() throws CadiException, LocatorException { - if(aafCon==null) { - if(access.getProperty(Config.AAF_URL,null)!=null) { + if (aafCon==null) { + if (access.getProperty(Config.AAF_URL,null)!=null) { aafCon = _newAAFConHttp(); } else { throw new CadiException("AAFCon cannot be constructed without " + Config.AAF_URL); @@ -137,7 +137,7 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte * @throws LocatorException */ protected synchronized AAFConHttp _newAAFConHttp() throws CadiException, LocatorException { - if(aafCon==null) { + if (aafCon==null) { aafCon = new AAFConHttp(access); } return aafCon; @@ -165,20 +165,20 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte protected static final String loadFromArgOrSystem(final Properties props, final String tag, final String args[], final String def) { String tagEQ = tag + '='; String value; - for(String arg : args) { - if(arg.startsWith(tagEQ)) { + for (String arg : args) { + if (arg.startsWith(tagEQ)) { props.put(tag, value=arg.substring(tagEQ.length())); return value; } } // check System.properties value = System.getProperty(tag); - if(value!=null) { + if (value!=null) { props.put(tag, value); return value; } - if(def!=null) { + if (def!=null) { props.put(tag,def); } return def; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java index f14d6c32..29166b0b 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/AbsServiceStarter.java @@ -72,11 +72,11 @@ public abstract class AbsServiceStarter<ENV extends RosettaEnv, TRANS extends Tr @SafeVarargs public final synchronized void register(final Registrant<ENV> ... registrants) { - if(do_register) { - if(registrar==null) { + if (do_register) { + if (registrar==null) { registrar = new Registrar<ENV>(env(),false); } - for(Registrant<ENV> r : registrants) { + for (Registrant<ENV> r : registrants) { registrar.register(r); } } @@ -84,11 +84,11 @@ public abstract class AbsServiceStarter<ENV extends RosettaEnv, TRANS extends Tr @Override public void shutdown() { - if(registrar!=null) { + if (registrar!=null) { registrar.close(env()); registrar=null; } - if(service!=null) { + if (service!=null) { service.destroy(); } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java index a0dafed1..c5849d05 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/JettyServiceStarter.java @@ -78,15 +78,15 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex // Properties props = access().getProperties(); // Object temp = null; // // Critical - if no Security Protocols set, then set it. We'll just get messed up if not -// if((temp=props.get(Config.CADI_PROTOCOLS))==null) { -// if((temp=props.get(Config.HTTPS_PROTOCOLS))==null) { +// if ((temp=props.get(Config.CADI_PROTOCOLS))==null) { +// if ((temp=props.get(Config.HTTPS_PROTOCOLS))==null) { // props.put(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT); // } else { // props.put(Config.CADI_PROTOCOLS, temp); // } // } // -// if("1.7".equals(System.getProperty("java.specification.version"))) { +// if ("1.7".equals(System.getProperty("java.specification.version"))) { // System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); // } // System.setProperty(Config.HTTPS_CIPHER_SUITES, temp.toString()); @@ -98,15 +98,15 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex Properties props = access().getProperties(); Object httpproto = null; // Critical - if no Security Protocols set, then set it. We'll just get messed up if not - if((httpproto=props.get(Config.CADI_PROTOCOLS))==null) { - if((httpproto=props.get(Config.HTTPS_PROTOCOLS))==null) { + if ((httpproto=props.get(Config.CADI_PROTOCOLS))==null) { + if ((httpproto=props.get(Config.HTTPS_PROTOCOLS))==null) { props.put(Config.CADI_PROTOCOLS, (httpproto=SecurityInfo.HTTPS_PROTOCOLS_DEFAULT)); } else { props.put(Config.CADI_PROTOCOLS, httpproto); } } - if("1.7".equals(System.getProperty("java.specification.version")) && (httpproto==null || (httpproto instanceof String && ((String)httpproto).contains("TLSv1.2")))) { + if ("1.7".equals(System.getProperty("java.specification.version")) && (httpproto==null || (httpproto instanceof String && ((String)httpproto).contains("TLSv1.2")))) { System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); } } @@ -114,7 +114,7 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex @Override public void _start(RServlet<TRANS> rserv) throws Exception { String hostname = access().getProperty(Config.HOSTNAME, null); - if(hostname==null) { + if (hostname==null) { hostname = Inet4Address.getLocalHost().getHostName(); } final int port = Integer.parseInt(access().getProperty("port","0")); @@ -124,14 +124,14 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex ServerConnector conn; String protocol; - if(!secure || keystore==null) { + if (!secure || keystore==null) { conn = new ServerConnector(server); protocol = "http"; } else { protocol = "https"; String keystorePassword = access().getProperty(Config.CADI_KEYSTORE_PASSWORD, null); - if(keystorePassword==null) { + if (keystorePassword==null) { throw new CadiException("No Keystore Password configured for " + keystore); } SslContextFactory sslContextFactory = new SslContextFactory(); @@ -142,9 +142,9 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex temp=null; // don't leave lying around String truststore = access().getProperty(Config.CADI_TRUSTSTORE, null); - if(truststore!=null) { + if (truststore!=null) { String truststorePassword = access().getProperty(Config.CADI_TRUSTSTORE_PASSWORD, null); - if(truststorePassword==null) { + if (truststorePassword==null) { throw new CadiException("No Truststore Password configured for " + truststore); } sslContextFactory.setTrustStorePath(truststore); @@ -163,7 +163,7 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex // sslContextFactory.setEnableCRLDP(false); // sslContextFactory.setEnableOCSP(false); String certAlias = access().getProperty(Config.CADI_ALIAS, null); - if(certAlias!=null) { + if (certAlias!=null) { sslContextFactory.setCertAlias(certAlias); } @@ -232,7 +232,7 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex register(service.registrants(port)); access().printf(Level.INIT, "Starting Jetty Service for %s, version %s, on %s://%s:%d", service.app_name,service.app_version,protocol,hostname,port); server.join(); - } catch(Exception e) { + } catch (Exception e) { access().log(e,"Error registering " + service.app_name); String doExit = access().getProperty("cadi_exitOnFailure", "true"); if (doExit == "true") { @@ -246,7 +246,7 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex private FilterChain buildFilterChain(final AbsService<?,?> as, final FilterChain doLast) throws CadiException, LocatorException { Filter[] filters = as.filters(); FilterChain fc = doLast; - for(int i=filters.length-1;i>=0;--i) { + for (int i=filters.length-1;i>=0;--i) { fc = new FCImpl(filters[i],fc); } return fc; diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java index 31b76395..fd0691b6 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/server/Log4JLogIt.java @@ -55,14 +55,14 @@ public class Log4JLogIt implements LogIt { String etc_dir = getArgOrVM(Config.CADI_ETCDIR,args,"/opt/app/osaaf/etc"); String log_level = getArgOrVM(Config.CADI_LOGLEVEL,args,"INFO"); File logs = new File(log_dir); - if(!logs.isDirectory()) { + if (!logs.isDirectory()) { logs.delete(); } - if(!logs.exists()) { + if (!logs.exists()) { logs.mkdirs(); } - if(System.getProperty("log4j.configuration")==null) { + if (System.getProperty("log4j.configuration")==null) { System.setProperty("log4j.configuration", etc_dir+'/'+propsFile); } LogFileNamer lfn = new LogFileNamer(log_dir,root); @@ -86,14 +86,14 @@ public class Log4JLogIt implements LogIt { private static final String getArgOrVM(final String tag, final String args[], final String def) { String tagEQ = tag + '='; String value; - for(String arg : args) { - if(arg.startsWith(tagEQ)) { + for (String arg : args) { + if (arg.startsWith(tagEQ)) { return arg.substring(tagEQ.length()); } } // check System.properties value = System.getProperty(tag); - if(value!=null) { + if (value!=null) { return value; } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java index eb721285..1c9f4123 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/validation/Validator.java @@ -70,16 +70,16 @@ public class Validator { } public final Validator nullOrBlank(String name, String str) { - if(str==null) { + if (str==null) { msg(name + " is null."); - } else if(str.length()==0) { + } else if (str.length()==0) { msg(name + " is blank."); } return this; } public final Validator isNull(String name, Object o) { - if(o==null) { + if (o==null) { msg(name + " is null."); } return this; @@ -93,10 +93,10 @@ public class Validator { } protected final void msg(String ... strs) { - if(msgs==null) { + if (msgs==null) { msgs=new StringBuilder(); } - for(String str : strs) { + for (String str : strs) { msgs.append(str); } msgs.append('\n'); @@ -107,23 +107,23 @@ public class Validator { } public final Validator notOK(Result<?> res) { - if(res==null) { + if (res==null) { msgs.append("Result object is blank"); - } else if(res.notOK()) { + } else if (res.notOK()) { msgs.append(res.getClass().getSimpleName()).append(" is not OK"); } return this; } protected Validator intRange(String text, int target, int start, int end) { - if(target<start || target>end) { + if (target<start || target>end) { msg(text + " is out of range (" + start + '-' + end + ')'); } return this; } protected Validator floatRange(String text, float target, float start, float end) { - if(target<start || target>end) { + if (target<start || target>end) { msg(text + " is out of range (" + start + '-' + end + ')'); } return this; @@ -137,25 +137,25 @@ public class Validator { } public final Validator permType(String type) { - if(nob(type,NAME_CHARS)) { + if (nob(type,NAME_CHARS)) { msg("Perm Type [" +type + "] is invalid."); } return this; } public final Validator permType(String type, String ns) { - if(type==null) { + if (type==null) { msg("Perm Type is null"); - } else if(ns==null) { + } else if (ns==null) { msg("Perm NS is null"); - } else if(nob(type,NAME_CHARS)) { + } else if (nob(type,NAME_CHARS)) { msg("Perm Type [" + (ns+(type.length()==0?"":'.')) + type + "] is invalid."); } return this; } public final Validator permInstance(String instance) { - if(nob(instance,instChars)) { + if (nob(instance,instChars)) { msg("Perm Instance [" + instance + "] is invalid."); } return this; @@ -163,28 +163,28 @@ public class Validator { public final Validator permAction(String action) { // TODO check for correct Splits? Type|Instance|Action ? - if(nob(action, actionChars)) { + if (nob(action, actionChars)) { msg("Perm Action [" + action + "] is invalid."); } return this; } public final Validator role(String role) { - if(nob(role, NAME_CHARS)) { + if (nob(role, NAME_CHARS)) { msg("Role [" + role + "] is invalid."); } return this; } public final Validator ns(String ns) { - if(ns==null) { + if (ns==null) { msg("NS is null"); return this; - } else if(nob(ns,NAME_CHARS)) { + } else if (nob(ns,NAME_CHARS)) { msg("NS [" + ns + "] is invalid."); } - for(String s : nsKeywords) { - if(ns.endsWith(s)) { + for (String s : nsKeywords) { + if (ns.endsWith(s)) { msg("NS [" + ns + "] may not be named with NS keywords"); break; } @@ -193,14 +193,14 @@ public class Validator { } public final Validator key(String key) { - if(nob(key,NAME_CHARS)) { + if (nob(key,NAME_CHARS)) { msg("NS Prop Key [" + key + "] is invalid"); } return this; } public final Validator value(String value) { - if(nob(value,ESSENTIAL_CHARS)) { + if (nob(value,ESSENTIAL_CHARS)) { msg("NS Prop value [" + value + "] is invalid"); } return this; diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java index a88b005d..2bc7dfa0 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_AbsData.java @@ -74,7 +74,7 @@ public class JU_AbsData { FileOutputStream is = new FileOutputStream(keyfile); OutputStreamWriter osw = new OutputStreamWriter(is); BufferedWriter w = new BufferedWriter(osw); - for(int i = 0; i< 10; i++) { //Write lines to file + for (int i = 0; i< 10; i++) { //Write lines to file w.write("a\nsdfasdfxasdf" + i + "\n"); } w.close(); diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java index 099a9f00..b0af89ce 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_DataFile.java @@ -53,13 +53,13 @@ public class JU_DataFile { // Token tok = df.new Token(1024000); // Field fld = tok.new Field('|'); // -// while(tok.nextLine()) { +// while (tok.nextLine()) { // ++count; // fld.reset(); // list.add(fld.at(0)); // } //// Collections.sort(list); -// for(String s: list) { +// for (String s: list) { // System.out.println(s); // // } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java index fadc3b67..d4330296 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/local/test/JU_TextIndex.java @@ -83,7 +83,7 @@ public class JU_TextIndex { FileOutputStream is = new FileOutputStream(keyfile); OutputStreamWriter osw = new OutputStreamWriter(is); BufferedWriter w = new BufferedWriter(osw); - for(int i = 0; i< 10; i++) { //Write lines to file + for (int i = 0; i< 10; i++) { //Write lines to file w.write("a\nsdfasdfxasdf" + i + "\n"); } w.close(); diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java index acbaa9c8..0786c134 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSAttribCompare.java @@ -59,10 +59,10 @@ public class NSAttribCompare extends RosettaCompare<NsAttribRequest> { @Override public void compare(NsAttribRequest t1, NsAttribRequest t2) { assertEquals(t1.getNs(),t2.getNs()); - for(Attrib a1 : t1.getAttrib()) { + for (Attrib a1 : t1.getAttrib()) { boolean ok = false; - for(Attrib a2 : t2.getAttrib()) { - if(a1.getKey().equals(a2.getKey()) && + for (Attrib a2 : t2.getAttrib()) { + if (a1.getKey().equals(a2.getKey()) && a1.getValue().equals(a2.getValue())) { ok = true; break; @@ -70,10 +70,10 @@ public class NSAttribCompare extends RosettaCompare<NsAttribRequest> { } assertTrue("a2 Attribs in a1",ok); } - for(Attrib a2 : t2.getAttrib()) { + for (Attrib a2 : t2.getAttrib()) { boolean ok = false; - for(Attrib a1 : t1.getAttrib()) { - if(a1.getKey().equals(a2.getKey()) && + for (Attrib a1 : t1.getAttrib()) { + if (a1.getKey().equals(a2.getKey()) && a1.getValue().equals(a2.getValue())) { ok = true; break; diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java index 53f78b7c..c3504216 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/request/test/NSCompare.java @@ -56,10 +56,10 @@ public class NSCompare extends RosettaCompare<NsRequest> { public void compare(NsRequest t1, NsRequest t2) { assertEquals(t1.getName(),t2.getName()); assertEquals(t1.getDescription(),t2.getDescription()); - for(String s : t1.getAdmin()) { + for (String s : t1.getAdmin()) { assertTrue(t2.getAdmin().contains(s)); } - for(String s : t2.getAdmin()) { + for (String s : t2.getAdmin()) { assertTrue(t1.getAdmin().contains(s)); } assertEquals(t1.getType(),t2.getType()); diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java index 5a581edc..c809c55f 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/validation/test/JU_Validator.java @@ -286,7 +286,7 @@ public class JU_Validator { assertFalse(Validator.INST_CHARS.matcher("").matches()); - for( char c=0x20;c<0x7F;++c) { + for ( char c=0x20;c<0x7F;++c) { boolean b; switch(c) { case '?': diff --git a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java index d9336d4e..4f2d9676 100644 --- a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java +++ b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrg.java @@ -62,11 +62,11 @@ public class DefaultOrg implements Organization { String s; NAME=env.getProperty(realm + ".name","Default Organization"); mailHost = env.getProperty(s=(realm + ".mailHost"), null); - if(mailHost==null) { + if (mailHost==null) { throw new OrganizationException(s + PROPERTY_IS_REQUIRED); } mailFrom = env.getProperty(s=(realm + ".mailFrom"), null); - if(mailFrom==null) { + if (mailFrom==null) { throw new OrganizationException(s + PROPERTY_IS_REQUIRED); } @@ -88,16 +88,16 @@ public class DefaultOrg implements Organization { String defFile; String temp=env.getProperty(defFile = (getClass().getName()+".file")); File fIdentities=null; - if(temp==null) { + if (temp==null) { temp = env.getProperty(AAF_DATA_DIR); - if(temp!=null) { + if (temp!=null) { env.warn().log(defFile, " is not defined. Using default: ",temp+"/identities.dat"); File dir = new File(temp); fIdentities=new File(dir,"identities.dat"); - if(!fIdentities.exists()) { + if (!fIdentities.exists()) { env.warn().log("No",fIdentities.getCanonicalPath(),"exists. Creating."); - if(!dir.exists()) { + if (!dir.exists()) { dir.mkdirs(); } fIdentities.createNewFile(); @@ -105,18 +105,18 @@ public class DefaultOrg implements Organization { } } else { fIdentities = new File(temp); - if(!fIdentities.exists()) { + if (!fIdentities.exists()) { String dataDir = env.getProperty(AAF_DATA_DIR); - if(dataDir!=null) { + if (dataDir!=null) { fIdentities = new File(dataDir,temp); } } } - if(fIdentities!=null && fIdentities.exists()) { + if (fIdentities!=null && fIdentities.exists()) { identities = new Identities(fIdentities); } else { - if(fIdentities==null) { + if (fIdentities==null) { throw new OrganizationException("No Identities"); } else { throw new OrganizationException(fIdentities.getCanonicalPath() + " does not exist."); @@ -138,7 +138,7 @@ public class DefaultOrg implements Organization { static { typeSet = new HashSet<>(); - for(Types t : Types.values()) { + for (Types t : Types.values()) { typeSet.add(t.name()); } } @@ -185,9 +185,9 @@ public class DefaultOrg implements Organization { // have domain? int at = id.indexOf('@'); String sid; - if(at > 0) { + if (at > 0) { // Use this to prevent passwords to any but THIS domain. -// if(!id.regionMatches(at+1, domain, 0, id.length()-at-1)) { +// if (!id.regionMatches(at+1, domain, 0, id.length()-at-1)) { // return false; // } sid = id.substring(0,at); @@ -198,7 +198,7 @@ public class DefaultOrg implements Organization { return isValidID(trans, sid)==null; // Check Pattern (if checking existing is too long) - // if(id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) { + // if (id.endsWith(SUFFIX) && ID_PATTERN.matcher(id).matches()) { // return true; // } // return false; @@ -232,13 +232,13 @@ public class DefaultOrg implements Organization { */ @Override public String isValidPassword(final AuthzTrans trans, final String user, final String password, final String... prev) { - for(String p : prev) { - if(password.contains(p)) { // A more sophisticated algorithm might be better. + for (String p : prev) { + if (password.contains(p)) { // A more sophisticated algorithm might be better. return "Password too similar to previous passwords"; } } // If you have an Organization user/Password scheme, replace the following - if(PASS_PATTERN.matcher(password).matches()) { + if (PASS_PATTERN.matcher(password).matches()) { return ""; } return "Password does not match " + NAME + " Password Standards"; @@ -430,7 +430,7 @@ public class DefaultOrg implements Organization { // Extending Password give 5 extra days, max 8 days from now rv.add(GregorianCalendar.DATE, 5); now.add(GregorianCalendar.DATE, 8); - if(rv.after(now)) { + if (rv.after(now)) { rv = now; } break; @@ -453,7 +453,7 @@ public class DefaultOrg implements Organization { // Delegations expire max in 2 months, renewable to 3 rv.add(GregorianCalendar.MONTH, 2); now.add(GregorianCalendar.MONTH, 3); - if(rv.after(now)) { + if (rv.after(now)) { rv = now; } break; @@ -483,9 +483,9 @@ public class DefaultOrg implements Organization { public List<Identity> getApprovers(AuthzTrans trans, String user) throws OrganizationException { Identity orgIdentity = getIdentity(trans, user); List<Identity> orgIdentitys = new ArrayList<>(); - if(orgIdentity!=null) { + if (orgIdentity!=null) { Identity supervisor = orgIdentity.responsibleTo(); - if(supervisor!=null) { + if (supervisor!=null) { orgIdentitys.add(supervisor); } } @@ -519,15 +519,15 @@ public class DefaultOrg implements Organization { switch(policy) { case OWNS_MECHID: case CREATE_MECHID: - if(vars.length>0) { + if (vars.length>0) { DefaultOrgIdentity thisID = getIdentity(trans,vars[0]); - if("a".equals(thisID.identity.status)) { // MechID + if ("a".equals(thisID.identity.status)) { // MechID DefaultOrgIdentity requestor = getIdentity(trans, trans.user()); - if(requestor!=null) { + if (requestor!=null) { Identity mechid = getIdentity(trans, vars[0]); - if(mechid!=null) { + if (mechid!=null) { Identity sponsor = mechid.responsibleTo(); - if(sponsor!=null && requestor.fullID().equals(sponsor.fullID())) { + if (sponsor!=null && requestor.fullID().equals(sponsor.fullID())) { return null; } else { return trans.user() + " is not the Sponsor of MechID " + vars[0]; @@ -558,19 +558,19 @@ public class DefaultOrg implements Organization { private String extractRealm(final String r) { int at; - if((at=r.indexOf('@'))>=0) { + if ((at=r.indexOf('@'))>=0) { return FQI.reverseDomain(r.substring(at+1)); } return r; } @Override public boolean supportsRealm(final String r) { - if(r.endsWith(realm)) { + if (r.endsWith(realm)) { return true; } else { String erealm = extractRealm(r); - for(String sr : supportedRealms) { - if(erealm.startsWith(sr)) { + for (String sr : supportedRealms) { + if (erealm.startsWith(sr)) { return true; } } @@ -588,8 +588,8 @@ public class DefaultOrg implements Organization { Boolean urgent) throws OrganizationException { if (mailer!=null) { List<String> to = new ArrayList<>(); - for(String em : toList) { - if(em.indexOf('@')<0) { + for (String em : toList) { + if (em.indexOf('@')<0) { to.add(new DefaultOrgIdentity(trans, em, this).email()); } else { to.add(em); @@ -597,11 +597,11 @@ public class DefaultOrg implements Organization { } List<String> cc = new ArrayList<>(); - if(ccList!=null) { - if(!ccList.isEmpty()) { + if (ccList!=null) { + if (!ccList.isEmpty()) { - for(String em : ccList) { - if(em.indexOf('@')<0) { + for (String em : ccList) { + if (em.indexOf('@')<0) { cc.add(new DefaultOrgIdentity(trans, em, this).email()); } else { cc.add(em); diff --git a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java index 25832620..ba616ade 100644 --- a/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java +++ b/auth/auth-deforg/src/main/java/org/onap/aaf/org/DefaultOrgIdentity.java @@ -62,7 +62,7 @@ public class DefaultOrgIdentity implements Identity { Reuse r = org.identities.reuse(); int at = key.indexOf(dorg.getDomain()); String search; - if(at>=0) { + if (at>=0) { search = key.substring(0,at); } else { search = key; @@ -71,7 +71,7 @@ public class DefaultOrgIdentity implements Identity { - if(identity==null) { + if (identity==null) { identity = Identities.NO_DATA; } } finally { @@ -84,7 +84,7 @@ public class DefaultOrgIdentity implements Identity { @Override public boolean equals(Object b) { - if(b instanceof DefaultOrgIdentity) { + if (b instanceof DefaultOrgIdentity) { return identity.id.equals(((DefaultOrgIdentity)b).identity.id); } return false; @@ -120,7 +120,7 @@ public class DefaultOrgIdentity implements Identity { @Override public Identity responsibleTo() throws OrganizationException { - if("".equals(identity.responsibleTo) && isFound()) { // cover the situation of Top Dog... reports to no-one. + if ("".equals(identity.responsibleTo) && isFound()) { // cover the situation of Top Dog... reports to no-one. return this; } else { return org.getIdentity(trans, identity.responsibleTo); @@ -151,9 +151,9 @@ public class DefaultOrgIdentity implements Identity { @Override public String mayOwn() { // Assume only Employees are responsible for Resources. - if(identity.status==null|| identity.status.length()==0) { + if (identity.status==null|| identity.status.length()==0) { return "Identity must have valid status"; - } else if(EMPLOYEE.equals(identity.status)) { + } else if (EMPLOYEE.equals(identity.status)) { return null; // This is "Yes, is Responsible" } else { return "Reponsible Party must be an Employee"; diff --git a/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java b/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java index 345e6e82..9f65b418 100644 --- a/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java +++ b/auth/auth-deforg/src/main/java/org/onap/aaf/org/Identities.java @@ -134,7 +134,7 @@ public class Identities extends AbsData { r.reset(); // These are new, to allow for Thread Safety int rec = ti.find(key,r,0); - if(rec<0) { + if (rec<0) { return null; } r.pos(rec); diff --git a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java index b8069ccc..ce34e2a1 100644 --- a/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java +++ b/auth/auth-deforg/src/test/java/org/onap/aaf/org/test/JU_Identities.java @@ -56,7 +56,7 @@ public class JU_Identities { // AuthzTrans trans = env.newTransNoAvg(); // // Note: utilize TimeTaken, from trans.start if you want to time. // fids = new File(DATA_IDENTITIES); -// if(fids.exists()) { +// if (fids.exists()) { // ids = new Identities(fids); // ids.open(trans, 5000); // } else { @@ -72,7 +72,7 @@ public class JU_Identities { // @AfterClass // public static void tearDownAfterClass() throws Exception { // AuthzTrans trans = env.newTransNoAvg(); -// if(ids!=null) { +// if (ids!=null) { // ids.close(trans); // } // } diff --git a/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java b/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java index 128c1f9b..e316e015 100644 --- a/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java +++ b/auth/auth-fs/src/main/java/org/onap/aaf/auth/fs/AAF_FS.java @@ -62,7 +62,7 @@ public class AAF_FS extends AbsService<AuthzEnv, AuthzTrans> { route(env,GET,"/:key", cfa); route(env,GET,"/:key/:cmd", cfa); final String aaf_locate_url = access.getProperty(Config.AAF_LOCATE_URL, null); - if(aaf_locate_url == null) { + if (aaf_locate_url == null) { access.printf(Level.WARN, "Redirection requires property %s",Config.AAF_LOCATE_URL); } else { route(env,GET,"/", new Redirect(this,aaf_locate_url)); diff --git a/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java b/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java index 9915082b..40105c6e 100644 --- a/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java +++ b/auth/auth-fs/src/test/java/org/onap/aaf/auth/fs/test/JU_AAF_FS.java @@ -112,14 +112,14 @@ public class JU_AAF_FS { String[] strArr = {"aaf_component=aaf_com:po.nent"}; try { //AAF_FS.main(strArr); //Timeout caused in Jenkins but not in local - } catch(Exception e) { + } catch (Exception e) { //Failure expected until we understand how code is. } } @After public void cleanUp() { - for(File f : d.listFiles()) { + for (File f : d.listFiles()) { f.delete(); } d.delete(); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java index ecbd0a25..e533abbe 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/cui/CUI.java @@ -51,7 +51,7 @@ public class CUI extends HttpCode<AuthzTrans, Void> { int c; StringBuilder cmd = new StringBuilder(); - while((c=isr.read())>=0) { + while ((c=isr.read())>=0) { cmd.append((char)c); } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java index 84ad1b1f..48164227 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/AAF_GUI.java @@ -124,7 +124,7 @@ public class AAF_GUI extends AbsService<AuthzEnv, AuthzTrans> implements State<E slot_httpServletRequest = env.slot(HTTP_SERVLET_REQUEST); String[] component = Split.split(':', access.getProperty(Config.AAF_COMPONENT, "N/A:2.x")); - if(component.length>1) { + if (component.length>1) { deployedVersion =component[1]; } else { deployedVersion = "2.x"; @@ -217,7 +217,7 @@ public class AAF_GUI extends AbsService<AuthzEnv, AuthzTrans> implements State<E } public void writeError(AuthzTrans trans, Future<?> fp, HTMLGen hgen, int indent) { - if(hgen!=null) { + if (hgen!=null) { String msg = aafCon.readableErrMsg(fp); hgen.incr(HTMLGen.P,"style=text-indent:"+indent*10+"px") .text("<font color=\"red\"><i>Error</i>:</font> ") diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java index c5c14d3f..4f1a7e82 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/BreadCrumbs.java @@ -55,18 +55,18 @@ public class BreadCrumbs extends NamedCode { HttpServletRequest req = trans.get(gui.slot_httpServletRequest, null); StringBuilder key = new StringBuilder(); String value, hidden; - for(Page p : breadcrumbs) { + for (Page p : breadcrumbs) { hidden=""; // Add keys for page from commandline, where possible. - if(p.fields().length>0) { + if (p.fields().length>0) { boolean first = true; key.setLength(0); - for(String field : p.fields()) { - if((value=req.getParameter(field))==null) { + for (String field : p.fields()) { + if ((value=req.getParameter(field))==null) { hidden="style=display:none;"; break; } - if(first) { + if (first) { first = false; key.append('?'); } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java index d1817531..c25d6641 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Display.java @@ -38,7 +38,7 @@ public class Display { final String[] fields = page.fields(); final Slot slots[] = new Slot[fields.length]; String prefix = page.name() + '.'; - for(int i=0;i<slots.length;++i) { + for (int i=0;i<slots.length;++i) { slots[i] = gui.env.slot(prefix + fields[i]); } @@ -49,26 +49,26 @@ public class Display { * we turn such names into arrays with same index number. Then, we place them in the Transaction "Properties" so that * it can be transferred to subclasses easily. */ - if(meth.equals(HttpMethods.POST)) { + if (meth.equals(HttpMethods.POST)) { // Here, we'll expect FORM URL Encoded Data, which we need to get from the body gui.route(gui.env, meth, page.url(), new HttpCode<AuthzTrans,AAF_GUI>(gui,page.name()) { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { trans.put(gui.slot_httpServletRequest, req); - for(int i=0; i<fields.length;++i) { + for (int i=0; i<fields.length;++i) { int idx = fields[i].indexOf("[]"); - if(idx<0) { // single value + if (idx<0) { // single value trans.put(slots[i], req.getParameter(fields[i])); // assume first value } else { // multi value - Expect Values to be set with Field root name "field.<int>" corresponding to an array of types String field=fields[i].substring(0, idx)+'.'; String[] array = new String[16]; - for(Enumeration<String> names = req.getParameterNames(); names.hasMoreElements();) { + for (Enumeration<String> names = req.getParameterNames(); names.hasMoreElements();) { String key = names.nextElement(); - if(key.startsWith(field)) { + if (key.startsWith(field)) { try { int x = Integer.parseInt(key.substring(field.length())); - if(x>=array.length) { + if (x>=array.length) { String[] temp = new String[x+10]; System.arraycopy(temp, 0, temp, 0, array.length); array = temp; @@ -95,20 +95,20 @@ public class Display { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { trans.put(gui.slot_httpServletRequest, req); - for(int i=0; i<slots.length;++i) { + for (int i=0; i<slots.length;++i) { int idx = fields[i].indexOf("[]"); - if(idx<0) { // single value + if (idx<0) { // single value trans.put(slots[i], req.getParameter(fields[i])); } else { // multi value String[] array = new String[30]; String field=fields[i].substring(0, idx); - for(Enumeration<String> mm = req.getParameterNames();mm.hasMoreElements();) { + for (Enumeration<String> mm = req.getParameterNames();mm.hasMoreElements();) { String key = mm.nextElement(); - if(key.startsWith(field)) { + if (key.startsWith(field)) { try { int x = Integer.parseInt(key.substring(field.length())); - if(x>=array.length) { + if (x>=array.length) { String[] temp = new String[x+10]; System.arraycopy(temp, 0, temp, 0, array.length); array = temp; diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java index cc51983b..40aef8fb 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Form.java @@ -45,7 +45,7 @@ public class Form extends NamedCode { @Override public void code(final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { - if(preamble!=null) { + if (preamble!=null) { hgen.incr("p","class=preamble").text(preamble).end(); } hgen.incr("form","method=post"); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java index 37576008..435197c8 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/NamedCode.java @@ -51,7 +51,7 @@ public abstract class NamedCode implements ContentCode { public void addAttr(boolean first, String attr) { String[] temp = new String[idattrs.length+1]; - if(first) { + if (first) { temp[0] = attr; System.arraycopy(idattrs, 0, temp, 1, idattrs.length); } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java index 6010dd8b..deed77c0 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/OrgLookupFilter.java @@ -48,16 +48,16 @@ public class OrgLookupFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { final AuthzTrans trans = (AuthzTrans) req.getAttribute(TransFilter.TRANS_TAG); - if(req instanceof HttpServletRequest) { + if (req instanceof HttpServletRequest) { Principal p = ((HttpServletRequest)req).getUserPrincipal(); - if(p instanceof TaggedPrincipal) { + if (p instanceof TaggedPrincipal) { ((TaggedPrincipal)p).setTagLookup(new TaggedPrincipal.TagLookup() { @Override public String lookup() throws CadiException { Identity id; try { id = trans.org().getIdentity(trans, p.getName()); - if(id!=null && id.isFound()) { + if (id!=null && id.isFound()) { return id.firstName(); } } catch (OrganizationException e) { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java index a44a4846..1e067c44 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Page.java @@ -102,7 +102,7 @@ public class Page extends HTMLCacheGen { super(CacheGen.PRETTY, new PageCode(env, 1, content)); fields = new String[en.length]; int i=-1; - for(Enum<?> p : en) { + for (Enum<?> p : en) { fields[++i]=p.name(); } @@ -110,8 +110,8 @@ public class Page extends HTMLCacheGen { bcUrl = url; // Mark which fields must be "no_cache" boolean no_cacheTemp=false; - for(NamedCode nc : content) { - if(nc.no_cache()) { + for (NamedCode nc : content) { + if (nc.no_cache()) { no_cacheTemp=true; break; } @@ -124,7 +124,7 @@ public class Page extends HTMLCacheGen { public Page(AuthzEnv env, String name, String url, int backdots, String [] fields, final NamedCode ... content) throws APIException,IOException { super(CacheGen.PRETTY, new PageCode(env, backdots, content)); - if(fields==null) { + if (fields==null) { this.fields = new String[0]; } else { this.fields = fields; @@ -133,8 +133,8 @@ public class Page extends HTMLCacheGen { bcUrl = url; // Mark which fields must be "no_cache" boolean no_cacheTemp=false; - for(NamedCode nc : content) { - if(nc.no_cache()) { + for (NamedCode nc : content) { + if (nc.no_cache()) { no_cacheTemp=true; break; } @@ -220,7 +220,7 @@ public class Page extends HTMLCacheGen { // Obtain User Info, and print TaggedPrincipal p = trans.getUserPrincipal(); String user,secured; - if(p==null) { + if (p==null) { user = "please choose a Login Authority"; secured = "NOT Secure!"; } else { @@ -251,7 +251,7 @@ public class Page extends HTMLCacheGen { int cIdx; ContentCode nc; // If BreadCrumbs, put here - if(content.length>0 && content[0] instanceof BreadCrumbs) { + if (content.length>0 && content[0] instanceof BreadCrumbs) { nc = content[0]; Mark ctnt = hgen.divID(nc.idattrs()); nc.code(cache, hgen); @@ -265,7 +265,7 @@ public class Page extends HTMLCacheGen { Mark inner = hgen.divID("inner"); // Content - for(int i=cIdx;i<content.length;++i) { + for (int i=cIdx;i<content.length;++i) { nc = content[i]; Mark ctnt = hgen.divID(nc.idattrs()); nc.code(cache, hgen); @@ -280,28 +280,28 @@ public class Page extends HTMLCacheGen { hgen.incr("h2").text("Related Links").end(); hgen.incr(UL); String aaf_help = env.getProperty(AAF_URL_AAF_HELP,null); - if(aaf_help!=null) { + if (aaf_help!=null) { hgen.leaf(LI).leaf(A,"href="+env.getProperty(AAF_URL_AAF_HELP),"target=_blank").text("AAF WIKI").end(2); String sub = env.getProperty(AAF_URL_AAF_HELP+".sub"); - if(sub!=null) { + if (sub!=null) { hgen.incr(UL,"style=margin-left:5%"); - for(String s : Split.splitTrim(',', sub)) { + for (String s : Split.splitTrim(',', sub)) { hgen.leaf(LI).leaf(A,"href="+env.getProperty(AAF_URL_AAF_HELP+".sub."+s),"target=_blank").text(s.replace('+', ' ')).end(2); } hgen.end(); } } aaf_help = env.getProperty(AAF_URL_CADI_HELP,null); - if(aaf_help!=null) { + if (aaf_help!=null) { hgen.leaf(LI).leaf(A,"href="+aaf_help,"target=_blank").text("CADI WIKI").end(2); } String tools = env.getProperty(AAFURL_TOOLS); - if(tools!=null) { + if (tools!=null) { hgen.hr() .incr(HTMLGen.UL,"style=margin-left:5%") .leaf(HTMLGen.H3).text("Related Tools").end(); - for(String tool : Split.splitTrim(',',tools)) { + for (String tool : Split.splitTrim(',',tools)) { hgen.leaf(LI).leaf(A,"href="+env.getProperty(AAF_URL_TOOL_DOT+tool),"target=_blank").text(tool.replace('+', ' ')).end(2); } hgen.end(); @@ -350,10 +350,10 @@ public class Page extends HTMLCacheGen { */ public static BROWSER browser(AuthzTrans trans, Slot slot) { BROWSER br = trans.get(slot, null); - if(br==null) { + if (br==null) { String agent = trans.agent(); int msie; - if(agent.contains("iPhone") /* other phones? */) { + if (agent.contains("iPhone") /* other phones? */) { br=BROWSER.iPhone; } else if ((msie = agent.indexOf("MSIE"))>=0) { msie+=5; @@ -379,14 +379,14 @@ public class Page extends HTMLCacheGen { protected static synchronized Permission getPerm(String instance, String action) { Map<String,Permission> msp = perms.get(instance); Permission p; - if(msp==null) { + if (msp==null) { msp = new HashMap<>(); perms.put(instance, msp); p=null; } else { p = msp.get(instance); } - if(p==null) { + if (p==null) { p=new AAFPermission(PERM_NS, PERM_CA_TYPE,instance,action); msp.put(action, p); } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java index 844270ed..7462de80 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/SlotCode.java @@ -31,7 +31,7 @@ public abstract class SlotCode<TRANS extends TransStore> extends NamedCode { public SlotCode(boolean no_cache,EnvStore<?> env, String root, Enum<?> ... params) { super(no_cache,root); slots = new Slot[params.length]; - for(int i=0;i<params.length;++i) { + for (int i=0;i<params.length;++i) { slots[i] = env.slot(root + '.' + params[i].name()); } } @@ -41,7 +41,7 @@ public abstract class SlotCode<TRANS extends TransStore> extends NamedCode { } public<T> T get(TRANS trans,int idx, T dflt) { - if(idx>slots.length) { + if (idx>slots.length) { return dflt; } return trans.get(slots[idx],dflt); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java index 079593c9..6451c4e7 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/Table.java @@ -57,15 +57,15 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named public Table(String title, TRANS trans, Data<S,TRANS> data, String name, String ... attrs) { super(true,name); // prefix=postfix=null; - for(String a : attrs) { + for (String a : attrs) { addAttr(false, a); } ROW_MSG_SLOT=trans.slot("TABLE_ROW_MSG"); EMPTY_TABLE_SLOT=trans.slot("TABLE_EMPTY"); this.columns = data.headers(); boolean alt = false; - for(String s : attrs) { - if("class=std".equals(s) || "class=stdform".equals(s)) { + for (String s : attrs) { + if ("class=std".equals(s) || "class=stdform".equals(s)) { alt=true; } } @@ -89,7 +89,7 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named Mark tr = new Mark(); hgen.incr(table,TABLE); - if(title==null) { + if (title==null) { cache.dynamic(hgen, new DynamicCode<HTMLGen,S,TRANS>() { @Override public void code(S state, TRANS trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { @@ -100,7 +100,7 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named hgen.leaf("caption", "class=title").text(title).end(); } hgen.incr(tr,TR); - for(String column : columns) { + for (String column : columns) { hgen.leaf("th").text(column).end(); } hgen.end(tr); @@ -110,7 +110,7 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named // End Table hgen.end(table); - if(other!=null) { + if (other!=null) { other.code(cache,hgen); } @@ -119,10 +119,10 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named @Override public void code(S state, TRANS trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { String msg; - if((msg = trans.get(EMPTY_TABLE_SLOT, null))!=null) { + if ((msg = trans.get(EMPTY_TABLE_SLOT, null))!=null) { hgen.incr("style").text("#inner tr,caption,input,p.preamble {display: none;}#inner p.notfound {margin: 0px 0px 0px 20px}").end(); hgen.incr(HTMLGen.P,"class=notfound").text(msg).end().br(); - } else if((msg=trans.get(ROW_MSG_SLOT,null))!=null) { + } else if ((msg=trans.get(ROW_MSG_SLOT,null))!=null) { hgen.p(msg).br(); } } @@ -181,9 +181,9 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named int alt = this.alt; Cells cells = data.get(trans,state); - if(cells.cells.length>0) { - for(AbsCell[] row : cells.cells) { - if(row.length==0) { + if (cells.cells.length>0) { + for (AbsCell[] row : cells.cells) { + if (row.length==0) { hgen.text("</table>") .hr() .text("<table>"); @@ -198,7 +198,7 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named alt=1; hgen.incr(tr,TR,"class=alt"); } - for(AbsCell cell :row) { + for (AbsCell cell :row) { hgen.leaf(td, TD,cell.attrs()); cell.write(hgen); hgen.end(td); @@ -207,7 +207,7 @@ public class Table<S extends State<Env>, TRANS extends TransStore> extends Named } } // Pass Msg back to Table code, in order to place after Table Complete - if(cells.msg!=null) { + if (cells.msg!=null) { trans.put(ROW_MSG_SLOT,cells.msg); } } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java index f362418e..cf3a6715 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/XFrameFilter.java @@ -52,7 +52,7 @@ public class XFrameFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { - if(resp instanceof HttpServletResponse) { + if (resp instanceof HttpServletResponse) { @SuppressWarnings("unused") HttpServletResponse hresp = (HttpServletResponse)resp; ((HttpServletResponse)resp).addHeader("X-Frame-Options", xframe); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java index 235683d5..7d57b3d8 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiDocs.java @@ -176,11 +176,11 @@ public class ApiDocs extends Page { @Override public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Api> fa = client.read("/api",gui.getDF(Api.class)); - if(fa.get(5000)) { + if (fa.get(5000)) { tt.done(); TimeTaken tt2 = trans.start("Load Data", Env.SUB); try { - if(fa.value!=null)for(Route r : fa.value.getRoute()) { + if (fa.value!=null)for (Route r : fa.value.getRoute()) { String path = r.getPath(); // Build info StringBuilder desc = new StringBuilder(); @@ -188,39 +188,39 @@ public class ApiDocs extends Page { desc.append("<p class=double>"); desc.append(r.getDesc()); - if(r.getComments().size()>0) { - for(String ct : r.getComments()) { + if (r.getComments().size()>0) { + for (String ct : r.getComments()) { desc.append("</p><p class=api_comment>"); desc.append(ct); } } - if(r.getParam().size()>0) { + if (r.getParam().size()>0) { desc.append("<hr><p class=api_label>Parameters</p>"); - for(String params : r.getParam()) { + for (String params : r.getParam()) { String param[] = params.split("\\s*\\|\\s*"); desc.append("</p><p class=api_contentType>"); desc.append(param[0]); desc.append(" : "); desc.append(param[1]); - if("true".equalsIgnoreCase(param[2])) { + if ("true".equalsIgnoreCase(param[2])) { desc.append(" (Required)"); } } } - if(r.getExpected()!=0) { + if (r.getExpected()!=0) { desc.append("</p><p class=api_label>Expected HTTP Code</p><p class=api_comment>"); desc.append(r.getExpected()); } - if(r.getExplicitErr().size()!=0) { + if (r.getExplicitErr().size()!=0) { desc.append("</p><p class=api_label>Explicit HTTP Error Codes</p><p class=api_comment>"); boolean first = true; - for(int ee : r.getExplicitErr()) { - if(first) { + for (int ee : r.getExplicitErr()) { + if (first) { first = false; } else { desc.append(", "); @@ -232,11 +232,11 @@ public class ApiDocs extends Page { desc.append("</p><p class=api_label>"); desc.append("GET".equals(r.getMeth())?"Accept:":"ContentType:"); Collections.sort(r.getContentType()); - if(r.getPath().startsWith("/authn/basicAuth")) { + if (r.getPath().startsWith("/authn/basicAuth")) { desc.append("</p><p class=api_contentType>text/plain"); } - for(String ct : r.getContentType()) { - if(ct.contains("version=2")) { + for (String ct : r.getContentType()) { + if (ct.contains("version=2")) { desc.append("</p><p class=api_contentType><a href=\"./example/"); try { desc.append(Symm.base64noSplit.encode(ct)); @@ -258,16 +258,16 @@ public class ApiDocs extends Page { new TextCell(desc.toString()), }; - if(path.startsWith("/authz/perm")) { + if (path.startsWith("/authz/perm")) { sa[0] = perms.size()==0?new TextCell("PERMISSION"):BLANK; perms.add(sa); - } else if(path.startsWith("/authz/role") || path.startsWith("/authz/userRole")) { + } else if (path.startsWith("/authz/role") || path.startsWith("/authz/userRole")) { sa[0] = roles.size()==0?new TextCell("ROLE"):BLANK; roles.add(sa); - } else if(path.startsWith("/authz/ns")) { + } else if (path.startsWith("/authz/ns")) { sa[0] = ns.size()==0?new TextCell("NAMESPACE"):BLANK; ns.add(sa); - } else if(path.startsWith("/authn/basicAuth") + } else if (path.startsWith("/authn/basicAuth") || path.startsWith("/authn/validate") || path.startsWith("/authz/user")) { sa[0] = user.size()==0?new TextCell("USER"):BLANK; @@ -277,7 +277,7 @@ public class ApiDocs extends Page { aafOnly.add(sa); } } - //TODO if(trans.fish(p)) + //TODO if (trans.fish(p)) prepare(rv, perms,roles,ns,user); } finally { tt2.done(); @@ -301,8 +301,8 @@ public class ApiDocs extends Page { private void prepare(ArrayList<AbsCell[]> rv, ArrayList<AbsCell[]> ... all) { AbsCell lead; AbsCell[] row; - for(ArrayList<AbsCell[]> al : all) { - if(al.size()>1) { + for (ArrayList<AbsCell[]> al : all) { + if (al.size()>1) { row = al.get(0); lead = row[0]; row[0]=BLANK; @@ -312,7 +312,7 @@ public class ApiDocs extends Page { public int compare(AbsCell[] ca1, AbsCell[] ca2) { int meth = ((TextCell)ca1[2]).name.compareTo( ((TextCell)ca2[2]).name); - if(meth == 0) { + if (meth == 0) { return (HttpMethods.valueOf(((TextCell)ca1[1]).name).compareTo( HttpMethods.valueOf(((TextCell)ca2[1]).name))); } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java index 3beed563..7da77607 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApiExample.java @@ -79,7 +79,7 @@ public class ApiExample extends Page { "application/Void+json" ); Future<String> fs2; - if(typecode.contains("Request+")) { + if (typecode.contains("Request+")) { fs2 = gui.client().read("/api/example/" + encoded+"?optional=true", "application/Void+json" ); @@ -88,19 +88,19 @@ public class ApiExample extends Page { } - if(fp.get(5000)) { + if (fp.get(5000)) { xgen.incr(HTMLGen.H1).text("Sample Code").end() .incr(HTMLGen.H5).text(typecode).end(); xgen.incr("pre"); - if(typecode.contains("+xml")) { + if (typecode.contains("+xml")) { xgen.xml(fp.body()); - if(fs2!=null && fs2.get(5000)) { + if (fs2!=null && fs2.get(5000)) { xgen.text(WITH_OPTIONAL_PARAMETERS); xgen.xml(fs2.body()); } } else { xgen.text(fp.body()); - if(fs2!=null && fs2.get(5000)) { + if (fs2!=null && fs2.get(5000)) { xgen.text(WITH_OPTIONAL_PARAMETERS); xgen.text(fs2.body()); } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java index 507cb21a..8c90b491 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalAction.java @@ -63,16 +63,16 @@ public class ApprovalAction extends Page { lastPage += "?user="+user; } - if(appr==null) { + if (appr==null) { hgen.p("No Approvals have been selected."); } else { Approval app; final Approvals apps = new Approvals(); int count = 0; - for(String a : appr) { - if(a!=null) { + for (String a : appr) { + if (a!=null) { int idx = a.indexOf('|'); - if(idx>=0) { + if (idx>=0) { app = new Approval(); app.setStatus(a.substring(0,idx)); app.setTicket(a.substring(++idx)); @@ -82,7 +82,7 @@ public class ApprovalAction extends Page { } } } - if(apps.getApprovals().isEmpty()) { + if (apps.getApprovals().isEmpty()) { hgen.p("No Approvals have been sent."); } else { TimeTaken tt = trans.start("AAF Update Approvals",Env.REMOTE); @@ -93,7 +93,7 @@ public class ApprovalAction extends Page { public Boolean code(Rcli<?> client) throws APIException, CadiException { boolean fail2 = true; Future<Approvals> fa = client.update("/authz/approval",gui.getDF(Approvals.class),apps); - if(fa.get(AAF_GUI.TIMEOUT)) { + if (fa.get(AAF_GUI.TIMEOUT)) { // Do Remote Call fail2 = false; hgen.p(total + (total==1?" Approval has":" Approvals have") + " been Saved"); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java index 14d434cb..27fd5274 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/ApprovalForm.java @@ -146,9 +146,9 @@ public class ApprovalForm extends Page { public Integer code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Approvals> fa = client.read("/authz/approval/approver/"+trans.user(),gui.getDF(Approvals.class)); int numLeft = 0; - if(fa.get(AAF_GUI.TIMEOUT)) { + if (fa.get(AAF_GUI.TIMEOUT)) { - if(fa.value!=null) { + if (fa.value!=null) { for (Approval appr : fa.value.getApprovals()) { if ("pending".equals(appr.getStatus())) { if (userParam!=null && !appr.getUser().equalsIgnoreCase(userParam)) { @@ -227,23 +227,23 @@ public class ApprovalForm extends Page { boolean userOK=true; for (Approval appr : currApproverList) { - if(++line<MAX_LINE) { // limit number displayed at one time. + if (++line<MAX_LINE) { // limit number displayed at one time. AbsCell userCell; String user = appr.getUser(); - if(user.equals(prevUser)) { + if (user.equals(prevUser)) { userCell = AbsCell.Null; } else if (user.endsWith(DOMAIN_OF_USER)){ userOK=true; String title; Organization org = OrganizationFactory.obtain(trans.env(), user); - if(org==null) { + if (org==null) { title=""; } else { Identity au = org.getIdentity(trans, user); - if(au!=null) { - if("MECHID".equals(au.type())) { + if (au!=null) { + if ("MECHID".equals(au.type())) { Identity managedBy = au.responsibleTo(); - if(managedBy==null) { + if (managedBy==null) { title ="title=" + au.type(); } else { title="title=Sponsor is " + managedBy.fullName(); @@ -276,10 +276,10 @@ public class ApprovalForm extends Page { } } } - if(numLeft>0) { + if (numLeft>0) { msg = "After these, there will be " + numLeft + " approvals left to process"; } - if(rv.isEmpty()) { + if (rv.isEmpty()) { if (numLeft>0) { msg = "No Approvals to process at this time for user " + userParam +". You have " + numLeft + " other approvals to process."; diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java index 8088a700..d32c7dc3 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeAction.java @@ -77,34 +77,34 @@ trans.info().log("Step 1"); final String machine = trans.get(sMachine,null); final String ca = trans.get(sCA, null); final String sans = ((String)trans.get(sSans,null)); - if(sans!=null) { - for(String s: Split.splitTrim(',', sans)) { + if (sans!=null) { + for (String s: Split.splitTrim(',', sans)) { arti.getSans().add(s); } } // Disallow IP entries, except by special Permission - if(!trans.fish(getPerm(ca,"ip"))) { + if (!trans.fish(getPerm(ca,"ip"))) { boolean ok=true; - if(IPValidator.ip(machine)) { + if (IPValidator.ip(machine)) { ok=false; } - if(ok) { - for(String s: arti.getSans()) { - if(IPValidator.ip(s)) { + if (ok) { + for (String s: arti.getSans()) { + if (IPValidator.ip(s)) { ok=false; break; } } } - if(!ok) { + if (!ok) { hgen.p("Policy Failure: IPs in certificates are only allowed by Exception."); return; } } // Disallow Domain based Definitions without exception - if(machine.startsWith("*")) { // Domain set - if(!trans.fish(getPerm(ca, "domain"))) { + if (machine.startsWith("*")) { // Domain set + if (!trans.fish(getPerm(ca, "domain"))) { hgen.p("Policy Failure: Domain Artifact Declarations are only allowed by Exception."); return; } @@ -119,8 +119,8 @@ trans.info().log("Step 1"); arti.setRenewDays(Integer.parseInt((String)trans.get(sRenewal, null))); arti.setNotification((String)trans.get(sNotify, null)); String[] checkbox = trans.get(sType,null); - for(int i=0;i<CMArtiChangeForm.types.length;++i) { - if("on".equals(checkbox[i])) { + for (int i=0;i<CMArtiChangeForm.types.length;++i) { + if ("on".equals(checkbox[i])) { arti.getType().add(CMArtiChangeForm.types[i]); } } @@ -144,14 +144,14 @@ trans.info().log("Step 1"); case CMArtiChangeForm.CREATE: Future<Artifacts> fc; rv = fc = client.create("/cert/artifacts", gui.artifactsDF, artifacts); - if(fc.get(AAFcli.timeout())) { + if (fc.get(AAFcli.timeout())) { hgen.p("Created Artifact " + arti.getMechid() + " on " + arti.getMachine()); ok.set(true); } break; case CMArtiChangeForm.UPDATE: Future<Artifacts> fu = client.update("/cert/artifacts", gui.artifactsDF, artifacts); - if((rv=fu).get(AAFcli.timeout())) { + if ((rv=fu).get(AAFcli.timeout())) { hgen.p("Artifact " + arti.getMechid() + " on " + arti.getMachine() + " is updated"); ok.set(true); } @@ -159,12 +159,12 @@ trans.info().log("Step 1"); case CMArtiChangeForm.COPY: Future<Artifacts> future = client.read("/cert/artifacts/"+arti.getMechid()+'/'+arti.getMachine(), gui.artifactsDF); rv = future; - if(future.get(AAFcli.timeout())) { - for(Artifact a : future.value.getArtifact()) { // only one, because these two are key - for(String newMachine :Split.split(',', trans.get(sOther, ""))) { + if (future.get(AAFcli.timeout())) { + for (Artifact a : future.value.getArtifact()) { // only one, because these two are key + for (String newMachine :Split.split(',', trans.get(sOther, ""))) { a.setMachine(newMachine); Future<Artifacts> fup = client.update("/cert/artifacts", gui.artifactsDF, future.value); - if(fup.get(AAFcli.timeout())) { + if (fup.get(AAFcli.timeout())) { hgen.p("Copied to " + newMachine); ok.set(true); } @@ -175,7 +175,7 @@ trans.info().log("Step 1"); case CMArtiChangeForm.DELETE: Future<Void> fv; rv = fv = client.delete("/cert/artifacts/"+arti.getMechid()+"/"+arti.getMachine(),"application/json"); - if(fv.get(AAFcli.timeout())) { + if (fv.get(AAFcli.timeout())) { hgen.p("Deleted " + arti.getMechid() + " on " + arti.getMachine()); ok.set(true); deleted.set(true); @@ -185,11 +185,11 @@ trans.info().log("Step 1"); return rv; } }); - if(!ok.get()) { - if(f==null) { + if (!ok.get()) { + if (f==null) { hgen.p("Unknown Command"); } else { - if(f.body().contains("%")) { + if (f.body().contains("%")) { Error err = gui.getDF(Error.class).newData().in(TYPE.JSON).load(f.body()).asObject(); hgen.p(Vars.convert(err.getText(),err.getVariables())); } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java index 0268f498..ee55fdbc 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtiChangeForm.java @@ -138,25 +138,25 @@ public class CMArtiChangeForm extends Page { @Override public Artifact code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Artifacts> fa = client.read("/cert/artifacts/"+incomingID+'/'+incomingMach, gui.artifactsDF); - if(fa.get(AAFcli.timeout())) { - for(Artifact arti : fa.value.getArtifact()) { + if (fa.get(AAFcli.timeout())) { + for (Artifact arti : fa.value.getArtifact()) { return arti; // just need the first one } } return null; } }); - if(arti==null) { + if (arti==null) { Organization org = OrganizationFactory.get(trans); Identity user = org.getIdentity(trans, incomingID); - if(user==null) { + if (user==null) { hgen.p("The mechID you typed, \"" + incomingID + "\", is not a valid " + org.getName() + " ID"); return; } arti = new Artifact(); arti.setMechid(incomingID); Identity managedBy = user.responsibleTo(); - if(managedBy == null) { + if (managedBy == null) { arti.setSponsor("Unknown Sponsor"); } else { arti.setSponsor(managedBy.fullID()); @@ -173,7 +173,7 @@ public class CMArtiChangeForm extends Page { submitText = CREATE; delete = false; } else { - if(arti.getNotification()==null) { + if (arti.getNotification()==null) { Organization org = OrganizationFactory.get(trans); Identity user = org.getIdentity(trans, incomingID); arti.setNotification("mailto:"+user.email()); @@ -184,15 +184,15 @@ public class CMArtiChangeForm extends Page { .input(fields[0],"AppID*",true,"value="+arti.getMechid()) .input("sponsor", "Sponsor",false,"value="+arti.getSponsor(),"readonly","style=border:none;background-color:white;") .input(fields[1],"FQDN*",true,"value="+arti.getMachine(),"style=width:130%;"); -// if(maySans) { +// if (maySans) { hgen.incr(HTMLGen.TR).incr(HTMLGen.TD).end() .incr(HTMLGen.TD,"class=subtext").text("Use Fully Qualified Domain Names (that will be in DNS), "); - if(!trans.fish(getPerm(arti.getCa(),"ip"))) { + if (!trans.fish(getPerm(arti.getCa(),"ip"))) { hgen.text("NO "); } StringBuilder sb = null; - for(String s: arti.getSans()) { - if(sb==null) { + for (String s: arti.getSans()) { + if (sb==null) { sb = new StringBuilder(); } else { sb.append(", "); @@ -212,7 +212,7 @@ public class CMArtiChangeForm extends Page { .incr(HTMLGen.TR) .incr(HTMLGen.TD).leaf("label","for=types","required").text("Artifact Types").end(2) .incr(HTMLGen.TD); - for(int i=0;i<types.length;++i) { + for (int i=0;i<types.length;++i) { hgen.leaf("input","type=checkbox","name=types."+i,arti.getType().contains(types[i])?"checked":"").text(types[i]).end().br(); } @@ -232,7 +232,7 @@ public class CMArtiChangeForm extends Page { hgen.tagOnly("input","id="+fields[8],"name="+fields[8],"value="+submitText,"style=display:none;"); hgen.tagOnly("input","id=theButton","type=submit", "orig="+submitText,"value="+submitText); - } catch(CadiException | LocatorException | OrganizationException e) { + } catch (CadiException | LocatorException | OrganizationException e) { throw new APIException(e); } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtifactShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtifactShow.java index 0992ad3d..85797cb5 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtifactShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CMArtifactShow.java @@ -118,11 +118,11 @@ public class CMArtifactShow extends Page { @Override protected String title(AuthzTrans trans) { StringBuilder sb = new StringBuilder("X509 Certificates"); - if(sc!=null) { // initialized + if (sc!=null) { // initialized sb.append(" for "); String id = sc.get(trans,Params.id,""); sb.append(id); - if(id.indexOf('@')<0) { + if (id.indexOf('@')<0) { sb.append('@'); sb.append(FQI.reverseDomain(sc.get(trans, Params.ns,"missingDomain"))); } @@ -155,7 +155,7 @@ public class CMArtifactShow extends Page { @Override public Cells get(final AuthzTrans trans, final AAF_GUI gui) { String str = sc.get(trans,Params.id, null); - if(str==null) { + if (str==null) { return Cells.EMPTY; } final String id = str.indexOf('@')>=0?str:str + '@' + FQI.reverseDomain(sc.get(trans,Params.ns, "")); @@ -169,7 +169,7 @@ public class CMArtifactShow extends Page { Future<Artifacts> fuArt = client.read("/cert/artifacts?mechid="+id, gui.artifactsDF); X509Certificate[] lc; - if(fuCI.get(AAFcli.timeout())) { + if (fuCI.get(AAFcli.timeout())) { TimeTaken tt1 = trans.start("x509Certificate", Env.SUB); try { Collection<? extends Certificate> xcs = Factory.toX509Certificate(fuCI.value.getCerts()); @@ -185,8 +185,8 @@ public class CMArtifactShow extends Page { lc = null; trans.error().log("Cannot retrieve Certificates for " + id); } - if(fuArt.get(AAFcli.timeout())) { - for(Artifact arti : fuArt.value.getArtifact()) { + if (fuArt.get(AAFcli.timeout())) { + for (Artifact arti : fuArt.value.getArtifact()) { StringWriter sw = new StringWriter(); HTMLGen hgen = cas.clone(sw); Mark mark = new Mark(); @@ -195,17 +195,17 @@ public class CMArtifactShow extends Page { .text("Details") .end(mark); Date last = null; - if(lc!=null) { - for(X509Certificate xc : lc) { - if(xc.getSubjectDN().getName().contains("CN="+arti.getMachine())) { - if(last==null || last.before(xc.getNotAfter())) { + if (lc!=null) { + for (X509Certificate xc : lc) { + if (xc.getSubjectDN().getName().contains("CN="+arti.getMachine())) { + if (last==null || last.before(xc.getNotAfter())) { last = xc.getNotAfter(); } } } } GregorianCalendar renew; - if(last!=null) { + if (last!=null) { renew = new GregorianCalendar(); renew.setTime(last); renew.add(GregorianCalendar.DAY_OF_MONTH,arti.getRenewDays()*-1); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java index 7daee3dd..00e58c87 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/CredDetail.java @@ -90,13 +90,13 @@ public class CredDetail extends Page { Mark js = new Mark(), fn=new Mark(); hgen.js(js).function(fn,"newArtifact") .text("id=document.getElementById('id');") - .text("if(id.value=='') {alert('Enter the id in box');} else {") + .text("if (id.value=='') {alert('Enter the id in box');} else {") .text("window.open('"+CMArtiChangeForm.HREF+"?id='+id.value+'&ns="+ns+"','_self');}" ) .end(fn) .function("newPassword") .text("id=document.getElementById('id');") - .text("if(id.value=='') {alert('Enter the id in box');} else {") + .text("if (id.value=='') {alert('Enter the id in box');} else {") .text("window.open('"+PassChangeForm.HREF+"?id='+id.value+'@"+domain+"&ns="+ns+"','_self');}" ) .end(js); @@ -145,7 +145,7 @@ public class CredDetail extends Page { public Cells get(final AuthzTrans trans, final AAF_GUI gui) { final String ns = sc.get(trans, Params.ns, ""); final String id = sc.get(trans, Params.id, ""); - if(ns==null) { + if (ns==null) { return Cells.EMPTY; } final ArrayList<AbsCell[]> rv = new ArrayList<>(); @@ -156,7 +156,7 @@ public class CredDetail extends Page { @Override public List<Artifact> code(Rcli<?> client)throws CadiException, ConnectException, APIException { Future<Artifacts> fa = client.read("/cert/artifacts?ns="+ns,gui.artifactsDF); - if(fa.get(AAFcli.timeout())) { + if (fa.get(AAFcli.timeout())) { return fa.value.getArtifact(); } else { return null; @@ -165,8 +165,8 @@ public class CredDetail extends Page { }); final Set<String> lns = new HashSet<>(); - if(la!=null) { - for(Artifact a : la){ + if (la!=null) { + for (Artifact a : la){ lns.add(a.getMechid()); } } @@ -174,7 +174,7 @@ public class CredDetail extends Page { @Override public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Users> fu = client.read("/authn/creds/ns/"+ns,gui.getDF(Users.class)); - if(fu.get(AAFcli.timeout())) { + if (fu.get(AAFcli.timeout())) { // Organize User entries Map<String,List<Map<Integer,List<User>>>> users = new HashMap<>(); @@ -183,26 +183,26 @@ public class CredDetail extends Page { List<User> lu = null; for (User u : fu.value.getUser()) { - if(u.getType() == 200) { + if (u.getType() == 200) { lns.remove(u.getId()); } lmu = users.get(u.getId()); - if(lmu==null) { + if (lmu==null) { users.put(u.getId(),lmu=new ArrayList<>()); } mu=null; - for(Map<Integer,List<User>> xmu : lmu) { - if(xmu.containsKey(u.getType())) { + for (Map<Integer,List<User>> xmu : lmu) { + if (xmu.containsKey(u.getType())) { mu = xmu; } } - if(mu==null) { + if (mu==null) { lmu.add(mu=new HashMap<>()); } lu = mu.get(u.getType()); - if(lu==null) { + if (lu==null) { mu.put(u.getType(),lu = new ArrayList<>()); } lu.add(u); @@ -218,7 +218,7 @@ public class CredDetail extends Page { StringWriter creds = new StringWriter(); hgen = cd.clone(creds); Mark div = hgen.divID(key,ulm.getKey().equals(id)?"":"style=display:none;"); - for(Map<Integer, List<User>> miu : ulm.getValue()) { + for (Map<Integer, List<User>> miu : ulm.getValue()) { Mark utable = new Mark(); hgen.leaf(utable,HTMLGen.TABLE); @@ -226,7 +226,7 @@ public class CredDetail extends Page { String cls; boolean first = true; - for( Entry<Integer, List<User>> es : miu.entrySet()) { + for ( Entry<Integer, List<User>> es : miu.entrySet()) { Collections.sort(es.getValue(),new Comparator<User>() { @Override public int compare(User u1, User u2) { @@ -237,22 +237,22 @@ public class CredDetail extends Page { int xcnt = 0; XMLGregorianCalendar oldest=null, newest=null; String id = null; - for(User u: es.getValue()) { - if(id==null) { + for (User u: es.getValue()) { + if (id==null) { id = u.getId(); } // Need to compile entries for Certificates on this screen - if(es.getKey()==200) { + if (es.getKey()==200) { ++xcnt; - if(oldest==null || oldest.compare(u.getExpires())<0) { + if (oldest==null || oldest.compare(u.getExpires())<0) { oldest = u.getExpires(); } - if(newest==null || newest.compare(u.getExpires())<0) { + if (newest==null || newest.compare(u.getExpires())<0) { newest = u.getExpires(); } } else { hgen.leaf(uRow,HTMLGen.TR); - if(first) { + if (first) { hgen.leaf(HTMLGen.TD,cls="class=detailFirst",STYLE_WIDTH_10); switch(es.getKey()) { case 1: @@ -274,7 +274,7 @@ public class CredDetail extends Page { "&date="+u.getExpires().toXMLFormat() + "&type="+u.getType()) .text("Delete").end(); - if(first && es.getKey()<10) { // Change Password Screen + if (first && es.getKey()<10) { // Change Password Screen hgen.leaf(HTMLGen.A,"class=button","href="+PassChangeForm.HREF+"?id="+id+"&ns="+ns) .text("Add") .end(); @@ -287,7 +287,7 @@ public class CredDetail extends Page { hgen.end(uRow); } } - if(xcnt>0) { // print compilations, if any, of Certificate + if (xcnt>0) { // print compilations, if any, of Certificate hgen.leaf(uRow,HTMLGen.TR) .leaf(HTMLGen.TD,cls="class=detailFirst",STYLE_WIDTH_10).text("x509").end() .leaf(HTMLGen.TD, cls,STYLE_WIDTH_20) @@ -316,7 +316,7 @@ public class CredDetail extends Page { new TextCell(creds.toString(),STYLE_WIDTH_70) }); } - for(String missing : lns) { + for (String missing : lns) { StringWriter buttons = new StringWriter(); HTMLGen hgen = cd.clone(buttons); hgen.leaf(HTMLGen.A,"class=button","href="+CMArtifactShow.HREF+"?id="+missing+"&ns="+ns) diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java index 5b614edc..3fd69aca 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/LoginLanding.java @@ -56,10 +56,10 @@ public class LoginLanding extends Page { @Override public void code(AAF_GUI authGUI, AuthzTrans trans, Cache<HTMLGen> cache, HTMLGen xgen) throws APIException, IOException { HttpServletRequest req = trans.get(gui.slot_httpServletRequest, null); - if(req!=null) { + if (req!=null) { String query = req.getQueryString(); - if(query!=null) { - for(String qs : query.split("&")) { + if (query!=null) { + for (String qs : query.split("&")) { int equals = qs.indexOf('='); xgen.leaf(HTMLGen.A, "href="+URLDecoder.decode(qs.substring(equals+1),Config.UTF_8)).text(qs.substring(0,equals).replace('_', ' ')).end(); } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java index faf657e7..c7515e00 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsDetail.java @@ -76,7 +76,7 @@ public class NsDetail extends Page { model.set(this); keySlot = gui.env.slot(NAME+".ns"); gw_url = gui.env.getProperty(Config.GW_URL); - if(gw_url==null) { + if (gw_url==null) { gw_url=""; } else { gw_url+="/aaf/2.0"; @@ -101,12 +101,12 @@ public class NsDetail extends Page { final String nsName = trans.get(keySlot, null); Validator v = new Validator(); v.ns(nsName); - if(v.err()) { + if (v.err()) { trans.warn().printf("Error in NsDetail Request: %s", v.errs()); return Cells.EMPTY; } - if(nsName==null) { + if (nsName==null) { return Cells.EMPTY; } final ArrayList<AbsCell[]> rv = new ArrayList<>(); @@ -119,12 +119,12 @@ public class NsDetail extends Page { public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Nss> fn = client.read("/authz/nss/"+nsName,gui.getDF(Nss.class)); - if(fn.get(AAF_GUI.TIMEOUT)) { + if (fn.get(AAF_GUI.TIMEOUT)) { tt.done(); try { // TimeTaken tt = trans.start("Load Data", Env.SUB); - for(Ns n : fn.value.getNs()) { + for (Ns n : fn.value.getNs()) { String desc = (n.getDescription()!=null?n.getDescription():BLANK); rv.add(new AbsCell[]{new TextCell("Description:"),new TextCell(desc)}); @@ -145,7 +145,7 @@ public class NsDetail extends Page { gui.getDF(Roles.class) ); List<String> roles = new ArrayList<>(); - if(fr.get(AAFcli.timeout())) { + if (fr.get(AAFcli.timeout())) { for (Role r : fr.value.getRole()) { roles.add(r.getName()); } @@ -159,7 +159,7 @@ public class NsDetail extends Page { ); List<String> perms = new ArrayList<>(); - if(fp.get(AAFcli.timeout())) { + if (fp.get(AAFcli.timeout())) { for (Perm p : fp.value.getPerm()) { perms.add(p.getType() + "|" + p.getInstance() + "|" + p.getAction()); } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java index 7d11e66f..bca6c92c 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsHistory.java @@ -164,7 +164,7 @@ public class NsHistory extends Page { final String oName = trans.get(name,null); final String oDates = trans.get(dates,null); - if(oName==null) { + if (oName==null) { return Cells.EMPTY; } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java index 8a2da3d3..cb942c6c 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoAction.java @@ -71,9 +71,9 @@ public class NsInfoAction extends Page { if (id==null || id.indexOf('@')<=0) { hgen.p("Data Entry Failure: Please enter a valid ID, including domain."); - } else if(password == null || password2 == null || currPass == null) { + } else if (password == null || password2 == null || currPass == null) { hgen.p("Data Entry Failure: Both Password Fields need entries."); - } else if(!password.equals(password2)) { + } else if (!password.equals(password2)) { hgen.p("Data Entry Failure: Passwords do not match."); } else { // everything else is checked by Server final CredRequest cred = new CredRequest(); @@ -93,21 +93,21 @@ public class NsInfoAction extends Page { boolean go; boolean fail = true; fcr.get(5000); - if(fcr.code() == 200) { + if (fcr.code() == 200) { hgen.p("Current Password validated"); go = true; } else { hgen.p(String.format("Invalid Current Password: %d %s",fcr.code(),fcr.body())); go = false; } - if(go) { + if (go) { tt.done(); tt = trans.start("AAF Change Password",Env.REMOTE); try { // Change over Cred to reset mode cred.setPassword(password); String start = trans.get(startDate, null); - if(start!=null) { + if (start!=null) { try { cred.setStart(Chrono.timeStamp(Chrono.dateOnlyFmt.parse(start))); } catch (ParseException e) { @@ -121,7 +121,7 @@ public class NsInfoAction extends Page { cred ); - if(fcr.get(5000)) { + if (fcr.get(5000)) { // Do Remote Call hgen.p("New Password has been added."); fail = false; @@ -145,7 +145,7 @@ public class NsInfoAction extends Page { } } hgen.br(); - if(fail) { + if (fail) { hgen.incr("a",true,"href="+PassChangeForm.HREF+"?id="+id).text("Try again").end(); } else { hgen.incr("a",true,"href="+Home.HREF).text("Home").end(); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java index 2447c98b..2306a1a5 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NsInfoForm.java @@ -80,21 +80,21 @@ public class NsInfoForm extends Page { final String incomingID= trans.get(sID, ""); final String[] info = new String[fields.length]; final Object own_adm[] = new Object[2]; - for(int i=0;i<info.length;++i) { + for (int i=0;i<info.length;++i) { info[i]=""; } - if(incomingID.length()>0) { + if (incomingID.length()>0) { TimeTaken tt = trans.start("AAF Namespace Info",Env.REMOTE); try { gui.clientAsUser(trans.getUserPrincipal(), new Retryable<Void>() { @Override public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Nss> fn = client.read("/authz/nss/"+incomingID,gui.getDF(Nss.class)); - if(fn.get(AAF_GUI.TIMEOUT)) { - for(Ns ns : fn.value.getNs()) { + if (fn.get(AAF_GUI.TIMEOUT)) { + for (Ns ns : fn.value.getNs()) { info[0]=ns.getName(); info[1]=ns.getDescription(); - for(Ns.Attrib attr: ns.getAttrib()) { + for (Ns.Attrib attr: ns.getAttrib()) { switch(attr.getKey()) { case "mots": info[2]=attr.getValue(); @@ -128,8 +128,8 @@ public class NsInfoForm extends Page { .end(endTD) .incr(endTD,HTMLGen.TD) .tagOnly("input","id="+fields[3],"title=Owner of App, must be an Non-Bargained Employee"); - if(own_adm[0]!=null) { - for(String s : (List<String>)own_adm[0]) { + if (own_adm[0]!=null) { + for (String s : (List<String>)own_adm[0]) { hgen.incr("label",true).text(s).end(); } } @@ -142,8 +142,8 @@ public class NsInfoForm extends Page { .end(endTD) .incr(endTD,HTMLGen.TD) .tagOnly("input","id="+fields[4],"title=Admins may be employees, contractors or mechIDs"); - if(own_adm[1]!=null) { - for(String s : (List<String>)own_adm[1]) { + if (own_adm[1]!=null) { + for (String s : (List<String>)own_adm[1]) { hgen.incr(HTMLGen.P,true).text(s).end(); } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java index b2a6e368..6f090a49 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/NssShow.java @@ -85,7 +85,7 @@ public class NssShow extends Page { public Cells get(final AuthzTrans trans, final AAF_GUI gui) { ArrayList<AbsCell[]> rv = new ArrayList<>(); List<Ns> nss = trans.get(sNssByUser, null); - if(nss==null) { + if (nss==null) { TimeTaken tt = trans.start("AAF Nss by User for " + privilege,Env.REMOTE); try { nss = gui.clientAsUser(trans.getUserPrincipal(), new Retryable<List<Ns>>() { @@ -93,10 +93,10 @@ public class NssShow extends Page { public List<Ns> code(Rcli<?> client) throws CadiException, ConnectException, APIException { List<Ns> nss = null; Future<Nss> fp = client.read("/authz/nss/either/" + trans.user(),gui.getDF(Nss.class)); - if(fp.get(AAF_GUI.TIMEOUT)) { + if (fp.get(AAF_GUI.TIMEOUT)) { TimeTaken tt = trans.start("Load Data for " + privilege, Env.SUB); try { - if(fp.value!=null) { + if (fp.value!=null) { nss = fp.value.getNs(); Collections.sort(nss, new Comparator<Ns>() { public int compare(Ns ns1, Ns ns2) { @@ -121,9 +121,9 @@ public class NssShow extends Page { } } - if(nss!=null) { - for(Ns n : nss) { - if((isAdmin && !n.getAdmin().isEmpty()) + if (nss!=null) { + for (Ns n : nss) { + if ((isAdmin && !n.getAdmin().isEmpty()) || (!isAdmin && !n.getResponsible().isEmpty())) { AbsCell[] sa = new AbsCell[] { new RefCell(n.getName(),NsDetail.HREF diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java index aafd0c96..10af074a 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeAction.java @@ -82,9 +82,9 @@ public class PassChangeAction extends Page { if (id==null || id.indexOf('@')<=0) { hgen.p("Data Entry Failure: Please enter a valid ID, including domain."); - } else if(password == null || password2 == null) { + } else if (password == null || password2 == null) { hgen.p("Data Entry Failure: Both Password Fields need entries."); - } else if(!password.equals(password2)) { + } else if (!password.equals(password2)) { hgen.p("Data Entry Failure: Passwords do not match."); } else { // everything else is checked by Server final CredRequest cred = new CredRequest(); @@ -98,30 +98,30 @@ public class PassChangeAction extends Page { boolean go = false; try { Organization org = OrganizationFactory.obtain(trans.env(), id); - if(org!=null) { + if (org!=null) { go = PassChangeForm.skipCurrent(trans, org.getIdentity(trans, id)); } - } catch(OrganizationException e) { + } catch (OrganizationException e) { trans.error().log(e); } - if(cred.getPassword()==null) { + if (cred.getPassword()==null) { try { - if(!go) { + if (!go) { go=gui.clientAsUser(trans.getUserPrincipal(), new Retryable<Boolean>() { @Override public Boolean code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Users> fc = client.read("/authn/creds/id/"+id,gui.getDF(Users.class)); - if(fc.get(AAFcli.timeout())) { + if (fc.get(AAFcli.timeout())) { GregorianCalendar now = new GregorianCalendar(); - for(aaf.v2_0.Users.User u : fc.value.getUser()) { - if(u.getType()<10 && u.getExpires().toGregorianCalendar().after(now)) { + for (aaf.v2_0.Users.User u : fc.value.getUser()) { + if (u.getType()<10 && u.getExpires().toGregorianCalendar().after(now)) { return false; // an existing, non expired, password type exists } } return true; // no existing, no expired password } else { - if(fc.code()==404) { // not found... + if (fc.code()==404) { // not found... return true; } else { trans.error().log(gui.aafCon.readableErrMsg(fc)); @@ -131,7 +131,7 @@ public class PassChangeAction extends Page { } }); } - if(!go) { + if (!go) { hgen.p("Current Password required").br(); } } catch (LocatorException e) { @@ -144,7 +144,7 @@ public class PassChangeAction extends Page { // Note: Need "Post", because of hiding password in SSL Data Future<CredRequest> fcr = client.create("/authn/validate",gui.getDF(CredRequest.class),cred); fcr.get(5000); - if(fcr.code() == 200) { + if (fcr.code() == 200) { hgen.p("Current Password validated").br(); go = true; } else { @@ -156,13 +156,13 @@ public class PassChangeAction extends Page { tt.done(); } } - if(go) { + if (go) { TimeTaken tt = trans.start("AAF Change Password",Env.REMOTE); try { // Change over Cred to reset mode cred.setPassword(password); String start = trans.get(startDate, null); - if(start!=null) { + if (start!=null) { try { cred.setStart(Chrono.timeStamp(Chrono.dateOnlyFmt.parse(start))); } catch (ParseException e) { @@ -171,7 +171,7 @@ public class PassChangeAction extends Page { } Future<CredRequest> fcr = gui.clientAsUser(trans.getUserPrincipal()).create("/authn/cred",gui.getDF(CredRequest.class),cred); - if(fcr.get(AAFcli.timeout())) { + if (fcr.get(AAFcli.timeout())) { // Do Remote Call hgen.p("New Password has been added. The previous one is still valid until Expiration."); fail = false; @@ -194,10 +194,10 @@ public class PassChangeAction extends Page { } hgen.br(); - if(fail) { + if (fail) { hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+PassChangeForm.HREF+"?id="+id).text("Try again").end(); } else { - if(ns==null) { + if (ns==null) { hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+Home.HREF).text("Back").end(); } else { hgen.incr(HTMLGen.A,true,"class=greenbutton","href="+CredDetail.HREF+"?id="+id+"&ns="+ns).text("Back").end(); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java index dcaed047..499c02dd 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassChangeForm.java @@ -81,14 +81,14 @@ public class PassChangeForm extends Page { public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { String incomingID= trans.get(sID, ""); boolean skipCurrent = false; - if(incomingID.length()>0) { + if (incomingID.length()>0) { try { Organization org = OrganizationFactory.obtain(trans.env(), incomingID); - if(org==null) { + if (org==null) { hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: There is no supported company for ").text(incomingID).end(); } else { Identity user = org.getIdentity(trans, incomingID); - if(user==null) { + if (user==null) { int at = incomingID.indexOf('@'); hgen.incr(HTMLGen.H4,"style=color:red;").text("Error: You are not the sponsor of '").text(at<0?incomingID:incomingID.substring(0,at)) .text("' defined at ").text(org.getName()).end(); @@ -97,23 +97,23 @@ public class PassChangeForm extends Page { // Owners/or the IDs themselves are allowed to reset password without previous one skipCurrent=skipCurrent(trans, user); - if(!skipCurrent) { + if (!skipCurrent) { final String id = incomingID; try { skipCurrent=gui.clientAsUser(trans.getUserPrincipal(), new Retryable<Boolean>() { @Override public Boolean code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Users> fc = client.read("/authn/creds/id/"+id,gui.getDF(Users.class)); - if(fc.get(AAFcli.timeout())) { + if (fc.get(AAFcli.timeout())) { GregorianCalendar now = new GregorianCalendar(); - for(aaf.v2_0.Users.User u : fc.value.getUser()) { - if(u.getType()<10 && u.getType()>=1 && u.getExpires().toGregorianCalendar().after(now)) { + for (aaf.v2_0.Users.User u : fc.value.getUser()) { + if (u.getType()<10 && u.getType()>=1 && u.getExpires().toGregorianCalendar().after(now)) { return false; // an existing, non expired, password type exists } } return true; // no existing, no expired password } else { - if(fc.code()==404) { // not found... + if (fc.code()==404) { // not found... return true; } else { trans.error().log(gui.aafCon.readableErrMsg(fc)); @@ -135,10 +135,10 @@ public class PassChangeForm extends Page { } hgen.input(fields[0],"ID*",true,"value="+incomingID,(incomingID.length()==0?"":"readonly")); - if(!skipCurrent) { + if (!skipCurrent) { hgen.input(fields[1],"Current Password*",true,"type=password"); } - if(skipCurrent) { + if (skipCurrent) { hgen.input(fields[1],"",false,"type=hidden", "value=").end(); } @@ -166,10 +166,10 @@ public class PassChangeForm extends Page { public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { try { Organization org = OrganizationFactory.obtain(trans.env(),trans.getUserPrincipal().getName()); - if(org!=null) { + if (org!=null) { hgen.incr(HTMLGen.H4).text("Password Rules for ").text(org.getName()).end() .incr(HTMLGen.UL); - for(String line : org.getPasswordRules()) { + for (String line : org.getPasswordRules()) { hgen.leaf(HTMLGen.LI).text(line).end(); } hgen.end(); @@ -187,14 +187,14 @@ public class PassChangeForm extends Page { // Package on Purpose static boolean skipCurrent(AuthzTrans trans, Identity user) throws OrganizationException { - if(user!=null) { + if (user!=null) { // Should this be an abstractable Policy? String tuser = trans.user(); - if(user.fullID().equals(trans.user())) { + if (user.fullID().equals(trans.user())) { return true; } else { Identity manager = user.responsibleTo(); - if(tuser.equals(user.fullID()) || manager.isFound()) { + if (tuser.equals(user.fullID()) || manager.isFound()) { return true; } } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java index 2ad7ca5e..f66e8bcb 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PassDeleteAction.java @@ -65,13 +65,13 @@ public class PassDeleteAction extends Page { @Override public String code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<CredRequest> fcr = client.delete("/authn/cred", gui.getDF(CredRequest.class),cr); - if(!fcr.get(AAFcli.timeout())) { + if (!fcr.get(AAFcli.timeout())) { return gui.aafCon.readableErrMsg(fcr); } return null; } }); - if(err==null) { + if (err==null) { hgen.p("Password " + cr.getId() + ", " + cr.getEntry() + " is Deleted"); } else { hgen.p(err); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java index a4970e3c..22c3fd4d 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PendingRequestsShow.java @@ -125,10 +125,10 @@ public class PendingRequestsShow extends Page { TimeTaken tt = trans.start("AAF Get Approvals by User",Env.REMOTE); try { Future<Approvals> fa = client.read("/authz/approval/user/"+trans.user(),gui.getDF(Approvals.class)); - if(fa.get(5000)) { + if (fa.get(5000)) { tt.done(); tt = trans.start("Load Data", Env.SUB); - if(fa.value!=null) { + if (fa.value!=null) { List<Approval> approvals = fa.value.getApprovals(); Collections.sort(approvals, new Comparator<Approval>() { @Override @@ -140,7 +140,7 @@ public class PendingRequestsShow extends Page { }); String prevTicket = null; - for(Approval a : approvals) { + for (Approval a : approvals) { String approver = a.getApprover(); String approverShort = approver.substring(0,approver.indexOf('@')); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java index 750f725f..7d31d0e4 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermDetail.java @@ -92,7 +92,7 @@ public class PermDetail extends Page { .permInstance(pInstance) .permAction(pAction); - if(v.err()) { + if (v.err()) { trans.warn().printf("Error in PermDetail Request: %s", v.errs()); return Cells.EMPTY; } @@ -108,17 +108,17 @@ public class PermDetail extends Page { try { Future<Perms> fp= client.read("/authz/perms/"+pType + '/' + pInstance + '/' + pAction,gui.getDF(Perms.class)); - if(fp.get(AAF_GUI.TIMEOUT)) { + if (fp.get(AAF_GUI.TIMEOUT)) { tt.done(); tt = trans.start("Load Data", Env.SUB); List<Perm> ps = fp.value.getPerm(); - if(!ps.isEmpty()) { + if (!ps.isEmpty()) { Perm perm = fp.value.getPerm().get(0); String desc = (perm.getDescription()!=null?perm.getDescription():BLANK); rv.add(new AbsCell[]{new TextCell("Description:"),new TextCell(desc)}); boolean first=true; - for(String r : perm.getRoles()) { - if(first){ + for (String r : perm.getRoles()) { + if (first){ first=false; rv.add(new AbsCell[] { new TextCell("Associated Roles:"), diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java index 8839ed81..9d53c535 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantAction.java @@ -94,7 +94,7 @@ public class PermGrantAction extends Page { grantReq ); - if(fgrant.get(5000)) { + if (fgrant.get(5000)) { hgen.p("Permission has been granted to role."); fail = false; } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java index 1ecf3d30..71958060 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermGrantForm.java @@ -108,7 +108,7 @@ public class PermGrantForm extends Page { hgen .incr("option", "value=").text("Other").end() .end(selectRow); - if(roleValue==null) { + if (roleValue==null) { hgen.input(fields[3],"Role", true, "placeholder=or type a role here"); } else { hgen.input(fields[3],"Role",true, "value="+roleValue); @@ -133,7 +133,7 @@ public class PermGrantForm extends Page { TimeTaken tt = trans.start("AAF get my roles",Env.REMOTE); try { Future<Roles> fr = client.read("/authz/roles/user/"+trans.user(),gui.getDF(Roles.class)); - if(fr.get(5000)) { + if (fr.get(5000)) { tt.done(); tt = trans.start("Load Data", Env.SUB); if (fr.value != null) for (Role r : fr.value.getRole()) { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java index f3464bf9..bbaf419f 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermHistory.java @@ -171,7 +171,7 @@ public class PermHistory extends Page { final String oName = trans.get(sType,null); final String oDates = trans.get(sDates,null); - if(oName==null) { + if (oName==null) { return Cells.EMPTY; } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java index 22ba95b9..7dff0815 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/PermsShow.java @@ -84,11 +84,11 @@ public class PermsShow extends Page { @Override public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Perms> fp = client.read("/authz/perms/user/"+trans.user(), gui.getDF(Perms.class)); - if(fp.get(5000)) { + if (fp.get(5000)) { TimeTaken ttld = trans.start("Load Data", Env.SUB); try { - if(fp.value!=null) { - for(Perm p : fp.value.getPerm()) { + if (fp.value!=null) { + for (Perm p : fp.value.getPerm()) { AbsCell[] sa = new AbsCell[] { new RefCell(p.getType(),PermDetail.HREF +"?type="+p.getType() diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java index 0d0d03ad..090b6e3c 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RequestDetail.java @@ -80,7 +80,7 @@ public class RequestDetail extends Page { public Cells get(final AuthzTrans trans, final AAF_GUI gui) { Cells rv=Cells.EMPTY; final String ticket = trans.get(sTicket, null); - if(ticket!=null) { + if (ticket!=null) { try { rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable<Cells>() { @Override @@ -93,7 +93,7 @@ public class RequestDetail extends Page { gui.getDF(Approvals.class) ); - if(fa.get(AAF_GUI.TIMEOUT)) { + if (fa.get(AAF_GUI.TIMEOUT)) { if (!trans.user().equals(fa.value.getApprovals().get(0).getUser())) { return Cells.EMPTY; } diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java index d5a89c2c..bfc258bc 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetail.java @@ -107,7 +107,7 @@ public class RoleDetail extends Page { final String pRole = trans.get(sRoleName, null); Validator v = new Validator(); v.role(pRole); - if(v.err()) { + if (v.err()) { trans.warn().printf("Error in PermDetail Request: %s", v.errs()); return; } @@ -121,9 +121,9 @@ public class RoleDetail extends Page { try { Future<Roles> fr = client.read("/authz/roles/"+pRole+"?ns",gui.getDF(Roles.class)); Future<UserRoles> fur = client.read("/authz/userRoles/role/"+pRole,gui.getDF(UserRoles.class)); - if(fr.get(AAF_GUI.TIMEOUT)) { + if (fr.get(AAF_GUI.TIMEOUT)) { List<Role> roles = fr.value.getRole(); - if(!roles.isEmpty()) { + if (!roles.isEmpty()) { Role role = fr.value.getRole().get(0); trans.put(sRole, role); Boolean mayWrite = trans.fish(new AAFPermission(role.getNs(),ACCESS,":role:"+role.getName(),"write")); @@ -131,7 +131,7 @@ public class RoleDetail extends Page { Boolean mayApprove = trans.fish(new AAFPermission(role.getNs(),ACCESS,":role:"+role.getName(),"approve")); trans.put(sMayApprove, mayApprove); - if(mayWrite || mayApprove) { + if (mayWrite || mayApprove) { Mark js = new Mark(); Mark fn = new Mark(); hgen.js(js) @@ -160,7 +160,7 @@ public class RoleDetail extends Page { return false; } - if(fur.get(AAF_GUI.TIMEOUT)) { + if (fur.get(AAF_GUI.TIMEOUT)) { trans.put(sUserRole, fur.value.getUserRole()); } else { trans.error().printf("Error calling AAF for UserRoles in GUI, Role Detail %d: %s",fr.code(),fr.body()); @@ -184,7 +184,7 @@ public class RoleDetail extends Page { final Role role = trans.get(sRole,null); ArrayList<AbsCell[]> rv = new ArrayList<>(); - if(role!=null) { + if (role!=null) { boolean mayWrite = trans.get(sMayWrite, false); boolean mayApprove = trans.get(sMayApprove, false); @@ -192,7 +192,7 @@ public class RoleDetail extends Page { rv.add(new AbsCell[]{ new TextCell("Role:","width=45%"), new TextCell(pRole)}); - if(mayWrite) { + if (mayWrite) { rv.add(new AbsCell[]{ new TextCell("Description:","width=45%"), new TextInputCell("description","textInput",desc,"id=descText","onkeypress=touchedDesc()"), @@ -211,9 +211,9 @@ public class RoleDetail extends Page { boolean protectedRole = role.getName().endsWith(".owner") || role.getName().endsWith(".admin"); boolean first = true; - for(Pkey r : role.getPerms()) { + for (Pkey r : role.getPerms()) { String key=r.getType() + '|' + r.getInstance() + '|' + r.getAction(); - if(mayWrite) { + if (mayWrite) { rv.add(new AbsCell[] { AbsCell.Null, protectedRole && r.getType().endsWith(".access") @@ -223,7 +223,7 @@ public class RoleDetail extends Page { new TextCell(key) }); } else { - if(first) { + if (first) { rv.add(new AbsCell[] { new TextCell("Associated Permissions:","width=45%"), new TextCell(key) @@ -238,7 +238,7 @@ public class RoleDetail extends Page { } } - if(mayApprove) { + if (mayApprove) { rv.add(AbsCell.HLINE); // @@ -249,8 +249,8 @@ public class RoleDetail extends Page { }); List<UserRole> userroles = trans.get(sUserRole,null); - if(userroles!=null) { - for(UserRole ur : userroles) { + if (userroles!=null) { + for (UserRole ur : userroles) { String tag = "userrole"; rv.add(new AbsCell[] { @@ -284,10 +284,10 @@ public class RoleDetail extends Page { @Override public void postfix(AAF_GUI state, AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) { final Mark mark = trans.get(sMark, null); - if(mark!=null) { + if (mark!=null) { hgen.tagOnly("input", "type=submit", "value=Submit"); final String pNS = trans.get(sNS, null); - if(pNS!=null && pNS.length()>0) { + if (pNS!=null && pNS.length()>0) { hgen.leaf(mark,HTMLGen.A,"href="+NsDetail.HREF+"?ns="+pNS,"class=greenbutton").text("Back").end(mark); } hgen.end(mark); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java index 1f00d955..fb64cd6e 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleDetailAction.java @@ -67,7 +67,7 @@ public class RoleDetailAction extends Page { public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { final HttpServletRequest req = trans.get(sReq, null); final String role = getSingleParam(req,"role"); - if(role==null) { + if (role==null) { hgen.text("Parameter 'role' is required").end(); } else { // Run Validations @@ -79,14 +79,14 @@ public class RoleDetailAction extends Page { List<TypedFuture> ltf = new ArrayList<>(); String text; Map<String, String[]> pm = (Map<String, String[]>)req.getParameterMap(); - for(final Entry<String, String[]> es : pm.entrySet()) { - for(final String v : es.getValue()) { + for (final Entry<String, String[]> es : pm.entrySet()) { + for (final String v : es.getValue()) { TimeTaken tt = null; try { switch(es.getKey()) { case "desc": // Check box set String desc = getSingleParam(req, "description"); - if(desc!=null) { + if (desc!=null) { text = "Setting Description on " + role + " to " + desc; tt = trans.start(text, Env.REMOTE); RoleRequest rr = new RoleRequest(); @@ -102,7 +102,7 @@ public class RoleDetailAction extends Page { text = "Ungranting Permission '" + v + "' from '" + role + '\''; tt = trans.start(text, Env.REMOTE); String[] pf = Split.splitTrim('|', v); - if(pf.length==3) { + if (pf.length==3) { Pkey perm = new Pkey(); perm.setType(pf[0]); perm.setInstance(pf[1]); @@ -135,7 +135,7 @@ public class RoleDetailAction extends Page { // System.out.println(es.getKey() + "=" + v); } } finally { - if(tt!=null) { + if (tt!=null) { tt.done(); tt=null; } @@ -143,11 +143,11 @@ public class RoleDetailAction extends Page { } } - if(ltf.isEmpty()) { + if (ltf.isEmpty()) { hgen.p("No Changes"); } else { - for(TypedFuture tf : ltf) { - if(tf.future.get(5000)) { + for (TypedFuture tf : ltf) { + if (tf.future.get(5000)) { hgen.p("<font color=\"green\"><i>Success</i>:</font> " + tf.text); } else { // Note: if handling of special Error codes is required, use diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java index 234b82c2..fdf6f9e3 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RoleHistory.java @@ -165,7 +165,7 @@ public class RoleHistory extends Page { final String oDates = trans.get(dates,null); Cells rv = Cells.EMPTY; - if(oName!=null) { + if (oName!=null) { try { rv = gui.clientAsUser(trans.getUserPrincipal(), new Retryable<Cells>() { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java index ffa8e3c2..414c4161 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/RolesShow.java @@ -95,7 +95,7 @@ public class RolesShow extends Page { try { Future<UserRoles> fur = client.read("/authz/userRoles/user/"+trans.user(),gui.getDF(UserRoles.class)); if (fur.get(5000) && fur.value != null) for (UserRole u : fur.value.getUserRole()) { - if(u.getExpires().compare(Chrono.timeStamp()) < 0) { + if (u.getExpires().compare(Chrono.timeStamp()) < 0) { AbsCell[] sa = new AbsCell[] { new TextCell(u.getRole() + "*", CLASS_EXPIRED), new TextCell(new SimpleDateFormat(DATE_TIME_FORMAT).format(u.getExpires().toGregorianCalendar().getTime()),CLASS_EXPIRED), diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java index 04e0e845..ed4c19d9 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleExtend.java @@ -68,7 +68,7 @@ public class UserRoleExtend extends Page { @Override public Void code(Rcli<?> client)throws CadiException, ConnectException, APIException { Future<Void> fv = client.update("/authz/userRole/extend/"+user+"/"+role+"?request=true"); - if(fv.get(5000)) { + if (fv.get(5000)) { // not sure if we'll ever hit this hgen.p("Extended User ["+ user+"] in Role [" +role+"]"); } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java index 73aa3e9f..11126f89 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/UserRoleRemove.java @@ -70,7 +70,7 @@ public class UserRoleRemove extends Page { Future<Void> fv = client.delete( "/authz/userRole/"+user+"/"+role+"?request=true",Void.class); - if(fv.get(5000)) { + if (fv.get(5000)) { // not sure if we'll ever hit this hgen.p("User ["+ user+"] Removed from Role [" +role+"]"); } else { diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java index 5fc82140..759d87f4 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/RefCell.java @@ -36,7 +36,7 @@ public class RefCell extends AbsCell { public RefCell(String name, String href, boolean newWindow, String... attributes) { this.name = name; - if(newWindow) { + if (newWindow) { str = new String[attributes.length+2]; str[attributes.length]="target=_blank"; } else { diff --git a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java index 34371a1f..9190c665 100644 --- a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java +++ b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/AAF_Hello.java @@ -70,7 +70,7 @@ public class AAF_Hello extends AbsService<AuthzEnv,AuthzTrans> { aafAuthn = aafCon().newAuthn(aafLurPerm); String aaf_env = env.getProperty(Config.AAF_ENV); - if(aaf_env==null) { + if (aaf_env==null) { throw new APIException("aaf_env needs to be set"); } diff --git a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java index 234dfe14..7fef0ba2 100644 --- a/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java +++ b/auth/auth-hello/src/main/java/org/onap/aaf/auth/hello/API_Hello.java @@ -68,12 +68,12 @@ public class API_Hello { ServletOutputStream os = resp.getOutputStream(); os.print("Hello AAF "); String perm = pathParam(req, "perm"); - if(perm!=null && perm.length()>0) { + if (perm!=null && perm.length()>0) { os.print('('); os.print(req.getUserPrincipal().getName()); TimeTaken tt = trans.start("Authorize perm", Env.REMOTE); try { - if(req.isUserInRole(perm)) { + if (req.isUserInRole(perm)) { os.print(" has "); } else { os.print(" does not have "); @@ -103,12 +103,12 @@ public class API_Hello { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder sb = new StringBuilder(); - while(br.ready()) { + while (br.ready()) { sb.append(br.readLine()); } String content = sb.toString(); trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content); - if(content.startsWith("{") && content.endsWith("}")) { + if (content.startsWith("{") && content.endsWith("}")) { resp.setStatus(201 /* OK */); } else { resp.getOutputStream().write(NOT_JSON); @@ -130,7 +130,7 @@ public class API_Hello { sb.append('"'); String perm = pathParam(req, "perm"); trans.info().printf("Read request from %s: %s\n", pathParam(req, ":id"),perm); - if(perm!=null && perm.length()>0) { + if (perm!=null && perm.length()>0) { TimeTaken tt = trans.start("Authorize perm", Env.REMOTE); try { sb.append(",\"validation\": { \"permission\" : \""); @@ -157,12 +157,12 @@ public class API_Hello { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder sb = new StringBuilder(); - while(br.ready()) { + while (br.ready()) { sb.append(br.readLine()); } String content = sb.toString(); trans.info().printf("Content from %s: %s\n", pathParam(req, ":id"),content); - if(content.startsWith("{") && content.endsWith("}")) { + if (content.startsWith("{") && content.endsWith("}")) { resp.setStatus(200 /* OK */); resp.getOutputStream().print(content); } else { diff --git a/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java b/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java index f41826d9..e85431d3 100644 --- a/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java +++ b/auth/auth-hello/src/test/java/org/onap/aaf/auth/hello/test/HelloTester.java @@ -46,7 +46,7 @@ public class HelloTester { try { Define.set(access); String uriPrefix = access.getProperty("locatorURI",null); - if(uriPrefix==null) { + if (uriPrefix==null) { System.out.println("You must add \"locatorURI=<uri>\" to the command line or VM_Args"); } else { SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(access, HttpURLConnection.class); @@ -57,12 +57,12 @@ public class HelloTester { String pathinfo = "/hello"; final int iterations = Integer.parseInt(access.getProperty("iterations","5")); System.out.println("Calling " + loc + " with Path " + pathinfo + ' ' + iterations + " time" + (iterations==1?"":"s")); - for(int i=0;i<iterations;++i) { + for (int i=0;i<iterations;++i) { aafcon.best(new Retryable<Void> () { @Override public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<String> fs = client.read("/hello","text/plain"); - if(fs.get(5000)) { + if (fs.get(5000)) { System.out.print(fs.body()); } else { System.err.println("Ooops, missed one: " + fs.code() + ": " + fs.body()); diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java index 545b6b47..bd44dfce 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/AAF_Locate.java @@ -120,7 +120,7 @@ public class AAF_Locate extends AbsService<AuthzEnv, AuthzTrans> { facade_1_1_XML = LocateFacadeFactory.v1_1(env,this,trans,Data.TYPE.XML); synchronized(env) { - if(cacheUser == null) { + if (cacheUser == null) { cacheUser = Cache.obtain(USER_PERMS); Cache.startCleansing(env, USER_PERMS); } @@ -163,7 +163,7 @@ public class AAF_Locate extends AbsService<AuthzEnv, AuthzTrans> { String version = "1.0"; // Get Correct API Class from Mapper Class<?> respCls = facade.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + if (respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); // setup Application API HTML ContentTypes for JSON and Route String application = applicationJSON(respCls, version); route(env,meth,path,code,application,"application/json;version="+version,"*/*","*"); @@ -186,7 +186,7 @@ public class AAF_Locate extends AbsService<AuthzEnv, AuthzTrans> { @Override protected AAFConHttp _newAAFConHttp() throws CadiException { try { - if(dal==null) { + if (dal==null) { dal = AbsAAFLocator.create(aaf_service_name,Config.AAF_DEFAULT_VERSION); } // utilize pre-constructed DirectAAFLocator @@ -197,7 +197,7 @@ public class AAF_Locate extends AbsService<AuthzEnv, AuthzTrans> { } public Locator<URI> getGUILocator() throws LocatorException { - if(gui_locator==null) { + if (gui_locator==null) { gui_locator = AbsAAFLocator.create(aaf_gui_name,Config.AAF_DEFAULT_VERSION); } return gui_locator; @@ -228,7 +228,7 @@ public class AAF_Locate extends AbsService<AuthzEnv, AuthzTrans> { @Override public void destroy() { Cache.stopTimer(); - if(cluster!=null) { + if (cluster!=null) { cluster.close(); } super.destroy(); diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java index c5239a5a..30258d80 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/BasicAuthCode.java @@ -45,7 +45,7 @@ public class BasicAuthCode extends LocateCode { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Principal p = trans.getUserPrincipal(); - if(p == null) { + if (p == null) { trans.error().log("Transaction not Authenticated... no Principal"); } else if (p instanceof BasicPrincipal) { // the idea is that if call is made with this credential, and it's a BasicPrincipal, it's ok @@ -55,12 +55,12 @@ public class BasicAuthCode extends LocateCode { } else if (p instanceof X509Principal) { // Since X509Principal has priority, BasicAuth Info might be there, but not validated. String ba; - if((ba=req.getHeader("Authorization"))!=null && ba.startsWith("Basic ")) { + if ((ba=req.getHeader("Authorization"))!=null && ba.startsWith("Basic ")) { ba = Symm.base64noSplit.decode(ba.substring(6)); int colon = ba.indexOf(':'); - if(colon>=0) { + if (colon>=0) { String err; - if((err=authn.validate(ba.substring(0, colon), ba.substring(colon+1),trans))==null) { + if ((err=authn.validate(ba.substring(0, colon), ba.substring(colon+1),trans))==null) { resp.setStatus(HttpStatus.OK_200); } else { trans.audit().log(ba.substring(0,colon),": ",err); diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java index 85cee82f..b5ab4351 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_AAFAccess.java @@ -78,7 +78,7 @@ public class API_AAFAccess { try { final String accept = req.getHeader("ACCEPT"); final String user = pathParam(req,":user"); - if(!user.contains("@")) { + if (!user.contains("@")) { context.error(trans,resp,Result.ERR_BadData,"User [%s] must be fully qualified with domain",user); return; } @@ -91,14 +91,14 @@ public class API_AAFAccess { tt2.done(); } - if(d==null || d.data.isEmpty()) { + if (d==null || d.data.isEmpty()) { tt2 = trans.start("AAF Service Call",Env.REMOTE); try { gwAPI.clientAsUser(trans.getUserPrincipal(), new Retryable<Void>() { @Override public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<String> fp = client.read("/authz/perms/user/"+user,accept); - if(fp.get(5000)) { + if (fp.get(5000)) { gwAPI.cacheUser.put(key, new Dated(new User(fp.code(),fp.body()),gwAPI.expireIn)); resp.setStatus(HttpStatus.OK_200); ServletOutputStream sos; @@ -159,7 +159,7 @@ public class API_AAFAccess { pathParam(req,":instance"), pathParam(req,":action")))); resp.setStatus(HttpStatus.OK_200); - } catch(Exception e) { + } catch (Exception e) { context.error(trans, resp, Result.ERR_General, e.getMessage()); } } @@ -258,14 +258,14 @@ public class API_AAFAccess { private static void redirect(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp, LocateFacade context, Locator<URI> loc, String path) throws IOException { try { - if(loc.hasItems()) { + if (loc.hasItems()) { Item item = loc.best(); URI uri = loc.get(item); StringBuilder redirectURL = new StringBuilder(uri.toString()); redirectURL.append('/'); redirectURL.append(path); String str = req.getQueryString(); - if(str!=null) { + if (str!=null) { redirectURL.append('?'); redirectURL.append(str); } diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java index 7ff1fceb..88fcc079 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Find.java @@ -62,7 +62,7 @@ public class API_Find { String service = pathParam(req, ":service"); String version = pathParam(req, ":version"); String other = pathParam(req, ":other"); - if(service.indexOf(':')>=0) { + if (service.indexOf(':')>=0) { String split[] = Split.split(':', service); switch(split.length) { case 3: diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java index 8bdf479f..19c09ff0 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/api/API_Proxy.java @@ -62,7 +62,7 @@ public class API_Proxy { public static void init(final AAF_Locate gwAPI, LocateFacade facade) throws Exception { String aafurl = gwAPI.access.getProperty(Config.AAF_URL,null); - if(aafurl==null) { + if (aafurl==null) { } else { //////// // Transferring APIs @@ -73,7 +73,7 @@ public class API_Proxy { gwAPI.routeAll(HttpMethods.GET,"/proxy/:path*",API.VOID,new LocateCode(facade,"Proxy GET", true) { @Override public void handle(final AuthzTrans trans, final HttpServletRequest req, final HttpServletResponse resp) throws Exception { - if("/proxy/authn/basicAuth".equals(req.getPathInfo()) && !(req.getUserPrincipal() instanceof OAuth2Principal)) { + if ("/proxy/authn/basicAuth".equals(req.getPathInfo()) && !(req.getUserPrincipal() instanceof OAuth2Principal)) { bac.handle(trans, req, resp); } else { TimeTaken tt = trans.start("Forward to AAF Service", Env.REMOTE); diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java index f41fcd91..fc73047c 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/facade/LocateFacadeImpl.java @@ -119,7 +119,7 @@ public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIGURA public void error(AuthzTrans trans, HttpServletResponse response, Result<?> result) { String msg = result.details==null?"":result.details.trim(); String[] detail; - if(result.variables==null) { + if (result.variables==null) { detail = new String[1]; } else { int l = result.variables.length; @@ -132,7 +132,7 @@ public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIGURA @Override public void error(AuthzTrans trans, HttpServletResponse response, int status, String msg, String ... _detail) { String[] detail = _detail; - if(detail.length==0) { + if (detail.length==0) { detail=new String[1]; } boolean hidemsg = false; @@ -199,7 +199,7 @@ public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIGURA "] " + holder.toString(), Env.ALWAYS); - if(hidemsg) { + if (hidemsg) { holder.setLength(0); em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); } @@ -221,25 +221,25 @@ public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIGURA Api api = new Api(); Api.Route ar; Method[] meths = LocateServiceImpl.class.getDeclaredMethods(); - for(RouteReport rr : rservlet.routeReport()) { + for (RouteReport rr : rservlet.routeReport()) { api.getRoute().add(ar = new Api.Route()); ar.setMeth(rr.meth.name()); ar.setPath(rr.path); ar.setDesc(rr.desc); ar.getContentType().addAll(rr.contextTypes); - for(Method m : meths) { + for (Method m : meths) { ApiDoc ad; - if((ad = m.getAnnotation(ApiDoc.class))!=null && + if ((ad = m.getAnnotation(ApiDoc.class))!=null && rr.meth.equals(ad.method()) && rr.path.equals(ad.path())) { - for(String param : ad.params()) { + for (String param : ad.params()) { ar.getParam().add(param); } - for(String text : ad.text()) { + for (String text : ad.text()) { ar.getComments().add(text); } ar.setExpected(ad.expectedCode()); - for(int ec : ad.errorCodes()) { + for (int ec : ad.errorCodes()) { ar.getExplicitErr().add(ec); } } @@ -289,20 +289,20 @@ public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIGURA String output=null; long temp=System.currentTimeMillis(); synchronized(LOCK) { - if(cacheClear<temp) { + if (cacheClear<temp) { epsCache.clear(); cacheClear = temp+1000*60*2; // 2 mins standard cache clear } else { output = epsCache.get(key); - if("{}".equals(output) && emptyCheck<temp) { + if ("{}".equals(output) && emptyCheck<temp) { output = null; emptyCheck = temp+5000; // 5 second check } } } - if(output==null) { + if (output==null) { Result<ENDPOINTS> reps = this.service.getEndPoints(trans,service,version,other); - if(reps.notOK()) { + if (reps.notOK()) { return Result.err(reps); } else { output = epDF.newData(trans).load(reps.value).asString(); @@ -334,7 +334,7 @@ public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIGURA try { RosettaData<MGMT_ENDPOINTS> data = mepDF.newData().load(req.getInputStream()); rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,PUT_MGMT_ENDPOINTS); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -370,7 +370,7 @@ public abstract class LocateFacadeImpl<IN,OUT,ENDPOINTS,MGMT_ENDPOINTS,CONFIGURA try { RosettaData<MGMT_ENDPOINTS> data = mepDF.newData().load(req.getInputStream()); rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,DELETE_MGMT_ENDPOINTS); return Result.err(Status.ERR_BadData,"Invalid Input"); diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java index d2eeb632..0d50f5d2 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/mapper/Mapper_1_1.java @@ -75,7 +75,7 @@ public class Mapper_1_1 implements Mapper<InRequest,Out,Endpoints,MgmtEndpoints, err.setMessageId(msgID); // AT&T Restful Error Format requires numbers "%" placements err.setText(Vars.convert(holder, text, var)); - for(String s : var) { + for (String s : var) { err.getVariables().add(s); } return err; @@ -86,25 +86,25 @@ public class Mapper_1_1 implements Mapper<InRequest,Out,Endpoints,MgmtEndpoints, */ @Override public Result<Endpoints> endpoints(Result<List<Data>> resultDB, String version, String other) { - if(resultDB.notOK()) { + if (resultDB.notOK()) { return Result.err(resultDB); } int major=-1, minor=-1, patch=-1, pkg=-1; - if(version!=null) { + if (version!=null) { try { String[] v = Split.split('.',version); - if(v.length>0) {major = Integer.parseInt(v[0]);} - if(v.length>1) {minor = Integer.parseInt(v[1]);} - if(v.length>2) {patch = Integer.parseInt(v[2]);} - if(v.length>3) {pkg = Integer.parseInt(v[3]);} + if (v.length>0) {major = Integer.parseInt(v[0]);} + if (v.length>1) {minor = Integer.parseInt(v[1]);} + if (v.length>2) {patch = Integer.parseInt(v[2]);} + if (v.length>3) {pkg = Integer.parseInt(v[3]);} } catch (NumberFormatException e) { return Result.err(Result.ERR_BadData,"Invalid Version String " + version); } } Endpoints eps = new Endpoints(); List<Endpoint> leps = eps.getEndpoint(); - for(Data d : resultDB.value) { - if((major<0 || major==d.major) && + for (Data d : resultDB.value) { + if ((major<0 || major==d.major) && (minor<0 || minor<=d.minor) && (patch<0 || patch==d.patch) && (pkg<0 || pkg ==d.pkg)) { @@ -119,7 +119,7 @@ public class Mapper_1_1 implements Mapper<InRequest,Out,Endpoints,MgmtEndpoints, ep.setLatitude(d.latitude); ep.setLongitude(d.longitude); ep.setProtocol(d.protocol); - for(String s : d.subprotocol(false)) { + for (String s : d.subprotocol(false)) { ep.getSubprotocol().add(s); } leps.add(ep); @@ -144,7 +144,7 @@ public class Mapper_1_1 implements Mapper<InRequest,Out,Endpoints,MgmtEndpoints, data.latitude = me.getLatitude(); data.longitude = me.getLongitude(); data.protocol = me.getProtocol(); - for(String s : me.getSubprotocol()) { + for (String s : me.getSubprotocol()) { data.subprotocol(true).add(s); } return data; diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java index d0aae466..6d96ded3 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/service/LocateServiceImpl.java @@ -68,28 +68,28 @@ public class LocateServiceImpl<IN,OUT,ERROR> @Override public Result<Void> putMgmtEndPoints(AuthzTrans trans, MgmtEndpoints meps) { LocateValidator v = new LocateValidator().mgmt_endpoints(meps, false); - if(v.err()) { + if (v.err()) { return Result.err(Result.ERR_BadData,v.errs()); } int count = 0; - for(MgmtEndpoint me : meps.getMgmtEndpoint()) { - if(permToRegister) { + for (MgmtEndpoint me : meps.getMgmtEndpoint()) { + if (permToRegister) { int dot = me.getName().lastIndexOf('.'); // Note: Validator checks for NS for getName() AAFPermission p = new AAFPermission(me.getName().substring(0,dot),"locator",me.getName(),"write"); - if(trans.fish(p)) { + if (trans.fish(p)) { LocateDAO.Data data = mapper.locateData(me); locateDAO.update(trans, data, true); ++count; } else { return Result.err(Result.ERR_Denied,"May not register service (needs " + p.getKey() + ')'); } - } else { //TODO if(MechID is part of Namespace) { + } else { //TODO if (MechID is part of Namespace) { LocateDAO.Data data = mapper.locateData(me); locateDAO.update(trans, data, true); ++count; } } - if(count>0) { + if (count>0) { return Result.ok(); } else { return Result.err(Result.ERR_NotFound, "No endpoints found"); @@ -102,14 +102,14 @@ public class LocateServiceImpl<IN,OUT,ERROR> @Override public Result<Void> removeMgmtEndPoints(AuthzTrans trans, MgmtEndpoints meps) { LocateValidator v = new LocateValidator().mgmt_endpoint_key(meps); - if(v.err()) { + if (v.err()) { return Result.err(Result.ERR_BadData,v.errs()); } int count = 0; - for(MgmtEndpoint me : meps.getMgmtEndpoint()) { + for (MgmtEndpoint me : meps.getMgmtEndpoint()) { int dot = me.getName().lastIndexOf('.'); // Note: Validator checks for NS for getName() AAFPermission p = new AAFPermission(me.getName().substring(0,dot),"locator",me.getHostname(),"write"); - if(trans.fish(p)) { + if (trans.fish(p)) { LocateDAO.Data data = mapper.locateData(me); data.port_key = UUID.randomUUID(); locateDAO.delete(trans, data, false); @@ -118,7 +118,7 @@ public class LocateServiceImpl<IN,OUT,ERROR> return Result.err(Result.ERR_Denied,"May not register service (needs " + p.getKey() + ')'); } } - if(count>0) { + if (count>0) { return Result.ok(); } else { return Result.err(Result.ERR_NotFound, "No endpoints found"); @@ -136,8 +136,8 @@ public class LocateServiceImpl<IN,OUT,ERROR> c.setName(type); Props p; - if(dr.isOKhasData()) { - for(ConfigDAO.Data data : dr.value) { + if (dr.isOKhasData()) { + for (ConfigDAO.Data data : dr.value) { p = new Props(); p.setTag(data.tag); p.setValue(data.value); diff --git a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java index 6dd3d92a..4f3884d2 100644 --- a/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java +++ b/auth/auth-locate/src/main/java/org/onap/aaf/auth/locate/validation/LocateValidator.java @@ -40,13 +40,13 @@ import locate.v1_0.MgmtEndpoints; */ public class LocateValidator extends Validator { private LocateValidator endpoint_key(Endpoint e) { - if(e==null) { + if (e==null) { msg("Endpoint Data is null."); } else { nullOrBlank("Endpoint Name", e.getName()); - if(e.getName()!=null) { + if (e.getName()!=null) { int idx = e.getName().indexOf('.'); - if(idx<=0) { + if (idx<=0) { msg("Endpoint Name must prefixed by Namespace"); } } @@ -59,7 +59,7 @@ public class LocateValidator extends Validator { public LocateValidator endpoint(Endpoint e) { endpoint_key(e); - if(e!=null) { + if (e!=null) { intRange("Endpoint Major Version",e.getMajor(),0,2000); intRange("Endpoint Minor Version",e.getMinor(),0,2000); intRange("Endpoint Patch Version",e.getPatch(),0,2000); @@ -67,7 +67,7 @@ public class LocateValidator extends Validator { floatRange("Endpoint Latitude",e.getLatitude(),-90f,90f); floatRange("Endpoint Longitude",e.getLongitude(),-180f,180f); nullOrBlank("Endpoint Protocol", e.getProtocol()); - for(String s : e.getSubprotocol()) { + for (String s : e.getSubprotocol()) { nullOrBlank("Endpoint Subprotocol", s); } } @@ -75,13 +75,13 @@ public class LocateValidator extends Validator { } public LocateValidator endpoints(Endpoints e, boolean emptyNotOK) { - if(e==null) { + if (e==null) { msg("Endpoints Data is null."); } else { - if(emptyNotOK && e.getEndpoint().size()==0) { + if (emptyNotOK && e.getEndpoint().size()==0) { msg("Endpoints contains no endpoints"); } else { - for(Endpoint ep : e.getEndpoint()) { + for (Endpoint ep : e.getEndpoint()) { endpoint(ep); } } @@ -90,10 +90,10 @@ public class LocateValidator extends Validator { } public LocateValidator mgmt_endpoint_key(MgmtEndpoints meps) { - if(meps==null) { + if (meps==null) { msg("MgmtEndpoints Data is null."); } else { - for(MgmtEndpoint ep : meps.getMgmtEndpoint()) { + for (MgmtEndpoint ep : meps.getMgmtEndpoint()) { endpoint_key(ep); } } @@ -101,13 +101,13 @@ public class LocateValidator extends Validator { } public LocateValidator mgmt_endpoints(MgmtEndpoints me, boolean emptyOK) { - if(me==null) { + if (me==null) { msg("MgmtEndpoints Data is null."); } else { - if(!emptyOK && me.getMgmtEndpoint().size()==0) { + if (!emptyOK && me.getMgmtEndpoint().size()==0) { msg("MgmtEndpoints contains no data"); } else { - for(MgmtEndpoint ep : me.getMgmtEndpoint()) { + for (MgmtEndpoint ep : me.getMgmtEndpoint()) { mgmt_endpoint(ep); } } @@ -117,21 +117,21 @@ public class LocateValidator extends Validator { private LocateValidator mgmt_endpoint(MgmtEndpoint ep) { endpoint(ep); - for(SpecialPorts sp : ep.getSpecialPorts()) { + for (SpecialPorts sp : ep.getSpecialPorts()) { specialPorts(sp); } return this; } private LocateValidator specialPorts(SpecialPorts sp) { - if(sp==null) { + if (sp==null) { msg("Special Ports is null."); } else { nullOrBlank("Special Port Name",sp.getName()); nullOrBlank("Special Port Protocol",sp.getProtocol()); intRange("Special Port",sp.getPort(),0,1000000); - for(String s : sp.getProtocolVersions()) { + for (String s : sp.getProtocolVersions()) { nullOrBlank("Special Port Protocol Version", s); } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java index 3ae80e3c..4104c34b 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/AAF_OAuth.java @@ -89,7 +89,7 @@ public class AAF_OAuth extends AbsService<AuthzEnv,AuthzTrans> { super(env.access(),env); String aaf_env = env.getProperty(Config.AAF_ENV); - if(aaf_env==null) { + if (aaf_env==null) { throw new APIException("aaf_env needs to be set"); } @@ -129,10 +129,10 @@ public class AAF_OAuth extends AbsService<AuthzEnv,AuthzTrans> { String version = "1.0"; // Get Correct API Class from Mapper Class<?> respCls = facade1_0.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + if (respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); // setup Application API HTML ContentTypes for JSON and Route String application = applicationJSON(respCls, version); - if(meth.equals(HttpMethods.POST)) { + if (meth.equals(HttpMethods.POST)) { route(env,meth,path,code,application,"application/json;version="+version,"application/x-www-form-urlencoded","*/*"); } else { route(env,meth,path,code,application,"application/json;version="+version,"*/*"); @@ -147,7 +147,7 @@ public class AAF_OAuth extends AbsService<AuthzEnv,AuthzTrans> { atl[0] = doat; atl[1] = doat.directUserPass(); - if(additionalTafLurs.length>0) { + if (additionalTafLurs.length>0) { System.arraycopy(additionalTafLurs, 0, atl, 2, additionalTafLurs.length); } @@ -176,10 +176,10 @@ public class AAF_OAuth extends AbsService<AuthzEnv,AuthzTrans> { @Override public void destroy() { Cache.stopTimer(); - if(service!=null) { + if (service!=null) { service.close(); } - if(cluster!=null) { + if (cluster!=null) { cluster.close(); } super.destroy(); diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java index bb882367..3d863824 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/DirectOAuthTAF.java @@ -74,7 +74,7 @@ public class DirectOAuthTAF implements HttpTaf { tkMgr = TokenMgr.getInstance(access,"dbToken","dbIntrospect"); String alt_url = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL,null); TokenClientFactory tcf; - if(alt_url!=null) { + if (alt_url!=null) { try { tcf = TokenClientFactory.instance(access); String[] split = Split.split(',', alt_url); @@ -94,42 +94,42 @@ public class DirectOAuthTAF implements HttpTaf { public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { String value; String token; - if((value=req.getHeader("Authorization"))!=null && value.startsWith("Bearer ")) { + if ((value=req.getHeader("Authorization"))!=null && value.startsWith("Bearer ")) { token = value.substring(7); } else { token = null; } - if("application/x-www-form-urlencoded".equals(req.getContentType())) { + if ("application/x-www-form-urlencoded".equals(req.getContentType())) { Map<String, String[]> map = req.getParameterMap(); String client_id=null,client_secret=null,username=null,password=null; - for(Map.Entry<String, String[]> es : map.entrySet()) { + for (Map.Entry<String, String[]> es : map.entrySet()) { switch(es.getKey()) { case "client_id": - for(String s : es.getValue()) { + for (String s : es.getValue()) { client_id=s; } break; case "client_secret": - for(String s : es.getValue()) { + for (String s : es.getValue()) { client_secret=s; } break; case "username": - for(String s : es.getValue()) { + for (String s : es.getValue()) { username=s; } break; case "password": - for(String s : es.getValue()) { + for (String s : es.getValue()) { password=s; } break; case "token": - if(token!=null) { // Defined as both Bearer and Form Encoded - Error + if (token!=null) { // Defined as both Bearer and Form Encoded - Error return new OAuth2HttpTafResp(access, null, "Token Info found as both Bearer Token and Form Info", RESP.FAIL, resp, true); } - for(String s : es.getValue()) { + for (String s : es.getValue()) { token=s; } break; @@ -137,22 +137,22 @@ public class DirectOAuthTAF implements HttpTaf { } } - if(client_id==null || client_secret==null) { + if (client_id==null || client_secret==null) { return new OAuth2HttpTafResp(access, null, "client_id and client_secret required", RESP.TRY_ANOTHER_TAF, resp, false); } - if(token==null) { // No Token to work with, use only Client_ID and Client_Secret + if (token==null) { // No Token to work with, use only Client_ID and Client_Secret AuthzTrans trans = (AuthzTrans)req.getAttribute(TransFilter.TRANS_TAG); - if(directUserPass.validate(client_id, Type.PASSWORD, client_secret.getBytes(), trans)) { + if (directUserPass.validate(client_id, Type.PASSWORD, client_secret.getBytes(), trans)) { // Client_ID is valid - if(username==null) { // Validating just the Client_ID + if (username==null) { // Validating just the Client_ID return new OAuth2FormHttpTafResp(access,new OAuth2FormPrincipal(client_id,client_id),"OAuth client_id authenticated",RESP.IS_AUTHENTICATED,resp,false); } else { //TODO - Does a clientID need specific Authorization to pair authentication with user name? At the moment, no. // username is ok. - if(password!=null) { - if(directUserPass.validate(username, Type.PASSWORD, password.getBytes(), trans)) { + if (password!=null) { + if (directUserPass.validate(username, Type.PASSWORD, password.getBytes(), trans)) { return new OAuth2FormHttpTafResp(access,new OAuth2FormPrincipal(client_id, username),"OAuth username authenticated",RESP.IS_AUTHENTICATED,resp,false); } else { return new OAuth2HttpTafResp(access,null,"OAuth username " + username + " not authenticated ",RESP.FAIL,resp,true); @@ -169,14 +169,14 @@ public class DirectOAuthTAF implements HttpTaf { } // OK, have only a Token to validate - if(token!=null) { + if (token!=null) { AuthzTrans trans = (AuthzTrans)req.getAttribute(TransFilter.TRANS_TAG); try { Result<Introspect> ri = oaFacade.mappedIntrospect(trans, token); - if(ri.isOK()) { + if (ri.isOK()) { TokenPerm tp = tkMgr.putIntrospect(ri.value, Hash.hashSHA256(token.getBytes())); - if(tp==null) { + if (tp==null) { return new OAuth2HttpTafResp(access, null, "TokenPerm persistence failure", RESP.FAIL, resp, false); } else { return new OAuth2HttpTafResp(access,new OAuth2Principal(tp,Hash.hashSHA256(token.getBytes())),"Token Authenticated",RESP.IS_AUTHENTICATED,resp,false); @@ -209,7 +209,7 @@ public class DirectOAuthTAF implements HttpTaf { @Override public org.onap.aaf.cadi.client.Result<TokenPerm> load(String accessToken, byte[] cred) throws APIException, CadiException, LocatorException { Result<Introspect> ri = oaFacade.mappedIntrospect(trans, accessToken); - if(ri.notOK()) { + if (ri.notOK()) { //TODO what should the status mapping be? return org.onap.aaf.cadi.client.Result.err(ri.status,ri.errorString()); } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java index 161f6095..9777f564 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/OAuth2Filter.java @@ -45,11 +45,11 @@ public class OAuth2Filter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest hreq = (HttpServletRequest)request; Principal p = hreq.getUserPrincipal(); - if(request.getContentType().equals("application/x-www-form-urlencoded")) { + if (request.getContentType().equals("application/x-www-form-urlencoded")) { - } else if(p instanceof BearerPrincipal) { - for(String authz : Split.splitTrim(';', hreq.getHeader("Authorization"))) { - if(authz.startsWith("Bearer ")) { + } else if (p instanceof BearerPrincipal) { + for (String authz : Split.splitTrim(';', hreq.getHeader("Authorization"))) { + if (authz.startsWith("Bearer ")) { ((BearerPrincipal)p).setBearer(authz.substring(7)); } } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java index f795dfd3..0ed4fbed 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/api/API_Token.java @@ -58,7 +58,7 @@ public class API_Token { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.createBearerToken(trans,req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(201/*HttpStatus.CREATED_201*/); } else { context.error(trans,resp,r); @@ -70,7 +70,7 @@ public class API_Token { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.introspect(trans,req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(200 /*HttpStatus.OK_200*/); } else { context.error(trans,resp,r); diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java index 2935ea3d..36f08b15 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/DirectIntrospectImpl.java @@ -44,9 +44,9 @@ public class DirectIntrospectImpl<INTROSPECT> extends FacadeImpl implements Dire public Result<INTROSPECT> mappedIntrospect(AuthzTrans trans, String token) { Result<INTROSPECT> rti; Result<OAuthTokenDAO.Data> rs = service.introspect(trans,token); - if(rs.notOK()) { + if (rs.notOK()) { rti = Result.err(rs); - } else if(rs.isEmpty()) { + } else if (rs.isEmpty()) { rti = Result.err(Result.ERR_NotFound,"No Token %s found",token); } else { rti = mapper.introspect(rs); diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java index cd1d7df1..e5e12bd6 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/facade/OAFacadeImpl.java @@ -119,27 +119,27 @@ public abstract class OAFacadeImpl<TOKEN_REQ,TOKEN,INTROSPECT,ERROR> TOKEN_REQ request; try { request = mapper.tokenReqFromParams(req); - if(request==null) { + if (request==null) { Data<TOKEN_REQ> rd = tokenReqDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,rd.asString()); } request = rd.asObject(); } - } catch(APIException e) { + } catch (APIException e) { trans.error().log(INVALID_INPUT,IN,CREATE_TOKEN); return Result.err(Status.ERR_BadData,INVALID_INPUT); } // Already validated for Oauth2FormPrincipal // Result<Void> rv = service.validate(trans,mapper.credsFromReq(request)); -// if(rv.notOK()) { +// if (rv.notOK()) { // return rv; // } Holder<GRANT_TYPE> hgt = new Holder<GRANT_TYPE>(GRANT_TYPE.unknown); Result<OAuthTokenDAO.Data> rs = service.createToken(trans,req,mapper.clientTokenReq(request,hgt),hgt); Result<TOKEN> rp; - if(rs.isOKhasData()) { + if (rs.isOKhasData()) { rp = mapper.tokenFromData(rs); } else { rp = Result.err(rs); @@ -147,7 +147,7 @@ public abstract class OAFacadeImpl<TOKEN_REQ,TOKEN,INTROSPECT,ERROR> switch(rp.status) { case OK: RosettaData<TOKEN> data = tokenDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -175,30 +175,30 @@ public abstract class OAFacadeImpl<TOKEN_REQ,TOKEN,INTROSPECT,ERROR> try { Principal p = req.getUserPrincipal(); String token=null; - if(p != null) { - if(p instanceof OAuth2Principal) { + if (p != null) { + if (p instanceof OAuth2Principal) { RosettaData<INTROSPECT> data = introspectDF.newData(trans).load(mapper.fromPrincipal((OAuth2Principal)p)); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); resp.getOutputStream().print('\n'); setContentType(resp,tokenDF.getOutType()); return Result.ok(); - } else if(p instanceof OAuth2FormPrincipal) { + } else if (p instanceof OAuth2FormPrincipal) { token = req.getParameter("token"); } } - if(token==null) { + if (token==null) { token = req.getParameter("access_token"); - if(token==null || token.isEmpty()) { + if (token==null || token.isEmpty()) { token = req.getHeader("Authorization"); - if(token != null && token.startsWith("Bearer ")) { + if (token != null && token.startsWith("Bearer ")) { token = token.substring(7); } else { token = req.getParameter("token"); - if(token==null) { + if (token==null) { return Result.err(Result.ERR_Security,"token is required"); } } @@ -209,7 +209,7 @@ public abstract class OAFacadeImpl<TOKEN_REQ,TOKEN,INTROSPECT,ERROR> switch(rti.status) { case OK: RosettaData<INTROSPECT> data = introspectDF.newData(trans).load(rti.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -308,7 +308,7 @@ public abstract class OAFacadeImpl<TOKEN_REQ,TOKEN,INTROSPECT,ERROR> "] " + holder.toString(), Env.ALWAYS); - if(hidemsg) { + if (hidemsg) { holder.setLength(0); em = mapper.errorFromMessage(holder, msgId, "Server had an issue processing this request"); } diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java index 4be079e4..027a51a7 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/Mapper1_0.java @@ -78,7 +78,7 @@ public class Mapper1_0 extends MapperIntrospect1_0 implements Mapper<TokenReques err.setMessageId(msgID); // AT&T Restful Error Format requires numbers "%" placements err.setText(Vars.convert(holder, text, var)); - for(String s : var) { + for (String s : var) { err.getVariables().add(s); } return err; @@ -89,46 +89,46 @@ public class Mapper1_0 extends MapperIntrospect1_0 implements Mapper<TokenReques TokenRequest tr = new TokenRequest(); boolean data = false; Map<String, String[]> map = req.getParameterMap(); - for(Entry<String, String[]> es : map.entrySet()) { + for (Entry<String, String[]> es : map.entrySet()) { switch(es.getKey()) { case "client_id": - if(es.getValue().length==1) { + if (es.getValue().length==1) { tr.setClientId(es.getValue()[0]); data = true; } break; case "client_secret": - if(es.getValue().length==1) { + if (es.getValue().length==1) { tr.setClientSecret(es.getValue()[0]); data = true; } break; case "username": - if(es.getValue().length==1) { + if (es.getValue().length==1) { tr.setUsername(es.getValue()[0]); data = true; } break; case "password": - if(es.getValue().length==1) { + if (es.getValue().length==1) { tr.setPassword(es.getValue()[0]); data = true; } break; case "scope": - if(es.getValue().length==1) { + if (es.getValue().length==1) { tr.setScope(es.getValue()[0]); data = true; } break; case "grant_type": - if(es.getValue().length==1) { + if (es.getValue().length==1) { tr.setGrantType(es.getValue()[0]); data = true; } break; case "refresh_token": - if(es.getValue().length==1) { + if (es.getValue().length==1) { tr.setRefreshToken(es.getValue()[0]); data = true; } @@ -158,12 +158,12 @@ public class Mapper1_0 extends MapperIntrospect1_0 implements Mapper<TokenReques OAuthTokenDAO.Data tdd = new OAuthTokenDAO.Data(); tdd.client_id = tokReq.getClientId(); tdd.user = tokReq.getUsername(); - if(tokReq.getRefreshToken()!=null) { + if (tokReq.getRefreshToken()!=null) { tdd.refresh=tokReq.getRefreshToken(); } - for(GRANT_TYPE ttt : GRANT_TYPE.values()) { - if(ttt.name().equals(tokReq.getGrantType())) { + for (GRANT_TYPE ttt : GRANT_TYPE.values()) { + if (ttt.name().equals(tokReq.getGrantType())) { hgt.set(ttt); break; } @@ -180,9 +180,9 @@ public class Mapper1_0 extends MapperIntrospect1_0 implements Mapper<TokenReques break; } String scopes=tokReq.getScope(); - if(scopes!=null) { + if (scopes!=null) { Set<String> ss = tdd.scopes(true); - for(String s: Split.split(' ', tokReq.getScope())) { + for (String s: Split.split(' ', tokReq.getScope())) { ss.add(s); } } @@ -193,12 +193,12 @@ public class Mapper1_0 extends MapperIntrospect1_0 implements Mapper<TokenReques @Override public Result<Token> tokenFromData(Result<Data> rd) { - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); } Data d = rd.value; Token token = new Token(); - if(OAuthService.TOKEN_TYPE.values().length>d.type) { + if (OAuthService.TOKEN_TYPE.values().length>d.type) { token.setTokenType(OAuthService.TOKEN_TYPE.values()[d.type].name()); } else { token.setTokenType("Invalid"); diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java index ac015c81..33df05fa 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/mapper/MapperIntrospect1_0.java @@ -32,19 +32,19 @@ import aafoauth.v2_0.Introspect; public class MapperIntrospect1_0 implements MapperIntrospect<Introspect> { public Result<Introspect> introspect(Result<Data> rs) { - if(rs.isOKhasData()) { + if (rs.isOKhasData()) { Data data = rs.value; Introspect ti = new Introspect(); ti.setAccessToken(data.id); ti.setActive(data.active); ti.setClientId(data.client_id); - for(CLIENT_TYPE ct : CLIENT_TYPE.values()) { - if(data.type==ct.ordinal()) { + for (CLIENT_TYPE ct : CLIENT_TYPE.values()) { + if (data.type==ct.ordinal()) { ti.setClientType(ct.name()); break; } } - if(ti.getClientType()==null) { + if (ti.getClientType()==null) { ti.setClientType(CLIENT_TYPE.unknown.name()); } ti.setActive(data.active); @@ -60,8 +60,8 @@ public class MapperIntrospect1_0 implements MapperIntrospect<Introspect> { protected static String getScopes(Set<String> scopes) { StringBuilder sb = new StringBuilder(); boolean start = true; - for(String s : scopes) { - if(start) { + for (String s : scopes) { + if (start) { start = false; } else { sb.append(' '); diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java index 886b06c5..8bceb2ab 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/JSONPermLoaderFactory.java @@ -52,8 +52,8 @@ public class JSONPermLoaderFactory { pathinfo.append(user); pathinfo.append("?scopes="); boolean first = true; - for(String s : scopes) { - if(first) { + for (String s : scopes) { + if (first) { first = false; } else { pathinfo.append(':'); @@ -63,9 +63,9 @@ public class JSONPermLoaderFactory { TimeTaken tt = trans.start("Call AAF Service", Env.REMOTE); try { Future<String> fs = c.read(pathinfo.toString(), "application/Perms+json;charset=utf-8;version=2.0"); - if(fs.get(timeout)) { + if (fs.get(timeout)) { return Result.ok(fs.body()); - } else if(fs.code()==404) { + } else if (fs.code()==404) { return Result.err(Result.ERR_NotFound,fs.body()); } else { return Result.err(Result.ERR_Backend,"Error accessing AAF %s: %s",Integer.toString(fs.code()),fs.body()); @@ -86,15 +86,15 @@ public class JSONPermLoaderFactory { } finally { tt.done(); } - if(pd.notOK()) { + if (pd.notOK()) { return Result.err(pd); } // Since we know it is StringBuilder sb = new StringBuilder("{\"perm\":["); boolean first = true; - for(PermDAO.Data d : pd.value) { - if(scopes.contains(d.ns)) { - if(first) { + for (PermDAO.Data d : pd.value) { + if (scopes.contains(d.ns)) { + if (first) { first = false; } else { sb.append(','); diff --git a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java index 1d926a74..e3aed80c 100644 --- a/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java +++ b/auth/auth-oauth/src/main/java/org/onap/aaf/auth/oauth/service/OAuthService.java @@ -82,7 +82,7 @@ public class OAuthService { }; try { String alt_url = access.getProperty(Config.AAF_ALT_OAUTH2_INTROSPECT_URL,null); - if(alt_url!=null) { + if (alt_url!=null) { tcf = TokenClientFactory.instance(access); String[] split = Split.split(',', alt_url); int timeout = split.length>1?Integer.parseInt(split[1]):3000; @@ -101,7 +101,7 @@ public class OAuthService { } public Result<Void> validate(AuthzTrans trans, OCreds creds) { - if(directUserPass.validate(creds.username, Type.PASSWORD, creds.password, trans)) { + if (directUserPass.validate(creds.username, Type.PASSWORD, creds.password, trans)) { return Result.ok(); } else { return Result.err(Result.ERR_Security, "Invalid Credential for ",creds.username); @@ -121,7 +121,7 @@ public class OAuthService { } private Result<Data> createBearerToken(AuthzTrans trans, OAuthTokenDAO.Data odd) { - if(odd.user==null) { + if (odd.user==null) { odd.user = trans.user(); } odd.id = AAFToken.toToken(UUID.randomUUID()); @@ -134,7 +134,7 @@ public class OAuthService { try { Result<Data> rd = loadToken(trans, odd); - if(rd.notOK()) { + if (rd.notOK()) { return rd; } } catch (APIException | CadiException e) { @@ -145,11 +145,11 @@ public class OAuthService { private Result<Data> loadToken(AuthzTrans trans, Data odd) throws APIException, CadiException { Result<String> rs = permLoader.loadJSONPerms(trans,odd.user,odd.scopes(false)); - if(rs.isOK()) { + if (rs.isOK()) { odd.content = rs.value; odd.type = TOKEN_TYPE.bearer.ordinal(); return Result.ok(odd); - } else if(rs.status == Result.ERR_NotFound || rs.status==Status.ERR_UserRoleNotFound) { + } else if (rs.status == Result.ERR_NotFound || rs.status==Status.ERR_UserRoleNotFound) { odd.type = TOKEN_TYPE.bearer.ordinal(); return Result.ok(odd); } else { @@ -161,28 +161,28 @@ public class OAuthService { private Result<Data> refreshBearerToken(AuthzTrans trans, Data odd) { Result<List<Data>> rld = tokenDAO.readByUser(trans, trans.user()); - if(rld.notOK()) { + if (rld.notOK()) { return Result.err(rld); } - if(rld.isEmpty()) { + if (rld.isEmpty()) { return Result.err(Result.ERR_NotFound,"Data not Found for %1 %2",trans.user(),odd.refresh==null?"":odd.refresh.toString()); } Data token = null; - for(Data d : rld.value) { - if(d.refresh.equals(odd.refresh)) { + for (Data d : rld.value) { + if (d.refresh.equals(odd.refresh)) { token = d; boolean scopesNE = false; Set<String> scopes = odd.scopes(false); - if(scopes.size()>0) { // only check if Scopes listed, RFC 6749, Section 6 - if(scopesNE=!(scopes.size() == d.scopes(false).size())) { - for(String s : odd.scopes(false)) { - if(!d.scopes(false).contains(s)) { + if (scopes.size()>0) { // only check if Scopes listed, RFC 6749, Section 6 + if (scopesNE=!(scopes.size() == d.scopes(false).size())) { + for (String s : odd.scopes(false)) { + if (!d.scopes(false).contains(s)) { scopesNE=true; break; } } } - if(scopesNE) { + if (scopesNE) { return Result.err(Result.ERR_BadData,"Requested Scopes do not match existing Token"); } } @@ -190,7 +190,7 @@ public class OAuthService { } } - if(token==null) { + if (token==null) { trans.audit().printf("Duplicate Refresh Token (%s) attempted for %s. Possible Replay Attack",odd.refresh.toString(),trans.user()); return Result.err(Result.ERR_Security,"Invalid Refresh Token"); } else { @@ -205,11 +205,11 @@ public class OAuthService { token.exp_sec = exp/1000; token.req_ip = trans.ip(); Result<Data> rd = tokenDAO.create(trans, token); - if(rd.notOK()) { + if (rd.notOK()) { return Result.err(rd); } Result<Void> rv = tokenDAO.delete(trans, deleteMe,false); - if(rv.notOK()) { + if (rv.notOK()) { trans.error().log("Unable to delete token", token); } } @@ -220,22 +220,22 @@ public class OAuthService { Result<List<Data>> rld; try { UUID uuid = AAFToken.fromToken(token); - if(uuid==null) { // not an AAF Token + if (uuid==null) { // not an AAF Token // Attempt to get Alternative Token - if(altIntrospectClient!=null) { + if (altIntrospectClient!=null) { org.onap.aaf.cadi.client.Result<Introspect> rai = altIntrospectClient.introspect(token); - if(rai.isOK()) { + if (rai.isOK()) { Introspect in = rai.value; - if(in.getExp()==null) { + if (in.getExp()==null) { trans.audit().printf("Alt OAuth sent back inactive, empty token: requesting_id,%s,access_token=%s,ip=%s\n",trans.user(),token,trans.ip()); } long expires = in.getExp()*1000; - if(in.isActive() && expires>System.currentTimeMillis()) { + if (in.isActive() && expires>System.currentTimeMillis()) { // We have a good Token, modify to be Fully Qualified String fqid = in.getUsername()+altDomain; // read contents rld = tokenDAO.read(trans, token); - if(rld.isOKhasData()) { + if (rld.isOKhasData()) { Data td = rld.value.get(0); in.setContent(td.content); } else { @@ -248,8 +248,8 @@ public class OAuthService { td.expires = new Date(expires); td.exp_sec = in.getExp(); Set<String> scopes = td.scopes(true); - if(in.getScope()!=null) { - for(String s : Split.split(' ', in.getScope())) { + if (in.getScope()!=null) { + for (String s : Split.split(' ', in.getScope())) { scopes.add(s); } } @@ -277,13 +277,13 @@ public class OAuthService { public Result<Data> dbIntrospect(final AuthzTrans trans, final String token) { Result<List<Data>> rld = tokenDAO.read(trans, token); - if(rld.notOKorIsEmpty()) { + if (rld.notOKorIsEmpty()) { return Result.err(rld); } OAuthTokenDAO.Data odd = rld.value.get(0); trans.checkpoint(odd.user + ':' + odd.client_id + ", " + odd.id); - if(odd.active) { - if(odd.expires.before(trans.now())) { + if (odd.active) { + if (odd.expires.before(trans.now())) { return Result.err(Result.ERR_Policy,"Token %1 has expired",token); } return Result.ok(rld.value.get(0)); // ok keyed on id/token. @@ -293,7 +293,7 @@ public class OAuthService { } public void close() { - for(DAO<AuthzTrans,?> dao : daos) { + for (DAO<AuthzTrans,?> dao : daos) { dao.close(NullTrans.singleton()); } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java index 69cde411..4a592651 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AAF_Service.java @@ -104,8 +104,8 @@ public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { // Initialize Organizations... otherwise, first pass may miss int org_size = ORGANIZATION.length(); - for(String n : env.existingStaticSlotNames()) { - if(n.startsWith(ORGANIZATION)) { + for (String n : env.existingStaticSlotNames()) { + if (n.startsWith(ORGANIZATION)) { OrganizationFactory.obtain(env, n.substring(org_size)); } } @@ -122,7 +122,7 @@ public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { // Print results and cleanup StringBuilder sb = new StringBuilder(); trans.auditTrail(0, sb); - if(sb.length()>0)env.init().log(sb); + if (sb.length()>0)env.init().log(sb); trans = null; sb = null; @@ -167,7 +167,7 @@ public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { domain,Long.parseLong(env.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)), false); - if(additionalTafLurs.length>0) { + if (additionalTafLurs.length>0) { System.arraycopy(additionalTafLurs, 0, atl, 2, additionalTafLurs.length); } @@ -194,7 +194,7 @@ public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { @Override public void destroy() { Cache.stopTimer(); - if(cluster!=null) { + if (cluster!=null) { cluster.close(); } super.destroy(); @@ -211,7 +211,7 @@ public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { public void route(HttpMethods meth, String path, API api, Code code) throws Exception { String version = "2.0"; Class<?> respCls = facade.mapper().getClass(api); - if(respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); + if (respCls==null) throw new Exception("Unknown class associated with " + api.getClass().getName() + ' ' + api.name()); String application = applicationJSON(respCls, version); route(env,meth,path,code,application,"application/json;version=2.0","*/*"); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java index c3e92df4..789a2e65 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzCassServiceImpl.java @@ -160,16 +160,16 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> createNS(final AuthzTrans trans, REQUEST from, NsType type) { final Result<Namespace> rnamespace = mapper.ns(trans, from); final ServiceValidator v = new ServiceValidator(); - if(v.ns(rnamespace).err()) { + if (v.ns(rnamespace).err()) { return Result.err(Status.ERR_BadData,v.errs()); } final Namespace namespace = rnamespace.value; final Result<NsDAO.Data> parentNs = ques.deriveNs(trans,namespace.name); - if(parentNs.notOK()) { + if (parentNs.notOK()) { return Result.err(parentNs); } - if(namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed + if (namespace.name.lastIndexOf('.')<0) { // Root Namespace... Function will check if allowed return func.createNS(trans, namespace, false); } @@ -184,7 +184,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> rnd; @Override public Result<?> mayChange() { - if(rnd==null) { + if (rnd==null) { rnd = ques.mayUser(trans, trans.user(), parentNs.value,Access.write); } return rnd; @@ -193,7 +193,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(fd.status) { case OK: Result<String> rfc = func.createFuture(trans, fd.value, namespace.name, trans.user(),parentNs.value, FUTURE_OP.C); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "NS [%s] is saved for future processing",namespace.name); } else { return Result.err(rfc); @@ -293,7 +293,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE try { // Check inputs final Validator v = new ServiceValidator(); - if(v.ns(ns).err() || + if (v.ns(ns).err() || v.key(key).err() || v.value(value).err()) { return Result.err(Status.ERR_BadData,v.errs()); @@ -301,18 +301,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Check if exists already Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns); - if(rlnsd.notOKorIsEmpty()) { + if (rlnsd.notOKorIsEmpty()) { return Result.err(rlnsd); } NsDAO.Data nsd = rlnsd.value.get(0); // Check for Existence - if(nsd.attrib.get(key)!=null) { + if (nsd.attrib.get(key)!=null) { return Result.err(Status.ERR_ConflictAlreadyExists, "NS Property %s:%s exists", ns, key); } // Check if User may put - if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + if (!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); } @@ -340,18 +340,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<KEYS> readNsByAttrib(AuthzTrans trans, String key) { // Check inputs final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Key",key).err()) { + if (v.nullOrBlank("Key",key).err()) { return Result.err(Status.ERR_BadData,v.errs()); } // May Read - if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + if (!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, ":"+trans.org().getDomain()+".*:"+key, Question.READ)) { return Result.err(Status.ERR_Denied,"%s may not read NS by Attrib '%s'",trans.user(),key); } Result<Set<String>> rsd = ques.nsDAO.dao().readNsByAttrib(trans, key); - if(rsd.notOK()) { + if (rsd.notOK()) { return Result.err(rsd); } return mapper().keys(rsd.value); @@ -376,7 +376,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE try { // Check inputs final Validator v = new ServiceValidator(); - if(v.ns(ns).err() || + if (v.ns(ns).err() || v.key(key).err() || v.value(value).err()) { return Result.err(Status.ERR_BadData,v.errs()); @@ -384,18 +384,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Check if exists already (NS must exist) Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns); - if(rlnsd.notOKorIsEmpty()) { + if (rlnsd.notOKorIsEmpty()) { return Result.err(rlnsd); } NsDAO.Data nsd = rlnsd.value.get(0); // Check for Existence - if(nsd.attrib.get(key)==null) { + if (nsd.attrib.get(key)==null) { return Result.err(Status.ERR_NotFound, "NS Property %s:%s exists", ns, key); } // Check if User may put - if(!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, + if (!ques.isGranted(trans, trans.user(), ROOT_NS, Question.ATTRIB, ":"+trans.org().getDomain()+".*:"+key, Access.write.name())) { return Result.err(Status.ERR_Denied, "%s may not create NS Attrib [%s:%s]", trans.user(),ns, key); } @@ -428,25 +428,25 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE try { // Check inputs final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS",ns).err() || + if (v.nullOrBlank("NS",ns).err() || v.nullOrBlank("Key",key).err()) { return Result.err(Status.ERR_BadData,v.errs()); } // Check if exists already Result<List<Data>> rlnsd = ques.nsDAO.read(trans, ns); - if(rlnsd.notOKorIsEmpty()) { + if (rlnsd.notOKorIsEmpty()) { return Result.err(rlnsd); } NsDAO.Data nsd = rlnsd.value.get(0); // Check for Existence - if(nsd.attrib.get(key)==null) { + if (nsd.attrib.get(key)==null) { return Result.err(Status.ERR_NotFound, "NS Property [%s:%s] does not exist", ns, key); } // Check if User may del - if(!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) { + if (!ques.isGranted(trans, trans.user(), ROOT_NS, "attrib", ":" + ROOT_COMPANY + ".*:"+key, Access.write.name())) { return Result.err(Status.ERR_Denied, "%s may not delete NS Attrib [%s:%s]", trans.user(),ns, key); } @@ -473,28 +473,28 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<NSS> getNSbyName(AuthzTrans trans, String ns) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", ns).err()) { + if (v.nullOrBlank("NS", ns).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, ns); - if(rlnd.isOK()) { - if(rlnd.isEmpty()) { + if (rlnd.isOK()) { + if (rlnd.isEmpty()) { return Result.err(Status.ERR_NotFound, "No data found for %s",ns); } Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rlnd.value.get(0), Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } Namespace namespace = new Namespace(rnd.value); Result<List<String>> rd = func.getOwners(trans, namespace.name, false); - if(rd.isOK()) { + if (rd.isOK()) { namespace.owner = rd.value; } rd = func.getAdmins(trans, namespace.name, false); - if(rd.isOK()) { + if (rd.isOK()) { namespace.admin = rd.value; } @@ -523,7 +523,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".admin", full); - if(rn.notOK()) { + if (rn.notOK()) { return Result.err(rn); } if (rn.isEmpty()) { @@ -552,7 +552,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<Collection<Namespace>> rn = loadNamepace(trans, user, null, full); - if(rn.notOK()) { + if (rn.notOK()) { return Result.err(rn); } if (rn.isEmpty()) { @@ -565,55 +565,55 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<Collection<Namespace>> loadNamepace(AuthzTrans trans, String user, String endsWith, boolean full) { Result<List<UserRoleDAO.Data>> urd = ques.userRoleDAO.readByUser(trans, user); - if(urd.notOKorIsEmpty()) { + if (urd.notOKorIsEmpty()) { return Result.err(urd); } Map<String, Namespace> lm = new HashMap<>(); Map<String, Namespace> other = full || endsWith==null?null:new TreeMap<>(); - for(UserRoleDAO.Data urdd : urd.value) { - if(full) { - if(endsWith==null || urdd.role.endsWith(endsWith)) { + for (UserRoleDAO.Data urdd : urd.value) { + if (full) { + if (endsWith==null || urdd.role.endsWith(endsWith)) { RoleDAO.Data rd = RoleDAO.Data.decode(urdd); Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read); - if(nsd.isOK()) { + if (nsd.isOK()) { Namespace namespace = lm.get(nsd.value.name); - if(namespace==null) { + if (namespace==null) { namespace = new Namespace(nsd.value); lm.put(namespace.name,namespace); } Result<List<String>> rls = func.getAdmins(trans, namespace.name, false); - if(rls.isOK()) { + if (rls.isOK()) { namespace.admin=rls.value; } rls = func.getOwners(trans, namespace.name, false); - if(rls.isOK()) { + if (rls.isOK()) { namespace.owner=rls.value; } } } } else { // Shortened version. Only Namespace Info available from Role. - if(Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) { + if (Question.ADMIN.equals(urdd.rname) || Question.OWNER.equals(urdd.rname)) { RoleDAO.Data rd = RoleDAO.Data.decode(urdd); Result<NsDAO.Data> nsd = ques.mayUser(trans, user, rd, Access.read); - if(nsd.isOK()) { + if (nsd.isOK()) { Namespace namespace = lm.get(nsd.value.name); - if(namespace==null) { - if(other!=null) { + if (namespace==null) { + if (other!=null) { namespace = other.remove(nsd.value.name); } - if(namespace==null) { + if (namespace==null) { namespace = new Namespace(nsd.value); namespace.admin=new ArrayList<>(); namespace.owner=new ArrayList<>(); } - if(endsWith==null || urdd.role.endsWith(endsWith)) { + if (endsWith==null || urdd.role.endsWith(endsWith)) { lm.put(namespace.name,namespace); } else { other.put(namespace.name,namespace); } } - if(Question.OWNER.equals(urdd.rname)) { + if (Question.OWNER.equals(urdd.rname)) { namespace.owner.add(urdd.user); } else { namespace.admin.add(urdd.user); @@ -642,7 +642,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE return Result.err(Status.ERR_BadData, v.errs()); } Result<Collection<Namespace>> rn = loadNamepace(trans, user, ".owner",full); - if(rn.notOK()) { + if (rn.notOK()) { return Result.err(rn); } if (rn.isEmpty()) { @@ -666,34 +666,34 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<NSS> getNSsChildren(AuthzTrans trans, String parent) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", parent).err()) { + if (v.nullOrBlank("NS", parent).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<NsDAO.Data> rnd = ques.deriveNs(trans, parent); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } Set<Namespace> lm = new HashSet<>(); Result<List<NsDAO.Data>> rlnd = ques.nsDAO.dao().getChildren(trans, parent); - if(rlnd.isOK()) { - if(rlnd.isEmpty()) { + if (rlnd.isOK()) { + if (rlnd.isEmpty()) { return Result.err(Status.ERR_NotFound, "No data found for %s",parent); } - for(NsDAO.Data ndd : rlnd.value) { + for (NsDAO.Data ndd : rlnd.value) { Namespace namespace = new Namespace(ndd); Result<List<String>> rls = func.getAdmins(trans, namespace.name, false); - if(rls.isOK()) { + if (rls.isOK()) { namespace.admin=rls.value; } rls = func.getOwners(trans, namespace.name, false); - if(rls.isOK()) { + if (rls.isOK()) { namespace.owner=rls.value; } @@ -720,17 +720,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> updateNsDescription(AuthzTrans trans, REQUEST from) { final Result<Namespace> nsd = mapper.ns(trans, from); final ServiceValidator v = new ServiceValidator(); - if(v.ns(nsd).err()) { + if (v.ns(nsd).err()) { return Result.err(Status.ERR_BadData,v.errs()); } - if(v.nullOrBlank("description", nsd.value.description).err()) { + if (v.nullOrBlank("description", nsd.value.description).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Namespace namespace = nsd.value; Result<List<NsDAO.Data>> rlnd = ques.nsDAO.read(trans, namespace.name); - if(rlnd.notOKorIsEmpty()) { + if (rlnd.notOKorIsEmpty()) { return Result.err(Status.ERR_NotFound, "Namespace [%s] does not exist",namespace.name); } @@ -739,7 +739,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<Void> rdr = ques.nsDAO.dao().addDescription(trans, namespace.name, namespace.description); - if(rdr.isOK()) { + if (rdr.isOK()) { return Result.ok(); } else { return Result.err(rdr); @@ -799,7 +799,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> createPerm(final AuthzTrans trans,REQUEST rreq) { final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq); final ServiceValidator v = new ServiceValidator(); - if(v.perm(newPd).err()) { + if (v.perm(newPd).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -817,14 +817,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { nsd = ques.mayUser(trans, trans.user(), newPd.value, Access.write); } return nsd; } }); Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, newPd.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } switch(fd.status) { @@ -834,7 +834,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE trans.user(), nsr.value.get(0), FUTURE_OP.C); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", newPd.value.ns, newPd.value.type, @@ -861,21 +861,21 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<PERMS> getPermsByType(AuthzTrans trans, final String permType) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("PermType", permType).err()) { + if (v.nullOrBlank("PermType", permType).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<PermDAO.Data>> rlpd = ques.getPermsByType(trans, permType); - if(rlpd.notOK()) { + if (rlpd.notOK()) { return Result.err(rlpd); } // We don't have instance & action for mayUserView... do we want to loop through all returned here as well as in mapper? // Result<NsDAO.Data> r; -// if((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r); +// if ((r = ques.mayUserViewPerm(trans, trans.user(), permType)).notOK())return Result.err(r); PERMS perms = mapper.newInstance(API.PERMS); - if(!rlpd.isEmpty()) { + if (!rlpd.isEmpty()) { // Note: Mapper will restrict what can be viewed return mapper.perms(trans, rlpd.value, perms, true); } @@ -895,19 +895,19 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<PERMS> getPermsByName(AuthzTrans trans, String type, String instance, String action) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("PermType", type).err() + if (v.nullOrBlank("PermType", type).err() || v.nullOrBlank("PermInstance", instance).err() || v.nullOrBlank("PermAction", action).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<PermDAO.Data>> rlpd = ques.getPermsByName(trans, type, instance, action); - if(rlpd.notOK()) { + if (rlpd.notOK()) { return Result.err(rlpd); } PERMS perms = mapper.newInstance(API.PERMS); - if(!rlpd.isEmpty()) { + if (!rlpd.isEmpty()) { // Note: Mapper will restrict what can be viewed return mapper.perms(trans, rlpd.value, perms, true); } @@ -926,19 +926,19 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<PERMS> getPermsByUser(AuthzTrans trans, String user) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { + if (v.nullOrBlank("User", user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.requested(force)); - if(rlpd.notOK()) { + if (rlpd.notOK()) { return Result.err(rlpd); } PERMS perms = mapper.newInstance(API.PERMS); - if(rlpd.isEmpty()) { + if (rlpd.isEmpty()) { return Result.ok(perms); } // Note: Mapper will restrict what can be viewed @@ -962,18 +962,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<PERMS> getPermsByUserScope(AuthzTrans trans, String user, String[] scopes) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { + if (v.nullOrBlank("User", user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user, trans.requested(force)); - if(rlpd.notOK()) { + if (rlpd.notOK()) { return Result.err(rlpd); } PERMS perms = mapper.newInstance(API.PERMS); - if(rlpd.isEmpty()) { + if (rlpd.isEmpty()) { return Result.ok(perms); } // Note: Mapper will restrict what can be viewed @@ -1014,13 +1014,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<PERMS> getPermsByUser(AuthzTrans trans, PERMS _perms, String user) { PERMS perms = _perms; final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { + if (v.nullOrBlank("User", user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } ////////////// Result<List<PermDAO.Data>> rlpd = ques.getPermsByUser(trans, user,trans.requested(force)); - if(rlpd.notOK()) { + if (rlpd.notOK()) { return Result.err(rlpd); } @@ -1029,25 +1029,25 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE 2) See if User is allowed */ Result<List<PermDAO.Data>> in = mapper.perms(trans, perms); - if(in.isOKhasData()) { + if (in.isOKhasData()) { List<PermDAO.Data> out = rlpd.value; boolean ok; - for(PermDAO.Data pdd : in.value) { + for (PermDAO.Data pdd : in.value) { ok = false; - if("access".equals(pdd.type)) { + if ("access".equals(pdd.type)) { Access access = Access.valueOf(pdd.action); String[] mdkey = Split.splitTrim(':',pdd.instance); - if(mdkey.length>1) { + if (mdkey.length>1) { String type = mdkey[1]; - if("role".equals(type)) { - if(mdkey.length>2) { + if ("role".equals(type)) { + if (mdkey.length>2) { RoleDAO.Data rdd = new RoleDAO.Data(); rdd.ns=pdd.ns; rdd.name=mdkey[2]; ok = ques.mayUser(trans, trans.user(), rdd, Access.read).isOK() && ques.mayUser(trans, user, rdd , access).isOK(); } - } else if("perm".equals(type)) { - if(mdkey.length>4) { // also need instance/action + } else if ("perm".equals(type)) { + if (mdkey.length>4) { // also need instance/action PermDAO.Data p = new PermDAO.Data(); p.ns=pdd.ns; p.type=mdkey[2]; @@ -1055,21 +1055,21 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE p.action=mdkey[4]; ok = ques.mayUser(trans, trans.user(), p, Access.read).isOK() && ques.mayUser(trans, user, p , access).isOK(); } - } else if("ns".equals(type)) { + } else if ("ns".equals(type)) { NsDAO.Data ndd = new NsDAO.Data(); ndd.name=pdd.ns; ok = ques.mayUser(trans, trans.user(), ndd, Access.read).isOK() && ques.mayUser(trans, user, ndd , access).isOK(); } } } - if(ok) { + if (ok) { out.add(pdd); } } } perms = mapper.newInstance(API.PERMS); - if(rlpd.isEmpty()) { + if (rlpd.isEmpty()) { return Result.ok(perms); } // Note: Mapper will restrict what can be viewed @@ -1090,24 +1090,24 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<PERMS> getPermsByRole(AuthzTrans trans,String role) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role", role).err()) { + if (v.nullOrBlank("Role", role).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques,role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } Result<NsDAO.Data> r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); - if(r.notOK()) { + if (r.notOK()) { return Result.err(r); } PERMS perms = mapper.newInstance(API.PERMS); Result<List<PermDAO.Data>> rlpd = ques.getPermsByRole(trans, role, trans.requested(force)); - if(rlpd.isOKhasData()) { + if (rlpd.isOKhasData()) { // Note: Mapper will restrict what can be viewed return mapper.perms(trans, rlpd.value, perms, true); } @@ -1125,27 +1125,27 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<PERMS> getPermsByNS(AuthzTrans trans,String ns) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", ns).err()) { + if (v.nullOrBlank("NS", ns).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<NsDAO.Data> rnd = ques.deriveNs(trans, ns); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } Result<List<PermDAO.Data>> rlpd = ques.permDAO.readNS(trans, ns); - if(rlpd.notOK()) { + if (rlpd.notOK()) { return Result.err(rlpd); } PERMS perms = mapper.newInstance(API.PERMS); - if(!rlpd.isEmpty()) { + if (!rlpd.isEmpty()) { // Note: Mapper will restrict what can be viewed return mapper.perms(trans, rlpd.value,perms, true); } @@ -1167,7 +1167,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> renamePerm(final AuthzTrans trans,REQUEST rreq, String origType, String origInstance, String origAction) { final Result<PermDAO.Data> newPd = mapper.perm(trans, rreq); final ServiceValidator v = new ServiceValidator(); - if(v.perm(newPd).err()) { + if (v.perm(newPd).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -1179,7 +1179,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<NsSplit> nss = ques.deriveNsSplit(trans, origType); Result<List<PermDAO.Data>> origRlpd = ques.permDAO.read(trans, nss.value.ns, nss.value.name, origInstance, origAction); - if(origRlpd.notOKorIsEmpty()) { + if (origRlpd.notOKorIsEmpty()) { return Result.err(Status.ERR_PermissionNotFound, "Permission [%s|%s|%s] does not exist", origType,origInstance,origAction); @@ -1229,14 +1229,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> updatePermDescription(AuthzTrans trans, REQUEST from) { final Result<PermDAO.Data> pd = mapper.perm(trans, from); final ServiceValidator v = new ServiceValidator(); - if(v.perm(pd).err()) { + if (v.perm(pd).err()) { return Result.err(Status.ERR_BadData,v.errs()); } - if(v.nullOrBlank("description", pd.value.description).err()) { + if (v.nullOrBlank("description", pd.value.description).err()) { return Result.err(Status.ERR_BadData,v.errs()); } final PermDAO.Data perm = pd.value; - if(ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) { + if (ques.permDAO.read(trans, perm.ns, perm.type, perm.instance,perm.action).notOKorIsEmpty()) { return Result.err(Status.ERR_NotFound, "Permission [%s.%s|%s|%s] does not exist", perm.ns,perm.type,perm.instance,perm.action); } @@ -1247,13 +1247,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pd.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } Result<Void> rdr = ques.permDAO.addDescription(trans, perm.ns, perm.type, perm.instance, perm.action, perm.description); - if(rdr.isOK()) { + if (rdr.isOK()) { return Result.ok(); } else { return Result.err(rdr); @@ -1273,12 +1273,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> resetPermRoles(final AuthzTrans trans, REQUEST rreq) { final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq); - if(updt.notOKorIsEmpty()) { + if (updt.notOKorIsEmpty()) { return Result.err(updt); } final ServiceValidator v = new ServiceValidator(); - if(v.perm(updt).err()) { + if (v.perm(updt).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -1294,7 +1294,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE updt.value.instance, updt.value.action); - if(rcurr.notOKorIsEmpty()) { + if (rcurr.notOKorIsEmpty()) { return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist", updt.value.ns,updt.value.type,updt.value.instance,updt.value.action); @@ -1303,9 +1303,9 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Create a set of Update Roles, which are in Internal Format Set<String> updtRoles = new HashSet<>(); Result<NsSplit> nss; - for(String role : updt.value.roles(false)) { + for (String role : updt.value.roles(false)) { nss = ques.deriveNsSplit(trans, role); - if(nss.isOK()) { + if (nss.isOK()) { updtRoles.add(nss.value.ns + '|' + nss.value.name); } else { trans.error().log(nss.errorString()); @@ -1314,17 +1314,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<Void> rv = null; - for(PermDAO.Data curr : rcurr.value) { + for (PermDAO.Data curr : rcurr.value) { Set<String> currRoles = curr.roles(false); // must add roles to this perm, and add this perm to each role // in the update, but not in the current for (String role : updtRoles) { if (!currRoles.contains(role)) { Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role); - if(key.isOKhasData()) { + if (key.isOKhasData()) { Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, key.value); - if(rrd.isOKhasData()) { - for(RoleDAO.Data r : rrd.value) { + if (rrd.isOKhasData()) { + for (RoleDAO.Data r : rrd.value) { rv = func.addPermToRole(trans, r, curr, false); if (rv.notOK() && rv.status!=Result.ERR_ConflictAlreadyExists) { return Result.err(rv); @@ -1341,10 +1341,10 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE for (String role : currRoles) { if (!updtRoles.contains(role)) { Result<RoleDAO.Data> key = RoleDAO.Data.decode(trans, ques, role); - if(key.isOKhasData()) { + if (key.isOKhasData()) { Result<List<RoleDAO.Data>> rdd = ques.roleDAO.read(trans, key.value); - if(rdd.isOKhasData()) { - for(RoleDAO.Data r : rdd.value) { + if (rdd.isOKhasData()) { + for (RoleDAO.Data r : rdd.value) { rv = func.delPermFromRole(trans, r, curr, true); if (rv.notOK() && rv.status!=Status.ERR_PermissionNotFound) { return Result.err(rv); @@ -1373,11 +1373,11 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> deletePerm(final AuthzTrans trans, REQUEST from) { Result<PermDAO.Data> pd = mapper.perm(trans, from); - if(pd.notOK()) { + if (pd.notOK()) { return Result.err(pd); } final ServiceValidator v = new ServiceValidator(); - if(v.nullOrBlank(pd.value).err()) { + if (v.nullOrBlank(pd.value).err()) { return Result.err(Status.ERR_BadData,v.errs()); } final PermDAO.Data perm = pd.value; @@ -1397,7 +1397,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { nsd = ques.mayUser(trans, trans.user(), perm, Access.write); } return nsd; @@ -1407,13 +1407,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(fd.status) { case OK: Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, perm.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } Result<String> rfc = func.createFuture(trans, fd.value, perm.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Perm Deletion [%s] is saved for future processing",perm.encode()); } else { return Result.err(rfc); @@ -1442,7 +1442,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> deletePerm(AuthzTrans trans, String type, String instance, String action) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Type",type) + if (v.nullOrBlank("Type",type) .nullOrBlank("Instance",instance) .nullOrBlank("Action",action) .err()) { @@ -1450,7 +1450,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<PermDAO.Data> pd = ques.permFrom(trans, type, instance, action); - if(pd.isOK()) { + if (pd.isOK()) { return func.deletePerm(trans, pd.value, trans.requested(force), false); } else { return Result.err(pd); @@ -1485,11 +1485,11 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> createRole(final AuthzTrans trans, REQUEST from) { final Result<RoleDAO.Data> rd = mapper.role(trans, from); final ServiceValidator v = new ServiceValidator(); - if(v.role(rd).err()) { + if (v.role(rd).err()) { return Result.err(Status.ERR_BadData,v.errs()); } final RoleDAO.Data role = rd.value; - if(ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) { + if (ques.roleDAO.read(trans, role.ns, role.name).isOKhasData()) { return Result.err(Status.ERR_ConflictAlreadyExists, "Role [" + role.fullName() + "] already exists"); } @@ -1506,7 +1506,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { nsd = ques.mayUser(trans, trans.user(), role, Access.write); } return nsd; @@ -1514,7 +1514,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE }); Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } @@ -1522,7 +1522,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE case OK: Result<String> rfc = func.createFuture(trans, fd.value, role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.C); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Role [%s.%s] is saved for future processing", rd.value.ns, rd.value.name); @@ -1531,7 +1531,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } case Status.ACC_Now: Result<RoleDAO.Data> rdr = ques.roleDAO.create(trans, role); - if(rdr.isOK()) { + if (rdr.isOK()) { return Result.ok(); } else { return Result.err(rdr); @@ -1557,15 +1557,15 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<ROLES> getRolesByName(AuthzTrans trans, String role) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role", role).err()) { + if (v.nullOrBlank("Role", role).err()) { return Result.err(Status.ERR_BadData,v.errs()); } // Determine if User can ask this question Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.isOKhasData()) { + if (rrdd.isOKhasData()) { Result<NsDAO.Data> r; - if((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) { + if ((r = ques.mayUser(trans, trans.user(), rrdd.value, Access.read)).notOK()) { return Result.err(r); } } else { @@ -1575,7 +1575,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Look up data int query = role.indexOf('?'); Result<List<RoleDAO.Data>> rlrd = ques.getRolesByName(trans, query<0?role:role.substring(0, query)); - if(rlrd.isOK()) { + if (rlrd.isOK()) { // Note: Mapper will restrict what can be viewed ROLES roles = mapper.newInstance(API.ROLES); return mapper.roles(trans, rlrd.value, roles, true); @@ -1602,7 +1602,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<ROLES> getRolesByUser(AuthzTrans trans, String user) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { + if (v.nullOrBlank("User", user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -1610,12 +1610,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Get list of roles per user, then add to Roles as we go Result<List<RoleDAO.Data>> rlrd; Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user); - if(rlurd.isOKhasData()) { - for(UserRoleDAO.Data urd : rlurd.value ) { + if (rlurd.isOKhasData()) { + for (UserRoleDAO.Data urd : rlurd.value ) { rlrd = ques.roleDAO.read(trans, urd.ns,urd.rname); // Note: Mapper will restrict what can be viewed // if user is the same as that which is looked up, no filtering is required - if(rlrd.isOKhasData()) { + if (rlrd.isOKhasData()) { mapper.roles(trans, rlrd.value,roles, !user.equals(trans.user())); } } @@ -1641,17 +1641,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<ROLES> getRolesByNS(AuthzTrans trans, String ns) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS", ns).err()) { + if (v.nullOrBlank("NS", ns).err()) { return Result.err(Status.ERR_BadData,v.errs()); } // check if user is allowed to view NS Result<NsDAO.Data> rnsd = ques.deriveNs(trans, ns); - if(rnsd.notOK()) { + if (rnsd.notOK()) { return Result.err(rnsd); } rnsd = ques.mayUser(trans, trans.user(), rnsd.value, Access.read); - if(rnsd.notOK()) { + if (rnsd.notOK()) { return Result.err(rnsd); } @@ -1660,8 +1660,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE ROLES roles = mapper.newInstance(API.ROLES); // Get list of roles per user, then add to Roles as we go Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readNS(trans, ns); - if(rlrd.isOK()) { - if(!rlrd.isEmpty()) { + if (rlrd.isOK()) { + if (!rlrd.isEmpty()) { // Note: Mapper doesn't need to restrict what can be viewed, because we did it already. mapper.roles(trans,rlrd.value,roles,false); } @@ -1691,7 +1691,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<ROLES> getRolesByNameOnly(AuthzTrans trans, String name) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Name", name).err()) { + if (v.nullOrBlank("Name", name).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -1702,8 +1702,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE ROLES roles = mapper.newInstance(API.ROLES); // Get list of roles per user, then add to Roles as we go Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.readName(trans, name); - if(rlrd.isOK()) { - if(!rlrd.isEmpty()) { + if (rlrd.isOK()) { + if (!rlrd.isEmpty()) { // Note: Mapper will restrict what can be viewed mapper.roles(trans,rlrd.value,roles,true); } @@ -1739,7 +1739,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<ROLES> getRolesByPerm(AuthzTrans trans, String type, String instance, String action) { final Validator v = new ServiceValidator(); - if(v.permType(type) + if (v.permType(type) .permInstance(instance) .permAction(action) .err()) { @@ -1751,22 +1751,22 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE ROLES roles = mapper.newInstance(API.ROLES); // Get list of roles per user, then add to Roles as we go Result<NsSplit> nsSplit = ques.deriveNsSplit(trans, type); - if(nsSplit.isOK()) { + if (nsSplit.isOK()) { PermDAO.Data pdd = new PermDAO.Data(nsSplit.value, instance, action); Result<?> res; - if((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) { + if ((res=ques.mayUser(trans, trans.user(), pdd, Question.Access.read)).notOK()) { return Result.err(res); } Result<List<PermDAO.Data>> pdlr = ques.permDAO.read(trans, pdd); - if(pdlr.isOK())for(PermDAO.Data pd : pdlr.value) { + if (pdlr.isOK())for (PermDAO.Data pd : pdlr.value) { Result<List<RoleDAO.Data>> rlrd; - for(String r : pd.roles) { + for (String r : pd.roles) { Result<String[]> rs = RoleDAO.Data.decodeToArray(trans, ques, r); - if(rs.isOK()) { + if (rs.isOK()) { rlrd = ques.roleDAO.read(trans, rs.value[0],rs.value[1]); // Note: Mapper will restrict what can be viewed - if(rlrd.isOKhasData()) { + if (rlrd.isOKhasData()) { mapper.roles(trans,rlrd.value,roles,true); } } @@ -1792,15 +1792,15 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> updateRoleDescription(AuthzTrans trans, REQUEST from) { final Result<RoleDAO.Data> rd = mapper.role(trans, from); final ServiceValidator v = new ServiceValidator(); - if(v.role(rd).err()) { + if (v.role(rd).err()) { return Result.err(Status.ERR_BadData,v.errs()); } { - if(v.nullOrBlank("description", rd.value.description).err()) { + if (v.nullOrBlank("description", rd.value.description).err()) { return Result.err(Status.ERR_BadData,v.errs()); } } final RoleDAO.Data role = rd.value; - if(ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) { + if (ques.roleDAO.read(trans, role.ns, role.name).notOKorIsEmpty()) { return Result.err(Status.ERR_NotFound, "Role [" + role.fullName() + "] does not exist"); } @@ -1809,12 +1809,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } Result<Void> rdr = ques.roleDAO.addDescription(trans, role.ns, role.name, role.description); - if(rdr.isOK()) { + if (rdr.isOK()) { return Result.ok(); } else { return Result.err(rdr); @@ -1846,24 +1846,24 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> addPermToRole(final AuthzTrans trans, REQUEST rreq) { // Translate Request into Perm and Role Objects final Result<PermDAO.Data> rpd = mapper.permFromRPRequest(trans, rreq); - if(rpd.notOKorIsEmpty()) { + if (rpd.notOKorIsEmpty()) { return Result.err(rpd); } final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq); - if(rrd.notOKorIsEmpty()) { + if (rrd.notOKorIsEmpty()) { return Result.err(rrd); } // Validate Role and Perm values final ServiceValidator v = new ServiceValidator(); - if(v.perm(rpd.value) + if (v.perm(rpd.value) .role(rrd.value) .err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<RoleDAO.Data>> rlrd = ques.roleDAO.read(trans, rrd.value.ns, rrd.value.name); - if(rlrd.notOKorIsEmpty()) { + if (rlrd.notOKorIsEmpty()) { return Result.err(Status.ERR_RoleNotFound, "Role [%s] does not exist", rrd.value.fullName()); } @@ -1871,8 +1871,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, rpd.value.ns, rpd.value.type, rpd.value.instance, rpd.value.action); PermDAO.Data createPerm = null; // if not null, create first - if(rlpd.notOKorIsEmpty()) { // Permission doesn't exist - if(trans.requested(force)) { + if (rlpd.notOKorIsEmpty()) { // Permission doesn't exist + if (trans.requested(force)) { // Remove roles from perm data object so we just create the perm here createPerm = rpd.value; createPerm.roles.clear(); @@ -1903,14 +1903,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write); } return nsd; } }); Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rpd.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } switch(fd.status) { @@ -1920,7 +1920,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE trans.user(), nsr.value.get(0), FUTURE_OP.G); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", rpd.value.ns, rpd.value.type, @@ -1931,10 +1931,10 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } case Status.ACC_Now: Result<Void> rv = null; - if(createPerm!=null) {// has been validated for creating + if (createPerm!=null) {// has been validated for creating rv = func.createPerm(trans, createPerm, false); } - if(rv==null || rv.isOK()) { + if (rv==null || rv.isOK()) { rv = func.addPermToRole(trans, rrd.value, rpd.value, false); } return rv; @@ -1962,16 +1962,16 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> delPermFromRole(final AuthzTrans trans, REQUEST rreq) { final Result<PermDAO.Data> updt = mapper.permFromRPRequest(trans, rreq); - if(updt.notOKorIsEmpty()) { + if (updt.notOKorIsEmpty()) { return Result.err(updt); } final Result<RoleDAO.Data> rrd = mapper.roleFromRPRequest(trans, rreq); - if(rrd.notOKorIsEmpty()) { + if (rrd.notOKorIsEmpty()) { return Result.err(rrd); } final ServiceValidator v = new ServiceValidator(); - if(v.nullOrBlank(updt.value) + if (v.nullOrBlank(updt.value) .nullOrBlank(rrd.value) .err()) { return Result.err(Status.ERR_BadData,v.errs()); @@ -1984,7 +1984,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<List<PermDAO.Data>> rlpd = ques.permDAO.read(trans, pdd.ns, pdd.type, pdd.instance, pdd.action); - if(rlpd.notOKorIsEmpty()) { + if (rlpd.notOKorIsEmpty()) { return Result.err(Status.ERR_PermissionNotFound, "Permission [%s.%s|%s|%s] does not exist", pdd.ns,pdd.type,pdd.instance,pdd.action); @@ -2002,14 +2002,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { nsd = ques.mayUser(trans, trans.user(), pdd, Access.write); } return nsd; } }); Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, pdd.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } switch(fd.status) { @@ -2020,7 +2020,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE nsr.value.get(0), FUTURE_OP.UG ); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Perm [%s.%s|%s|%s] is saved for future processing", pdd.ns, pdd.type, @@ -2053,12 +2053,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> delPermFromRole(AuthzTrans trans, String role, String type, String instance, String action) { Result<Data> rpns = ques.deriveNs(trans, type); - if(rpns.notOKorIsEmpty()) { + if (rpns.notOKorIsEmpty()) { return Result.err(rpns); } final Validator v = new ServiceValidator(); - if(v.role(role) + if (v.role(role) .permType(rpns.value.name,rpns.value.parent) .permInstance(instance) .permAction(action) @@ -2067,17 +2067,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<Data> rrns = ques.deriveNs(trans, role); - if(rrns.notOKorIsEmpty()) { + if (rrns.notOKorIsEmpty()) { return Result.err(rrns); } final Result<List<RoleDAO.Data>> rrd = ques.roleDAO.read(trans, rrns.value.parent, rrns.value.name); - if(rrd.notOKorIsEmpty()) { + if (rrd.notOKorIsEmpty()) { return Result.err(rrd); } final Result<List<PermDAO.Data>> rpd = ques.permDAO.read(trans, rpns.value.parent, rpns.value.name, instance, action); - if(rpd.notOKorIsEmpty()) { + if (rpd.notOKorIsEmpty()) { return Result.err(rpd); } @@ -2097,9 +2097,9 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> deleteRole(AuthzTrans trans, String role) { Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.isOKhasData()) { + if (rrdd.isOKhasData()) { final ServiceValidator v = new ServiceValidator(); - if(v.nullOrBlank(rrdd.value).err()) { + if (v.nullOrBlank(rrdd.value).err()) { return Result.err(Status.ERR_BadData,v.errs()); } return func.deleteRole(trans, rrdd.value, false, false); @@ -2125,14 +2125,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> deleteRole(final AuthzTrans trans, REQUEST from) { final Result<RoleDAO.Data> rd = mapper.role(trans, from); final ServiceValidator v = new ServiceValidator(); - if(rd==null) { + if (rd==null) { return Result.err(Status.ERR_BadData,"Request does not contain Role"); } - if(v.nullOrBlank(rd.value).err()) { + if (v.nullOrBlank(rd.value).err()) { return Result.err(Status.ERR_BadData,v.errs()); } final RoleDAO.Data role = rd.value; - if(ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) { + if (ques.roleDAO.read(trans, role).notOKorIsEmpty() && !trans.requested(force)) { return Result.err(Status.ERR_RoleNotFound, "Role [" + role.fullName() + "] does not exist"); } @@ -2148,7 +2148,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { nsd = ques.mayUser(trans, trans.user(), role, Access.write); } return nsd; @@ -2158,13 +2158,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(fd.status) { case OK: Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rd.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } Result<String> rfc = func.createFuture(trans, fd.value, role.encode(), trans.user(),nsr.value.get(0),FUTURE_OP.D); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Role Deletion [%s.%s] is saved for future processing", rd.value.ns, rd.value.name); @@ -2196,18 +2196,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { nsd = ques.validNSOfDomain(trans, cred.id); } // is Ns of CredID valid? - if(nsd.isOK()) { + if (nsd.isOK()) { try { // Check Org Policy - if(trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) { + if (trans.org().validate(trans,Policy.CREATE_MECHID, exec, cred.id)==null) { return Result.ok(); } else { Result<?> rmc = ques.mayUser(trans, trans.user(), nsd.value, Access.write); - if(rmc.isOKhasData()) { + if (rmc.isOKhasData()) { return rmc; } } @@ -2234,21 +2234,21 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<?> mayChange() { // User can change himself (but not create) - if(trans.user().equals(cred.id)) { + if (trans.user().equals(cred.id)) { return Result.ok(); } - if(nsd==null) { + if (nsd==null) { nsd = ques.validNSOfDomain(trans, cred.id); } // Get the Namespace - if(nsd.isOK()) { - if(ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) { + if (nsd.isOK()) { + if (ques.mayUser(trans, trans.user(), nsd.value,Access.write).isOK()) { return Result.ok(); } String user[] = Split.split('.',trans.user()); - if(user.length>2) { + if (user.length>2) { String company = user[user.length-1] + '.' + user[user.length-2]; - if(ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) { + if (ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,"reset")) { return Result.ok(); } } @@ -2282,13 +2282,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE try { Result<CredDAO.Data> rcred = mapper.cred(trans, from, true); - if(rcred.isOKhasData()) { + if (rcred.isOKhasData()) { byte[] rawCred = rcred.value.cred.array(); rcred = ques.userCredSetup(trans, rcred.value); final ServiceValidator v = new ServiceValidator(); - if(v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations + if (v.cred(trans, trans.org(),rcred,true).err()) { // Note: Creates have stricter Validations return Result.err(Status.ERR_BadData,v.errs()); } @@ -2301,12 +2301,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } catch (Exception e1) { trans.error().log(e1,rcred.value.id,"cannot be validated at this time"); } - if(mechID==null || !mechID.isFound()) { + if (mechID==null || !mechID.isFound()) { return Result.err(Status.ERR_Policy,"MechIDs must be registered with %s before provisioning in AAF",org.getName()); } Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(Status.ERR_NsNotFound,"Cannot provision %s on non-existent Namespace %s",mechID.id(),rcred.value.ns); } @@ -2327,9 +2327,9 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // password to validate char differences. rb = ques.userCredCheck(trans, curr, rawCred); - if(rb.notOK()) { + if (rb.notOK()) { return Result.err(rb); - } else if(rb.value){ + } else if (rb.value){ return Result.err(Status.ERR_Policy, "Credential content cannot be reused."); } else if (Chrono.dateOnlyStamp(curr.expires).equals(Chrono.dateOnlyStamp(rcred.value.expires)) && curr.type==rcred.value.type) { return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists, use 'reset'"); @@ -2341,15 +2341,15 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE String theMechID = rcred.value.id; Boolean otherMechIDs = false; // find out if this is the only mechID. other MechIDs mean special handling (not automated) - for(CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) { - if(!cd.id.equals(theMechID)) { + for (CredDAO.Data cd : ques.credDAO.readNS(trans,nsr.value.get(0).name).value) { + if (!cd.id.equals(theMechID)) { otherMechIDs = true; break; } } String reason; // We can say "ID does not exist" here - if((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) { + if ((reason=org.validate(trans, Policy.CREATE_MECHID, exec, theMechID,trans.user(),otherMechIDs.toString()))!=null) { return Result.err(Status.ERR_Denied, reason); } firstID=true; @@ -2378,7 +2378,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<String> rfc = func.createFuture(trans, fd.value, rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, trans.user(), nsr.value.get(0), FUTURE_OP.C); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s] is saved for future processing", rcred.value.id, Integer.toString(rcred.value.type), @@ -2388,13 +2388,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } case Status.ACC_Now: try { - if(firstID) { + if (firstID) { // && !nsr.value.get(0).isAdmin(trans.getUserPrincipal().getName())) { Result<List<String>> admins = func.getAdmins(trans, nsr.value.get(0).name, false); // OK, it's a first ID, and not by NS Admin, so let's set TempPassword length // Note, we only do this on First time, because of possibility of // prematurely expiring a production id - if(admins.isOKhasData() && !admins.value.contains(trans.user())) { + if (admins.isOKhasData() && !admins.value.contains(trans.user())) { rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime(); } } @@ -2402,7 +2402,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE trans.error().log(e, "While setting expiration to TempPassword"); } Result<?>udr = ques.credDAO.create(trans, rcred.value); - if(udr.isOK()) { + if (udr.isOK()) { return Result.ok(); } return Result.err(udr); @@ -2430,17 +2430,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<USERS> getCredsByNS(AuthzTrans trans, String ns) { final Validator v = new ServiceValidator(); - if(v.ns(ns).err()) { + if (v.ns(ns).err()) { return Result.err(Status.ERR_BadData,v.errs()); } // check if user is allowed to view NS Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } @@ -2449,8 +2449,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE USERS users = mapper.newInstance(API.USERS); Result<List<CredDAO.Data>> rlcd = ques.credDAO.readNS(trans, ns); - if(rlcd.isOK()) { - if(!rlcd.isEmpty()) { + if (rlcd.isOK()) { + if (!rlcd.isEmpty()) { return mapper.cred(rlcd.value, users); } return Result.ok(users); @@ -2476,18 +2476,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<USERS> getCredsByID(AuthzTrans trans, String id) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("ID",id).err()) { + if (v.nullOrBlank("ID",id).err()) { return Result.err(Status.ERR_BadData,v.errs()); } String ns = Question.domain2ns(id); // check if user is allowed to view NS Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } @@ -2496,8 +2496,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE USERS users = mapper.newInstance(API.USERS); Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, id); - if(rlcd.isOK()) { - if(!rlcd.isEmpty()) { + if (rlcd.isOK()) { + if (!rlcd.isEmpty()) { return mapper.cred(rlcd.value, users); } return Result.ok(users); @@ -2526,8 +2526,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE CERTS certs = mapper.newInstance(API.CERTS); Result<List<CertDAO.Data>> rlcd = ques.certDAO.readID(trans, id); - if(rlcd.isOK()) { - if(!rlcd.isEmpty()) { + if (rlcd.isOK()) { + if (!rlcd.isEmpty()) { return mapper.cert(rlcd.value, certs); } return Result.ok(certs); @@ -2557,16 +2557,16 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(cmdDescription, Env.SUB); try { Result<CredDAO.Data> rcred = mapper.cred(trans, from, true); - if(rcred.isOKhasData()) { + if (rcred.isOKhasData()) { rcred = ques.userCredSetup(trans, rcred.value); final ServiceValidator v = new ServiceValidator(); - if(v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations + if (v.cred(trans, trans.org(),rcred,false).err()) {// Note: Creates have stricter Validations return Result.err(Status.ERR_BadData,v.errs()); } Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, rcred.value.id); - if(rlcd.notOKorIsEmpty()) { + if (rlcd.notOKorIsEmpty()) { return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); } @@ -2577,7 +2577,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); - if(ri.notOK()) { + if (ri.notOK()) { return Result.err(ri); } int entry = ri.value; @@ -2598,7 +2598,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE mc); Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, rcred.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } @@ -2607,7 +2607,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<String> rfc = func.createFuture(trans, fd.value, rcred.value.id + '|' + rcred.value.type.toString() + '|' + rcred.value.expires, trans.user(), nsr.value.get(0), FUTURE_OP.U); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Credential Request [%s|%s|%s]", rcred.value.id, Integer.toString(rcred.value.type), @@ -2620,7 +2620,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // If we are Resetting Password on behalf of someone else (am not the Admin) // use TempPassword Expiration time. Expiration exp; - if(ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) { + if (ques.isAdmin(trans, trans.user(), nsr.value.get(0).name)) { exp = Expiration.Password; } else { exp = Expiration.TempPassword; @@ -2642,7 +2642,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE rcred.value.notes=current.notes; udr = ques.credDAO.create(trans, rcred.value); - if(udr.isOK()) { + if (udr.isOK()) { udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); } if (udr.isOK()) { @@ -2701,7 +2701,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<CredDAO.Data> cred = mapper.cred(trans, from, false); Organization org = trans.org(); final ServiceValidator v = new ServiceValidator(); - if(v.notOK(cred).err() || + if (v.notOK(cred).err() || v.nullOrBlank(cred.value.id, "Invalid ID").err() || v.user(org,cred.value.id).err()) { return Result.err(Status.ERR_BadData,v.errs()); @@ -2720,13 +2720,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Get the list of Cred Entries Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id); - if(rlcd.notOKorIsEmpty()) { + if (rlcd.notOKorIsEmpty()) { return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); } //Need to do the "Pick Entry" mechanism Result<Integer> ri = selectEntryIfMultiple((CredRequest)from, rlcd.value); - if(ri.notOK()) { + if (ri.notOK()) { return Result.err(ri); } @@ -2742,7 +2742,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime(); cred = ques.credDAO.create(trans, cd); - if(cred.isOK()) { + if (cred.isOK()) { return Result.ok(); } return Result.err(cred); @@ -2779,7 +2779,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE errMessage.append(' '); } errMessage.append(" Type Expires" + '\n'); - for(int i=0;i<value.size();++i) { + for (int i=0;i<value.size();++i) { errMessage.append(" %s\n"); } errMessage.append("Run same command again with chosen entry as last parameter"); @@ -2803,16 +2803,16 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> deleteUserCred(AuthzTrans trans, REQUEST from) { final Result<CredDAO.Data> cred = mapper.cred(trans, from, false); final Validator v = new ServiceValidator(); - if(v.nullOrBlank("cred", cred.value.id).err()) { + if (v.nullOrBlank("cred", cred.value.id).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<CredDAO.Data>> rlcd = ques.credDAO.readID(trans, cred.value.id); - if(rlcd.notOKorIsEmpty()) { + if (rlcd.notOKorIsEmpty()) { // Empty Creds should have no user_roles. Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { ques.userRoleDAO.delete(trans, data, false); } } @@ -2827,7 +2827,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } int entry = 0; - if(!trans.requested(force)) { + if (!trans.requested(force)) { if (rlcd.value.size() > 1) { CredRequest cr = (CredRequest)from; String inputOption = cr.getEntry(); @@ -2837,11 +2837,11 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE return Result.err(Status.ERR_ChoiceNeeded, message, variables); } else { try { - if(inputOption.length()>5) { // should be a date + if (inputOption.length()>5) { // should be a date Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime(); entry = 0; - for(CredDAO.Data cd : rlcd.value) { - if(cd.type.equals(cr.getType()) && cd.expires.equals(d)) { + for (CredDAO.Data cd : rlcd.value) { + if (cd.type.equals(cr.getType()) && cd.expires.equals(d)) { break; } ++entry; @@ -2849,9 +2849,9 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } else { entry = Integer.parseInt(inputOption) - 1; } - } catch(NullPointerException e) { + } catch (NullPointerException e) { return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry"); - } catch(NumberFormatException e) { + } catch (NumberFormatException e) { return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); } } @@ -2876,7 +2876,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE mc); Result<List<NsDAO.Data>> nsr = ques.nsDAO.read(trans, cred.value.ns); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } @@ -2885,7 +2885,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<String> rfc = func.createFuture(trans, fd.value, cred.value.id, trans.user(), nsr.value.get(0), FUTURE_OP.D); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Credential Delete [%s] is saved for future processing",cred.value.id); } else { return Result.err(rfc); @@ -2893,7 +2893,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE case Status.ACC_Now: Result<?>udr = null; if (!trans.requested(force)) { - if(entry<0 || entry >= rlcd.value.size()) { + if (entry<0 || entry >= rlcd.value.size()) { return Result.err(Status.ERR_BadData,"Invalid Choice [" + entry + "] chosen for Delete [%s] is saved for future processing",cred.value.id); } udr = ques.credDAO.delete(trans, rlcd.value.get(entry),false); @@ -2905,15 +2905,15 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } } } - if(isLastCred) { + if (isLastCred) { Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, cred.value.id); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { ques.userRoleDAO.delete(trans, data, false); } } } - if(udr==null) { + if (udr==null) { return Result.err(Result.ERR_NotFound,"No User Data found"); } if (udr.isOK()) { @@ -2933,11 +2933,11 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE try { // Note: Mapper assigns RAW type Result<CredDAO.Data> data = mapper.cred(trans, credReq,false); - if(data.notOKorIsEmpty()) { + if (data.notOKorIsEmpty()) { return Result.err(data); } CredDAO.Data cred = data.value; // of the Mapped Cred - if(cred.cred==null) { + if (cred.cred==null) { return Result.err(Result.ERR_BadData,"No Password"); } else { return ques.doesUserCredMatch(trans, cred.id, cred.cred.array()); @@ -2984,7 +2984,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE BasicPrincipal bp = new BasicPrincipal(basicAuth,trans.org().getRealm()); Result<Date> rq = ques.doesUserCredMatch(trans, bp.getName(), bp.getCred()); // Note: Only want to log problem, don't want to send back to end user - if(rq.isOK()) { + if (rq.isOK()) { return rq; } else { trans.audit().log(rq.errorString()); @@ -3018,13 +3018,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start("Create UserRole", Env.SUB); try { Result<UserRoleDAO.Data> urr = mapper.userRole(trans, from); - if(urr.notOKorIsEmpty()) { + if (urr.notOKorIsEmpty()) { return Result.err(urr); } final UserRoleDAO.Data userRole = urr.value; final ServiceValidator v = new ServiceValidator(); - if(v.user_role(userRole).err() || + if (v.user_role(userRole).err() || v.user(trans.org(), userRole.user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -3045,7 +3045,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(nsd==null) { + if (nsd==null) { RoleDAO.Data r = RoleDAO.Data.decode(userRole); nsd = ques.mayUser(trans, trans.user(), r, Access.write); } @@ -3053,7 +3053,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } }); Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } @@ -3061,7 +3061,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE case OK: Result<String> rfc = func.createFuture(trans, fd.value, userRole.user+'|'+userRole.ns + '.' + userRole.rname, userRole.user, nsr.value, FUTURE_OP.C); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "UserRole [%s - %s.%s] is saved for future processing", userRole.user, userRole.ns, @@ -3094,13 +3094,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<USERROLES> getUserRolesByRole(AuthzTrans trans, String role) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role",role).err()) { + if (v.nullOrBlank("Role",role).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<RoleDAO.Data> rrdd; rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } // May Requester see result? @@ -3116,8 +3116,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Get list of roles per user, then add to Roles as we go HashSet<UserRoleDAO.Data> userSet = new HashSet<>(); Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { userSet.add(data); } } @@ -3143,13 +3143,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<USERROLES> getUserRolesByUser(AuthzTrans trans, String user) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User",user).err()) { + if (v.nullOrBlank("User",user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } // Get list of roles per user, then add to Roles as we go Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, user); - if(rlurd.notOK()) { + if (rlurd.notOK()) { return Result.err(rlurd); } @@ -3164,16 +3164,16 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE String callingUser = trans.getUserPrincipal().getName(); NsDAO.Data ndd = new NsDAO.Data(); - if(user.equals(callingUser)) { + if (user.equals(callingUser)) { mustFilter = false; } else { Organization org = trans.org(); try { Identity orgID = org.getIdentity(trans, user); Identity manager = orgID==null?null:orgID.responsibleTo(); - if(orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) { + if (orgID!=null && (manager!=null && callingUser.equals(manager.fullID()))) { mustFilter = false; - } else if(ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) { + } else if (ques.isGranted(trans, callingUser, ROOT_NS, Question.ACCESS, "*", Access.read.name())) { mustFilter=false; } else { mustFilter = true; @@ -3185,13 +3185,13 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } List<UserRoleDAO.Data> content; - if(mustFilter) { + if (mustFilter) { content = new ArrayList<>(rlurd.value.size()); // avoid multi-memory redos - for(UserRoleDAO.Data data : rlurd.value) { + for (UserRoleDAO.Data data : rlurd.value) { ndd.name=data.ns; Result<Data> mur = ques.mayUser(trans, callingUser, ndd, Access.read); - if(mur.isOK()){ + if (mur.isOK()){ content.add(data); } } @@ -3224,7 +3224,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> resetRolesForUser(AuthzTrans trans, REQUEST rreq) { Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq); final ServiceValidator v = new ServiceValidator(); - if(rurdd.notOKorIsEmpty()) { + if (rurdd.notOKorIsEmpty()) { return Result.err(rurdd); } if (v.user(trans.org(), rurdd.value.user).err()) { @@ -3233,15 +3233,15 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Set<String> currRoles = new HashSet<>(); Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByUser(trans, rurdd.value.user); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { currRoles.add(data.role); } } Result<Void> rv = null; String[] roles; - if(rurdd.value.role==null) { + if (rurdd.value.role==null) { roles = new String[0]; } else { roles = rurdd.value.role.split(","); @@ -3252,7 +3252,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE return Result.err(Status.ERR_BadData,v.errs()); } Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } @@ -3263,11 +3263,11 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE return Result.err(nsd); } Result<NsDAO.Data> nsr = ques.deriveNs(trans, role); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } - if(currRoles.contains(role)) { + if (currRoles.contains(role)) { currRoles.remove(role); } else { rv = func.addUserRole(trans, rurdd.value); @@ -3280,7 +3280,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE for (String role : currRoles) { rurdd.value.role(trans,ques,role); rv = ques.userRoleDAO.delete(trans, rurdd.value, false); - if(rv.notOK()) { + if (rv.notOK()) { trans.info().log(rurdd.value.user,"/",rurdd.value.role, "expected to be deleted, but does not exist"); // return rv; // if it doesn't exist, don't error out } @@ -3305,7 +3305,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> resetUsersForRole(AuthzTrans trans, REQUEST rreq) { Result<UserRoleDAO.Data> rurdd = mapper.userRole(trans, rreq); - if(rurdd.notOKorIsEmpty()) { + if (rurdd.notOKorIsEmpty()) { return Result.err(rurdd); } final ServiceValidator v = new ServiceValidator(); @@ -3321,14 +3321,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<NsDAO.Data> nsr = ques.deriveNs(trans, rurdd.value.role); - if(nsr.notOKorIsEmpty()) { + if (nsr.notOKorIsEmpty()) { return Result.err(nsr); } Set<String> currUsers = new HashSet<>(); Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, rurdd.value.role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { currUsers.add(data.user); } } @@ -3352,7 +3352,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } rurdd.value.user = user; - if(currUsers.contains(user)) { + if (currUsers.contains(user)) { currUsers.remove(user); } else { rv = func.addUserRole(trans, rurdd.value); @@ -3365,7 +3365,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE for (String user : currUsers) { rurdd.value.user = user; rv = ques.userRoleDAO.delete(trans, rurdd.value, false); - if(rv.notOK()) { + if (rv.notOK()) { trans.info().log(rurdd.value, "expected to be deleted, but not exists"); return rv; } @@ -3390,29 +3390,29 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> extendUserRole(AuthzTrans trans, String user, String role) { Organization org = trans.org(); final ServiceValidator v = new ServiceValidator(); - if(v.user(org, user) + if (v.user(org, user) .role(role) .err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } Result<NsDAO.Data> rcr = ques.mayUser(trans, trans.user(), rrdd.value, Access.write); boolean mayNotChange; - if((mayNotChange = rcr.notOK()) && !trans.requested(future)) { + if ((mayNotChange = rcr.notOK()) && !trans.requested(future)) { return Result.err(rcr); } Result<List<UserRoleDAO.Data>> rr = ques.userRoleDAO.read(trans, user,role); - if(rr.notOK()) { + if (rr.notOK()) { return Result.err(rr); } - for(UserRoleDAO.Data userRole : rr.value) { - if(mayNotChange) { // Function exited earlier if !trans.futureRequested + for (UserRoleDAO.Data userRole : rr.value) { + if (mayNotChange) { // Function exited earlier if !trans.futureRequested FutureDAO.Data fto = new FutureDAO.Data(); fto.target=UserRoleDAO.TABLE; fto.memo = "Extend User ["+userRole.user+"] in Role ["+userRole.role+"]"; @@ -3428,7 +3428,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<String> rfc = func.createFuture(trans, fto, userRole.user+'|'+userRole.role, userRole.user, rcr.value, FUTURE_OP.U); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", userRole.user, userRole.role); @@ -3456,14 +3456,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> deleteUserRole(AuthzTrans trans, String usr, String role) { Validator val = new ServiceValidator(); - if(val.nullOrBlank("User", usr) + if (val.nullOrBlank("User", usr) .nullOrBlank("Role", role).err()) { return Result.err(Status.ERR_BadData, val.errs()); } boolean mayNotChange; Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans,ques,role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } @@ -3471,24 +3471,24 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<NsDAO.Data> rns = ques.mayUser(trans, trans.user(), rdd, Access.write); // Make sure we don't delete the last owner of valid NS - if(rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) { + if (rns.isOKhasData() && Question.OWNER.equals(rdd.name) && ques.countOwner(trans,rdd.ns)<=1) { return Result.err(Status.ERR_Denied,"You may not delete the last Owner of " + rdd.ns ); } - if(mayNotChange=rns.notOK()) { - if(!trans.requested(future)) { + if (mayNotChange=rns.notOK()) { + if (!trans.requested(future)) { return Result.err(rns); } } Result<List<UserRoleDAO.Data>> rulr; - if((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) { + if ((rulr=ques.userRoleDAO.read(trans, usr, role)).notOKorIsEmpty()) { return Result.err(Status.ERR_UserRoleNotFound, "User [ "+usr+" ] is not " + "Assigned to the Role [ " + role + " ]"); } UserRoleDAO.Data userRole = rulr.value.get(0); - if(mayNotChange) { // Function exited earlier if !trans.futureRequested + if (mayNotChange) { // Function exited earlier if !trans.futureRequested FutureDAO.Data fto = new FutureDAO.Data(); fto.target=UserRoleDAO.TABLE; fto.memo = "Remove User ["+userRole.user+"] from Role ["+userRole.role+"]"; @@ -3498,7 +3498,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<String> rfc = func.createFuture(trans, fto, userRole.user+'|'+userRole.role, userRole.user, rns.value, FUTURE_OP.D); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "UserRole [%s - %s] is saved for future processing", userRole.user, userRole.role); @@ -3523,7 +3523,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<USERS> getUserInRole(AuthzTrans trans, String user, String role) { final Validator v = new ServiceValidator(); - if(v.role(role).nullOrBlank("User", user).err()) { + if (v.role(role).nullOrBlank("User", user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -3533,18 +3533,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); // May calling user see by virtue of the Role Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } HashSet<UserRoleDAO.Data> userSet = new HashSet<>(); Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readUserInRole(trans, user, role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { userSet.add(data); } } @@ -3568,7 +3568,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<USERS> getUsersByRole(AuthzTrans trans, String role) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role",role).err()) { + if (v.nullOrBlank("Role",role).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -3578,15 +3578,15 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), ns.value, Access.write); // May calling user see by virtue of the Role Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } boolean contactOnly = false; // Allow the request of any valid user to find the contact of the NS (Owner) Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value,Access.read); - if(rnd.notOK()) { - if(Question.OWNER.equals(rrdd.value.name)) { + if (rnd.notOK()) { + if (Question.OWNER.equals(rrdd.value.name)) { contactOnly = true; } else { return Result.err(rnd); @@ -3595,9 +3595,9 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE HashSet<UserRoleDAO.Data> userSet = new HashSet<>(); Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role); - if(rlurd.isOK()) { - for(UserRoleDAO.Data data : rlurd.value) { - if(contactOnly) { //scrub data + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { + if (contactOnly) { //scrub data // Can't change actual object, or will mess up the cache. UserRoleDAO.Data scrub = new UserRoleDAO.Data(); scrub.ns = data.ns; @@ -3635,7 +3635,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<USERS> getUsersByPermission(AuthzTrans trans, String type, String instance, String action) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Type",type) + if (v.nullOrBlank("Type",type) .nullOrBlank("Instance",instance) .nullOrBlank("Action",action) .err()) { @@ -3643,7 +3643,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<NsSplit> nss = ques.deriveNsSplit(trans, type); - if(nss.notOK()) { + if (nss.notOK()) { return Result.err(nss); } @@ -3660,19 +3660,19 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Set<String> roleUsed = new HashSet<>(); Set<UserRoleDAO.Data> userSet = new HashSet<>(); - if(!nss.isEmpty()) { + if (!nss.isEmpty()) { Result<List<PermDAO.Data>> rlp = ques.permDAO.readByType(trans, nss.value.ns, nss.value.name); - if(rlp.isOKhasData()) { - for(PermDAO.Data pd : rlp.value) { - if((allInstance || pd.instance.equals(instance)) && + if (rlp.isOKhasData()) { + for (PermDAO.Data pd : rlp.value) { + if ((allInstance || pd.instance.equals(instance)) && (allAction || pd.action.equals(action))) { - if(ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) { - for(String role : pd.roles) { - if(!roleUsed.contains(role)) { // avoid evaluating Role many times + if (ques.mayUser(trans, trans.user(),pd,Access.read).isOK()) { + for (String role : pd.roles) { + if (!roleUsed.contains(role)) { // avoid evaluating Role many times roleUsed.add(role); Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO.readByRole(trans, role.replace('|', '.')); - if(rlurd.isOKhasData()) { - for(UserRoleDAO.Data urd : rlurd.value) { + if (rlurd.isOKhasData()) { + for (UserRoleDAO.Data urd : rlurd.value) { userSet.add(urd); } } @@ -3695,37 +3695,37 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<HISTORY> getHistoryByUser(final AuthzTrans trans, String user, final int[] yyyymm, final int sort) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User",user).err()) { + if (v.nullOrBlank("User",user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<NsDAO.Data> rnd; // Users may look at their own data - if(trans.user().equals(user)) { + if (trans.user().equals(user)) { // Users may look at their own data } else { int at = user.indexOf('@'); - if(at>=0 && trans.org().getRealm().equals(user.substring(at+1))) { + if (at>=0 && trans.org().getRealm().equals(user.substring(at+1))) { NsDAO.Data nsd = new NsDAO.Data(); nsd.name = Question.domain2ns(user); rnd = ques.mayUser(trans, trans.user(), nsd, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } } else { rnd = ques.validNSOfDomain(trans, user); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } } } Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readByUser(trans, user, yyyymm); - if(resp.notOK()) { + if (resp.notOK()) { return Result.err(resp); } return mapper.history(trans, resp.value,sort); @@ -3734,21 +3734,21 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<HISTORY> getHistoryByRole(AuthzTrans trans, String role, int[] yyyymm, final int sort) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Role",role).err()) { + if (v.nullOrBlank("Role",role).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<RoleDAO.Data> rrdd = RoleDAO.Data.decode(trans, ques, role); - if(rrdd.notOK()) { + if (rrdd.notOK()) { return Result.err(rrdd); } Result<NsDAO.Data> rnd = ques.mayUser(trans, trans.user(), rrdd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, role, "role", yyyymm); - if(resp.notOK()) { + if (resp.notOK()) { return Result.err(resp); } return mapper.history(trans, resp.value,sort); @@ -3757,23 +3757,23 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<HISTORY> getHistoryByPerm(AuthzTrans trans, String type, int[] yyyymm, final int sort) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Type",type) + if (v.nullOrBlank("Type",type) .err()) { return Result.err(Status.ERR_BadData,v.errs()); } // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of") Result<NsDAO.Data> rnd = ques.deriveNs(trans,type); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, type, "perm", yyyymm); - if(resp.notOK()) { + if (resp.notOK()) { return Result.err(resp); } return mapper.history(trans, resp.value,sort); @@ -3782,22 +3782,22 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<HISTORY> getHistoryByNS(AuthzTrans trans, String ns, int[] yyyymm, final int sort) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("NS",ns) + if (v.nullOrBlank("NS",ns) .err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<NsDAO.Data> rnd = ques.deriveNs(trans,ns); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if(rnd.notOK()) { + if (rnd.notOK()) { return Result.err(rnd); } Result<List<HistoryDAO.Data>> resp = ques.historyDAO.readBySubject(trans, ns, "ns", yyyymm); - if(resp.notOK()) { + if (resp.notOK()) { return Result.err(resp); } return mapper.history(trans, resp.value,sort); @@ -3820,20 +3820,20 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<Void> createOrUpdateDelegate(final AuthzTrans trans, REQUEST base, final Access access) { final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base); final ServiceValidator v = new ServiceValidator(); - if(v.delegate(trans.org(),rd).err()) { + if (v.delegate(trans.org(),rd).err()) { return Result.err(Status.ERR_BadData,v.errs()); } final DelegateDAO.Data dd = rd.value; Result<List<DelegateDAO.Data>> ddr = ques.delegateDAO.read(trans, dd); - if(access==Access.create && ddr.isOKhasData()) { + if (access==Access.create && ddr.isOKhasData()) { return Result.err(Status.ERR_ConflictAlreadyExists, "[%s] already delegates to [%s]", dd.user, ddr.value.get(0).delegate); - } else if(access!=Access.create && ddr.notOKorIsEmpty()) { + } else if (access!=Access.create && ddr.notOKorIsEmpty()) { return Result.err(Status.ERR_NotFound, "[%s] does not have a Delegate Record to [%s].",dd.user,access.name()); } Result<Void> rv = ques.mayUser(trans, dd, access); - if(rv.notOK()) { + if (rv.notOK()) { return rv; } @@ -3864,16 +3864,16 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE case OK: Result<String> rfc = func.createFuture(trans, fd.value, dd.user, trans.user(),null, access==Access.create?FUTURE_OP.C:FUTURE_OP.U); - if(rfc.isOK()) { + if (rfc.isOK()) { return Result.err(Status.ACC_Future, "Delegate for [%s]", dd.user); } else { return Result.err(rfc); } case Status.ACC_Now: - if(access==Access.create) { + if (access==Access.create) { Result<DelegateDAO.Data> rdr = ques.delegateDAO.create(trans, dd); - if(rdr.isOK()) { + if (rdr.isOK()) { return Result.ok(); } else { return Result.err(rdr); @@ -3890,17 +3890,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> deleteDelegate(AuthzTrans trans, REQUEST base) { final Result<DelegateDAO.Data> rd = mapper.delegate(trans, base); final Validator v = new ServiceValidator(); - if(v.notOK(rd).nullOrBlank("User", rd.value.user).err()) { + if (v.notOK(rd).nullOrBlank("User", rd.value.user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<DelegateDAO.Data>> ddl; - if((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) { + if ((ddl=ques.delegateDAO.read(trans, rd.value)).notOKorIsEmpty()) { return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); } final DelegateDAO.Data dd = ddl.value.get(0); Result<Void> rv = ques.mayUser(trans, dd, Access.write); - if(rv.notOK()) { + if (rv.notOK()) { return rv; } @@ -3911,17 +3911,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE public Result<Void> deleteDelegate(AuthzTrans trans, String userName) { DelegateDAO.Data dd = new DelegateDAO.Data(); final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", userName).err()) { + if (v.nullOrBlank("User", userName).err()) { return Result.err(Status.ERR_BadData,v.errs()); } dd.user = userName; Result<List<DelegateDAO.Data>> ddl; - if((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) { + if ((ddl=ques.delegateDAO.read(trans, dd)).notOKorIsEmpty()) { return Result.err(Status.ERR_DelegateNotFound,"Cannot delete non-existent Delegate"); } dd = ddl.value.get(0); Result<Void> rv = ques.mayUser(trans, dd, Access.write); - if(rv.notOK()) { + if (rv.notOK()) { return rv; } @@ -3931,7 +3931,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<DELGS> getDelegatesByUser(AuthzTrans trans, String user) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { + if (v.nullOrBlank("User", user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } @@ -3939,7 +3939,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE ddd.user = user; ddd.delegate = null; Result<Void> rv = ques.mayUser(trans, ddd, Access.read); - if(rv.notOK()) { + if (rv.notOK()) { return Result.err(rv); } @@ -3960,14 +3960,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<DELGS> getDelegatesByDelegate(AuthzTrans trans, String delegate) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Delegate", delegate).err()) { + if (v.nullOrBlank("Delegate", delegate).err()) { return Result.err(Status.ERR_BadData,v.errs()); } DelegateDAO.Data ddd = new DelegateDAO.Data(); ddd.user = delegate; Result<Void> rv = ques.mayUser(trans, ddd, Access.read); - if(rv.notOK()) { + if (rv.notOK()) { return Result.err(rv); } @@ -3992,11 +3992,11 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<Void> updateApproval(AuthzTrans trans, APPROVALS approvals) { Result<List<ApprovalDAO.Data>> rlad = mapper.approvals(approvals); - if(rlad.notOK()) { + if (rlad.notOK()) { return Result.err(rlad); } int numApprs = rlad.value.size(); - if(numApprs<1) { + if (numApprs<1) { return Result.err(Status.ERR_NoApprovals,"No Approvals sent for Updating"); } int numProcessed = 0; @@ -4004,10 +4004,10 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<List<ApprovalDAO.Data>> curr; Lookup<List<ApprovalDAO.Data>> apprByTicket=null; - for(ApprovalDAO.Data updt : rlad.value) { - if(updt.ticket!=null) { + for (ApprovalDAO.Data updt : rlad.value) { + if (updt.ticket!=null) { curr = ques.approvalDAO.readByTicket(trans, updt.ticket); - if(curr.isOKhasData()) { + if (curr.isOKhasData()) { final List<ApprovalDAO.Data> add = curr.value; apprByTicket = new Lookup<List<ApprovalDAO.Data>>() { // Store a Pre-Lookup @Override @@ -4016,29 +4016,29 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } }; } - } else if(updt.id!=null) { + } else if (updt.id!=null) { curr = ques.approvalDAO.read(trans, updt); - } else if(updt.approver!=null) { + } else if (updt.approver!=null) { curr = ques.approvalDAO.readByApprover(trans, updt.approver); } else { return Result.err(Status.ERR_BadData,"Approvals need ID, Ticket or Approval data to update"); } - if(curr.isOKhasData()) { + if (curr.isOKhasData()) { Map<String, Result<List<DelegateDAO.Data>>> delegateCache = new HashMap<>(); Map<UUID, FutureDAO.Data> futureCache = new HashMap<>(); FutureDAO.Data hasDeleted = new FutureDAO.Data(); - for(ApprovalDAO.Data cd : curr.value) { - if("pending".equals(cd.status)) { + for (ApprovalDAO.Data cd : curr.value) { + if ("pending".equals(cd.status)) { // Check for right record. Need ID, or (Ticket&Trans.User==Appr) // If Default ID boolean delegatedAction = ques.isDelegated(trans, user, cd.approver, delegateCache); String delegator = cd.approver; - if(updt.id!=null || + if (updt.id!=null || (updt.ticket!=null && user.equals(cd.approver)) || (updt.ticket!=null && delegatedAction)) { - if(updt.ticket.equals(cd.ticket)) { + if (updt.ticket.equals(cd.ticket)) { Changed ch = new Changed(); cd.id = ch.changed(cd.id,updt.id); // cd.ticket = changed(cd.ticket,updt.ticket); @@ -4049,29 +4049,29 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE cd.memo = ch.changed(cd.memo,updt.memo); cd.operation = ch.changed(cd.operation,updt.operation); cd.updated = ch.changed(cd.updated,updt.updated==null?new Date():updt.updated); - if(updt.status.equals("denied")) { + if (updt.status.equals("denied")) { cd.last_notified = null; } - if(cd.ticket!=null) { + if (cd.ticket!=null) { FutureDAO.Data fdd = futureCache.get(cd.ticket); - if(fdd==null) { // haven't processed ticket yet + if (fdd==null) { // haven't processed ticket yet Result<FutureDAO.Data> rfdd = ques.futureDAO.readPrimKey(trans, cd.ticket); - if(rfdd.isOK()) { + if (rfdd.isOK()) { fdd = rfdd.value; // null is ok } else { fdd = hasDeleted; } futureCache.put(cd.ticket, fdd); // processed this Ticket... don't do others on this ticket } - if(fdd==hasDeleted) { // YES, by Object + if (fdd==hasDeleted) { // YES, by Object cd.ticket = null; cd.status = "ticketDeleted"; ch.hasChanged(true); } else { FUTURE_OP fop = FUTURE_OP.toFO(cd.operation); - if(fop==null) { + if (fop==null) { trans.info().printf("Approval Status %s is not actionable",cd.status); - } else if(apprByTicket!=null) { + } else if (apprByTicket!=null) { Result<OP_STATUS> rv = func.performFutureOp(trans, fop, fdd, apprByTicket,func.urDBLookup); if (rv.isOK()) { switch(rv.value) { @@ -4097,7 +4097,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } ++numProcessed; } - if(ch.hasChanged()) { + if (ch.hasChanged()) { ques.approvalDAO.update(trans, cd, true); } } @@ -4107,7 +4107,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } } - if(numApprs==numProcessed) { + if (numApprs==numProcessed) { return Result.ok(); } return Result.err(Status.ERR_ActionNotCompleted,numProcessed + " out of " + numApprs + " completed"); @@ -4118,7 +4118,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private boolean hasChanged = false; public<T> T changed(T src, T proposed) { - if(proposed==null || (src!=null && src.equals(proposed))) { + if (proposed==null || (src!=null && src.equals(proposed))) { return src; } hasChanged=true; @@ -4137,12 +4137,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<APPROVALS> getApprovalsByUser(AuthzTrans trans, String user) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("User", user).err()) { + if (v.nullOrBlank("User", user).err()) { return Result.err(Status.ERR_BadData,v.errs()); } Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByUser(trans, user); - if(rapd.isOK()) { + if (rapd.isOK()) { return mapper.approvals(rapd.value); } else { return Result.err(rapd); @@ -4152,7 +4152,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<APPROVALS> getApprovalsByTicket(AuthzTrans trans, String ticket) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Ticket", ticket).err()) { + if (v.nullOrBlank("Ticket", ticket).err()) { return Result.err(Status.ERR_BadData,v.errs()); } UUID uuid; @@ -4163,7 +4163,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } Result<List<ApprovalDAO.Data>> rapd = ques.approvalDAO.readByTicket(trans, uuid); - if(rapd.isOK()) { + if (rapd.isOK()) { return mapper.approvals(rapd.value); } else { return Result.err(rapd); @@ -4173,14 +4173,14 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<APPROVALS> getApprovalsByApprover(AuthzTrans trans, String approver) { final Validator v = new ServiceValidator(); - if(v.nullOrBlank("Approver", approver).err()) { + if (v.nullOrBlank("Approver", approver).err()) { return Result.err(Status.ERR_BadData,v.errs()); } List<ApprovalDAO.Data> listRapds = new ArrayList<>(); Result<List<ApprovalDAO.Data>> myRapd = ques.approvalDAO.readByApprover(trans, approver); - if(myRapd.notOK()) { + if (myRapd.notOK()) { return Result.err(myRapd); } @@ -4211,7 +4211,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE */ @Override public Result<Void> cacheClear(AuthzTrans trans, String cname) { - if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { + if (ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { return ques.clearCache(trans,cname); } return Result.err(Status.ERR_Denied, "%s does not have AAF Permission '%s.%s|%s|clear", @@ -4223,12 +4223,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE */ @Override public Result<Void> cacheClear(AuthzTrans trans, String cname, int[] segment) { - if(ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { + if (ques.isGranted(trans,trans.user(),ROOT_NS,CACHE,cname,"clear")) { Result<Void> v=null; - for(int i: segment) { + for (int i: segment) { v=ques.cacheClear(trans,cname,i); } - if(v!=null) { + if (v!=null) { return v; } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java index 5213a6e9..70d131a5 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Api.java @@ -58,7 +58,7 @@ public class API_Api { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.getAPI(trans,resp,authzAPI); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -80,7 +80,7 @@ public class API_Api { Result<Void> r = context.getAPIExample(trans,resp,nameOrContextType, question>=0 && "optional=true".equalsIgnoreCase(req.getPathInfo().substring(question+1)) ); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java index c0836038..7c74be1b 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Approval.java @@ -49,7 +49,7 @@ public class API_Approval { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.getApprovalsByUser(trans, resp, pathParam(req,"user")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -64,7 +64,7 @@ public class API_Approval { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.getApprovalsByTicket(trans, resp, pathParam(req,"ticket")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -79,7 +79,7 @@ public class API_Approval { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.getApprovalsByApprover(trans, resp, pathParam(req,"approver")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -95,7 +95,7 @@ public class API_Approval { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.updateApproval(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java index 68e0f145..a8830c93 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Creds.java @@ -91,13 +91,13 @@ public class API_Creds { } else if (p instanceof X509Principal) { // have to check Basic Auth here, because it might be CSP. String authz = req.getHeader("Authorization"); - if(authz.startsWith("Basic ")) { + if (authz.startsWith("Basic ")) { BasicHttpTaf bht = ((X509Principal)p).getBasicHttpTaf(); - if(bht!=null) { + if (bht!=null) { BasicPrincipal bp = new BasicPrincipal(authz,""); CredVal cv = bht.getCredVal(bp.getDomain()); - if(cv!=null) { - if(cv.validate(bp.getName(), Type.PASSWORD, bp.getCred(), null) ) { + if (cv!=null) { + if (cv.validate(bp.getName(), Type.PASSWORD, bp.getCred(), null) ) { resp.setStatus(HttpStatus.OK_200); } else { resp.setStatus(HttpStatus.FORBIDDEN_403); @@ -108,7 +108,7 @@ public class API_Creds { int colon = decoded.indexOf(':'); TimeTaken tt = trans.start("Direct Validation", Env.REMOTE); try { - if(directAAFUserPass.validate( + if (directAAFUserPass.validate( decoded.substring(0,colon), CredVal.Type.PASSWORD , decoded.substring(colon+1).getBytes(),trans)) { @@ -124,7 +124,7 @@ public class API_Creds { } } } - } else if(p == null) { + } else if (p == null) { trans.error().log("Transaction not Authenticated... no Principal"); resp.setStatus(HttpStatus.FORBIDDEN_403); } else { @@ -146,7 +146,7 @@ public class API_Creds { HttpServletResponse resp) throws Exception { Result<Date> r = context.doesCredentialMatch(trans, req, resp); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { // For Security, we don't give any info out on why failed, other than forbidden @@ -167,7 +167,7 @@ public class API_Creds { HttpServletResponse resp) throws Exception { Result<Void> r = context.getCertInfoByID(trans, req, resp, pathParam(req,":id") ); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { // For Security, we don't give any info out on why failed, other than forbidden @@ -195,7 +195,7 @@ public class API_Creds { authzAPI.route(POST,"/authn/cred",API.CRED_REQ,new Code(facade,"Add a New ID/Credential", true) { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.createUserCred(trans, req); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.CREATED_201); } else { context.error(trans,resp,r); @@ -214,7 +214,7 @@ public class API_Creds { HttpServletResponse resp) throws Exception { Result<Void> r = context.getCredsByNS(trans, resp, pathParam(req, "ns")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -234,7 +234,7 @@ public class API_Creds { HttpServletResponse resp) throws Exception { Result<Void> r = context.getCredsByID(trans, resp, pathParam(req, "id")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -252,7 +252,7 @@ public class API_Creds { public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.changeUserCred(trans, req); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -273,7 +273,7 @@ public class API_Creds { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.extendUserCred(trans, req, pathParam(req, "days")); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); @@ -288,7 +288,7 @@ public class API_Creds { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { Result<Void> r = context.deleteUserCred(trans, req); - if(r.isOK()) { + if (r.isOK()) { resp.setStatus(HttpStatus.OK_200); } else { context.error(trans,resp,r); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java index e0911937..2c868d3d 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_History.java @@ -74,7 +74,7 @@ public class API_History { try { years = getYears(req); descend = decending(req); - } catch(Exception e) { + } catch (Exception e) { context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); return; } @@ -101,7 +101,7 @@ public class API_History { try { years = getYears(req); descend = decending(req); - } catch(Exception e) { + } catch (Exception e) { context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); return; } @@ -128,7 +128,7 @@ public class API_History { try { years = getYears(req); descend = decending(req); - } catch(Exception e) { + } catch (Exception e) { context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); return; } @@ -155,7 +155,7 @@ public class API_History { try { years = getYears(req); descend = decending(req); - } catch(Exception e) { + } catch (Exception e) { context.error(trans, resp, Result.err(Status.ERR_BadData, e.getMessage())); return; } @@ -174,8 +174,8 @@ public class API_History { // Check if Ascending private static int decending(HttpServletRequest req) { - if("true".equalsIgnoreCase(req.getParameter("desc")))return -1; - if("true".equalsIgnoreCase(req.getParameter("asc")))return 1; + if ("true".equalsIgnoreCase(req.getParameter("desc")))return -1; + if ("true".equalsIgnoreCase(req.getParameter("asc")))return 1; return 0; } @@ -186,21 +186,21 @@ public class API_History { SimpleDateFormat FMT = new SimpleDateFormat("yyyyMM"); String yyyymm = req.getParameter("yyyymm"); ArrayList<Integer> ai= new ArrayList<>(); - if(yyyymm==null) { + if (yyyymm==null) { GregorianCalendar gc = new GregorianCalendar(); // three months is the default - for(int i=0;i<3;++i) { + for (int i=0;i<3;++i) { ai.add(Integer.parseInt(FMT.format(gc.getTime()))); gc.add(GregorianCalendar.MONTH, -1); } } else { - for(String ym : yyyymm.split(",")) { + for (String ym : yyyymm.split(",")) { String range[] = ym.split("\\s*-\\s*"); switch(range.length) { case 0: break; case 1: - if(!ym.endsWith("-")) { + if (!ym.endsWith("-")) { ai.add(getNum(ym)); break; } else { @@ -214,26 +214,26 @@ public class API_History { gc.set(GregorianCalendar.MONTH, Integer.parseInt(range[0].substring(4,6))-1); gc.set(GregorianCalendar.YEAR, Integer.parseInt(range[0].substring(0,4))); - for(int i=getNum(FMT.format(gc.getTime()));i<=end;gc.add(GregorianCalendar.MONTH, 1),i=getNum(FMT.format(gc.getTime()))) { + for (int i=getNum(FMT.format(gc.getTime()));i<=end;gc.add(GregorianCalendar.MONTH, 1),i=getNum(FMT.format(gc.getTime()))) { ai.add(i); } } } } - if(ai.size()==0) { + if (ai.size()==0) { throw new NumberFormatException(yyyymm + " is an invalid number or range"); } Collections.sort(ai); int ym[] = new int[ai.size()]; - for(int i=0;i<ym.length;++i) { + for (int i=0;i<ym.length;++i) { ym[i]=ai.get(i); } return ym; } private static int getNum(String n) { - if(n==null || n.length()!=6) throw new NumberFormatException(n + " is not in YYYYMM format"); + if (n==null || n.length()!=6) throw new NumberFormatException(n + " is not in YYYYMM format"); return Integer.parseInt(n); } } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Mgmt.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Mgmt.java index be608df5..d99e1ada 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Mgmt.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Mgmt.java @@ -109,7 +109,7 @@ public class API_Mgmt { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { try { - if(req.isUserInRole(PERM_DB_POOL_CLEAR)) { + if (req.isUserInRole(PERM_DB_POOL_CLEAR)) { context.dbReset(trans); trans.audit().log("DB Sessions have been cleared by "+trans.user()); @@ -119,7 +119,7 @@ public class API_Mgmt { return; } context.error(trans,resp,Result.err(Result.ERR_Denied,"%s is not allowed to clear dbsessions",trans.user())); - } catch(Exception e) { + } catch (Exception e) { trans.error().log(e, "clearing dbsession"); context.error(trans,resp,Result.err(e)); } @@ -133,8 +133,8 @@ public class API_Mgmt { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String ip = pathParam(req,":ip"); - if(req.isUserInRole(PERM_DENY_IP)) { - if(DenialOfServiceTaf.denyIP(ip)) { + if (req.isUserInRole(PERM_DENY_IP)) { + if (DenialOfServiceTaf.denyIP(ip)) { trans.audit().log(ip+" has been set to deny by "+trans.user()); trans.checkpoint(SUCCESS,Trans.ALWAYS); @@ -158,8 +158,8 @@ public class API_Mgmt { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String ip = pathParam(req,":ip"); - if(req.isUserInRole(PERM_DENY_IP)) { - if(DenialOfServiceTaf.removeDenyIP(ip)) { + if (req.isUserInRole(PERM_DENY_IP)) { + if (DenialOfServiceTaf.removeDenyIP(ip)) { trans.audit().log(ip+" has been removed from denial by "+trans.user()); trans.checkpoint(SUCCESS,Trans.ALWAYS); resp.setStatus(HttpStatus.OK_200); @@ -182,8 +182,8 @@ public class API_Mgmt { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_DENY_ID)) { - if(DenialOfServiceTaf.denyID(id)) { + if (req.isUserInRole(PERM_DENY_ID)) { + if (DenialOfServiceTaf.denyID(id)) { trans.audit().log(id+" has been set to deny by "+trans.user()); trans.checkpoint(SUCCESS,Trans.ALWAYS); resp.setStatus(HttpStatus.CREATED_201); @@ -206,8 +206,8 @@ public class API_Mgmt { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_DENY_ID)) { - if(DenialOfServiceTaf.removeDenyID(id)) { + if (req.isUserInRole(PERM_DENY_ID)) { + if (DenialOfServiceTaf.removeDenyID(id)) { trans.audit().log(id+" has been removed from denial by " + trans.user()); trans.checkpoint(SUCCESS,Trans.ALWAYS); resp.setStatus(HttpStatus.OK_200); @@ -230,8 +230,8 @@ public class API_Mgmt { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_LOG_ID)) { - if(Question.specialLogOn(trans,id)) { + if (req.isUserInRole(PERM_LOG_ID)) { + if (Question.specialLogOn(trans,id)) { trans.audit().log(id+" has been set to special Log by "+trans.user()); trans.checkpoint(SUCCESS,Trans.ALWAYS); resp.setStatus(HttpStatus.CREATED_201); @@ -254,8 +254,8 @@ public class API_Mgmt { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { String id = pathParam(req,":id"); - if(req.isUserInRole(PERM_LOG_ID)) { - if(Question.specialLogOff(trans,id)) { + if (req.isUserInRole(PERM_LOG_ID)) { + if (Question.specialLogOff(trans,id)) { trans.audit().log(id+" has been removed from special Logging by " + trans.user()); trans.checkpoint(SUCCESS,Trans.ALWAYS); resp.setStatus(HttpStatus.OK_200); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java index 5f2a823e..ae94553c 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_Perms.java @@ -55,7 +55,7 @@ public class API_Perms { String scopes = req.getParameter("scopes"); Result<Void> r; - if(scopes==null) { + if (scopes==null) { r = context.getPermsByUser(trans, resp, pathParam(req, "user")); } else { r = context.getPermsByUserScope(trans, resp, pathParam(req, "user"),Split.split(':', scopes)); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java index 0e1479c4..1a016be6 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacadeImpl.java @@ -169,7 +169,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE String msgId; String[] detail; boolean hidemsg = false; - if(result.variables==null) { + if (result.variables==null) { detail = new String[1]; } else { int l = result.variables.length; @@ -307,7 +307,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE "] " + holder.toString(), Env.ALWAYS); - if(hidemsg) { + if (hidemsg) { holder.setLength(0); em = mapper().errorFromMessage(holder, msgId, "Server had an issue processing this request"); } @@ -344,11 +344,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST request; try { Data<REQUEST> rd = nsRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,rd.asString()); } request = rd.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,CREATE_NS); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -476,7 +476,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -505,7 +505,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -534,7 +534,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -564,7 +564,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -593,7 +593,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<NSS> data = nssDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -617,11 +617,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = nsRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,UPDATE_NS_DESC); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -706,7 +706,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<KEYS> data = keysDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -799,11 +799,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,CREATE_PERMISSION); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -836,7 +836,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -866,7 +866,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -895,7 +895,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -924,7 +924,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -954,11 +954,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE PERMS perms; try { RosettaData<PERMS> data = permsDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } perms = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,GET_PERMISSIONS_BY_USER_WITH_QUERY); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -967,7 +967,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -997,7 +997,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1023,7 +1023,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<PERMS> data = permsDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1054,11 +1054,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,cmdDescription); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -1086,11 +1086,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,UPDATE_PERM_DESC); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -1119,11 +1119,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN, SET_PERMISSION_ROLES_TO); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -1152,11 +1152,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = permRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,DELETE_PERMISSION); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -1218,11 +1218,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,CREATE_ROLE); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -1254,7 +1254,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1283,7 +1283,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1311,9 +1311,9 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<ROLES> rp = service.getRolesByNS(trans, ns); switch(rp.status) { case OK: - if(!rp.isEmpty()) { + if (!rp.isEmpty()) { RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1345,9 +1345,9 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Result<ROLES> rp = service.getRolesByNameOnly(trans, nameOnly); switch(rp.status) { case OK: - if(!rp.isEmpty()) { + if (!rp.isEmpty()) { RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1379,7 +1379,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<ROLES> data = roleDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1408,11 +1408,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,UPDATE_ROLE_DESC); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -1440,11 +1440,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,ADD_PERM_TO_ROLE); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -1473,11 +1473,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = rolePermRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,DELETE_PERM_FROM_ROLE); return Result.err(Status.ERR_BadData,"Invalid Input"); @@ -1551,11 +1551,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = roleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN,CREATE_ROLE); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -1596,11 +1596,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(CREATE_CRED, Env.SUB|Env.ALWAYS); try { RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } return service.createUserCred(trans, data.asObject()); - } catch(APIException e) { + } catch (APIException e) { trans.error().log(e,"Bad Input data"); return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); } catch (Exception e) { @@ -1616,12 +1616,12 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(UPDATE_CRED, Env.SUB|Env.ALWAYS); try { RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } return service.changeUserCred(trans, data.asObject()); - } catch(APIException e) { + } catch (APIException e) { trans.error().log(e,"Bad Input data"); return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); } catch (Exception e) { @@ -1640,12 +1640,12 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(EXTEND_CRED, Env.SUB|Env.ALWAYS); try { RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } return service.extendUserCred(trans, data.asObject(), days); - } catch(APIException e) { + } catch (APIException e) { trans.error().log(e,"Bad Input data"); return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); } catch (Exception e) { @@ -1665,7 +1665,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(ru.status) { case OK: RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans,trans.user())) { + if (Question.willSpecialLog(trans,trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1696,7 +1696,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(ru.status) { case OK: RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1719,12 +1719,12 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(DELETE_CRED, Env.SUB|Env.ALWAYS); try { RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } return service.deleteUserCred(trans, data.asObject()); - } catch(APIException e) { + } catch (APIException e) { trans.error().log(e,"Bad Input data"); return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); } catch (Exception e) { @@ -1741,12 +1741,12 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(DOES_CRED_MATCH, Env.SUB|Env.ALWAYS); try { RosettaData<REQUEST> data = credRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } return service.doesCredentialMatch(trans, data.asObject()); - } catch(APIException e) { + } catch (APIException e) { trans.error().log(e,"Bad Input data"); return Result.err(Status.ERR_BadData, e.getLocalizedMessage()); } catch (IOException e) { @@ -1788,7 +1788,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rci.status) { case OK: - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { RosettaData<CERTS> data = certsDF.newData(trans).load(rci.value); Question.logEncryptTrace(trans,data.asString()); data.to(resp.getOutputStream()); @@ -1819,7 +1819,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(CREATE_DELEGATE, Env.SUB|Env.ALWAYS); try { Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -1837,7 +1837,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(UPDATE_DELEGATE, Env.SUB|Env.ALWAYS); try { Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -1855,7 +1855,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(DELETE_DELEGATE, Env.SUB|Env.ALWAYS); try { Data<REQUEST> data = delgRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -1890,7 +1890,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rd.status) { case OK: RosettaData<DELGS> data = delgDF.newData(trans).load(rd.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1915,7 +1915,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rd.status) { case OK: RosettaData<DELGS> data = delgDF.newData(trans).load(rd.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -1947,12 +1947,12 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST request; try { Data<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } request = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -1980,7 +1980,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(ru.status) { case OK: RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2008,7 +2008,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(ru.status) { case OK: RosettaData<USERROLES> data = userrolesDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2036,7 +2036,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(ru.status) { case OK: RosettaData<USERROLES> data = userrolesDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2064,11 +2064,11 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN, SET_USERS_FOR_ROLE); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -2098,12 +2098,12 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE REQUEST rreq; try { RosettaData<REQUEST> data = userRoleRequestDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } rreq = data.asObject(); - } catch(APIException e) { + } catch (APIException e) { trans.error().log("Invalid Input",IN, SET_ROLES_FOR_USER); return Result.err(Status.ERR_BadData,"Invalid Input"); } @@ -2172,7 +2172,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE TimeTaken tt = trans.start(UPDATE_APPROVAL, Env.SUB|Env.ALWAYS); try { Data<APPROVALS> data = approvalDF.newData().load(req.getInputStream()); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2201,7 +2201,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } data.to(resp.getOutputStream()); @@ -2227,7 +2227,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2253,7 +2253,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rp.status) { case OK: RosettaData<APPROVALS> data = approvalDF.newData(trans).load(rp.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2287,7 +2287,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(ru.status) { case OK: RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2317,7 +2317,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(ru.status) { case OK: RosettaData<USERS> data = usersDF.newData(trans).load(ru.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2351,8 +2351,8 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE sb.append(user); sb.append(" for "); boolean first = true; - for(int i : yyyymm) { - if(first) { + for (int i : yyyymm) { + if (first) { first = false; } else { sb.append(','); @@ -2366,7 +2366,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rh.status) { case OK: RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2395,8 +2395,8 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE sb.append(role); sb.append(" for "); boolean first = true; - for(int i : yyyymm) { - if(first) { + for (int i : yyyymm) { + if (first) { first = false; } else { sb.append(','); @@ -2409,7 +2409,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rh.status) { case OK: RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2438,8 +2438,8 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE sb.append(ns); sb.append(" for "); boolean first = true; - for(int i : yyyymm) { - if(first) { + for (int i : yyyymm) { + if (first) { first = false; } else { sb.append(','); @@ -2452,7 +2452,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rh.status) { case OK: RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2481,8 +2481,8 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE sb.append(perm); sb.append(" for "); boolean first = true; - for(int i : yyyymm) { - if(first) { + for (int i : yyyymm) { + if (first) { first = false; } else { sb.append(','); @@ -2495,7 +2495,7 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE switch(rh.status) { case OK: RosettaData<HISTORY> data = historyDF.newData(trans).load(rh.value); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } @@ -2541,10 +2541,10 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE try { String[] segs = segments.split("\\s*,\\s*"); int isegs[] = new int[segs.length]; - for(int i=0;i<segs.length;++i) { + for (int i=0;i<segs.length;++i) { try { isegs[i] = Integer.parseInt(segs[i]); - } catch(NumberFormatException nfe) { + } catch (NumberFormatException nfe) { isegs[i] = -1; } } @@ -2576,32 +2576,32 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE Api api = new Api(); Api.Route ar; Method[] meths = AuthzCassServiceImpl.class.getDeclaredMethods(); - for(RouteReport rr : rservlet.routeReport()) { + for (RouteReport rr : rservlet.routeReport()) { api.getRoute().add(ar = new Api.Route()); ar.setMeth(rr.meth.name()); ar.setPath(rr.path); ar.setDesc(rr.desc); ar.getContentType().addAll(rr.contextTypes); - for(Method m : meths) { + for (Method m : meths) { ApiDoc ad; - if((ad = m.getAnnotation(ApiDoc.class))!=null && + if ((ad = m.getAnnotation(ApiDoc.class))!=null && rr.meth.equals(ad.method()) && rr.path.equals(ad.path())) { - for(String param : ad.params()) { + for (String param : ad.params()) { ar.getParam().add(param); } - for(String text : ad.text()) { + for (String text : ad.text()) { ar.getComments().add(text); } ar.setExpected(ad.expectedCode()); - for(int ec : ad.errorCodes()) { + for (int ec : ad.errorCodes()) { ar.getExplicitErr().add(ec); } } } } RosettaData<Api> data = apiDF.newData(trans).load(api); - if(Question.willSpecialLog(trans, trans.user())) { + if (Question.willSpecialLog(trans, trans.user())) { Question.logEncryptTrace(trans,data.asString()); } diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java index 5f6f30e4..55c3bc86 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/mapper/Mapper_2_0.java @@ -117,10 +117,10 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo trans.checkpoint(namespace.name, Env.ALWAYS); NsType nt = NsType.fromString(from.getType()); - if(nt.equals(NsType.UNKNOWN)) { + if (nt.equals(NsType.UNKNOWN)) { String ns = namespace.name; int count = 0; - for(int i=ns.indexOf('.'); + for (int i=ns.indexOf('.'); i>=0; i=ns.indexOf('.',i+1)) { ++count; @@ -141,10 +141,10 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo List<Ns> nss = to.getNs(); Ns ns = new Ns(); ns.setName(from.name); - if(from.admin!=null)ns.getAdmin().addAll(from.admin); - if(from.owner!=null)ns.getResponsible().addAll(from.owner); - if(from.attrib!=null) { - for(Pair<String,String> attrib : from.attrib) { + if (from.admin!=null)ns.getAdmin().addAll(from.admin); + if (from.owner!=null)ns.getResponsible().addAll(from.owner); + if (from.attrib!=null) { + for (Pair<String,String> attrib : from.attrib) { Ns.Attrib toAttrib = new Ns.Attrib(); toAttrib.setKey(attrib.x); toAttrib.setValue(attrib.y); @@ -163,18 +163,18 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo @Override public Result<Nss> nss(AuthzTrans trans, Collection<Namespace> from, Nss to) { List<Ns> nss = to.getNs(); - for(Namespace nd : from) { + for (Namespace nd : from) { Ns ns = new Ns(); ns.setName(nd.name); - if(nd.admin!=null) { + if (nd.admin!=null) { ns.getAdmin().addAll(nd.admin); } - if(nd.owner!=null) { + if (nd.owner!=null) { ns.getResponsible().addAll(nd.owner); } ns.setDescription(nd.description); - if(nd.attrib!=null) { - for(Pair<String,String> attrib : nd.attrib) { + if (nd.attrib!=null) { + for (Pair<String,String> attrib : nd.attrib) { Ns.Attrib toAttrib = new Ns.Attrib(); toAttrib.setKey(attrib.x); toAttrib.setValue(attrib.y); @@ -193,18 +193,18 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo final boolean addNS = trans.requested(REQD_TYPE.ns); TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); try { - if(from!=null) { + if (from!=null) { for (PermDAO.Data data : from) { - if(!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK()) { + if (!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK()) { Perm perm = new Perm(); perm.setType(data.fullType()); perm.setInstance(data.instance); perm.setAction(data.action); perm.setDescription(data.description); - if(addNS) { + if (addNS) { perm.setNs(data.ns); } - for(String role : data.roles(false)) { + for (String role : data.roles(false)) { perm.getRoles().add(role); } perms.add(perm); @@ -242,21 +242,21 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo List<Perm> perms = to.getPerm(); TimeTaken tt = trans.start("Filter Perms before return", Env.SUB); try { - if(from!=null) { + if (from!=null) { boolean inNSS; for (PermDAO.Data data : from) { inNSS=false; - for(int i=0;!inNSS && i<nss.length;++i) { - if(nss[i].equals(data.ns)) { + for (int i=0;!inNSS && i<nss.length;++i) { + if (nss[i].equals(data.ns)) { inNSS=true; } } - if(inNSS && (!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK())) { + if (inNSS && (!filter || q.mayUser(trans, trans.user(), data, Access.read).isOK())) { Perm perm = new Perm(); perm.setType(data.fullType()); perm.setInstance(data.instance); perm.setAction(data.action); - for(String role : data.roles(false)) { + for (String role : data.roles(false)) { perm.getRoles().add(role); } perm.setDescription(data.description); @@ -296,7 +296,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo for (Perm p : perms.getPerm()) { Result<NsSplit> nss = q.deriveNsSplit(trans, p.getType()); PermDAO.Data pd = new PermDAO.Data(); - if(nss.isOK()) { + if (nss.isOK()) { pd.ns=nss.value.ns; pd.type = nss.value.name; pd.instance = p.getInstance(); @@ -322,10 +322,10 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo public Result<PermDAO.Data> permFromRPRequest(AuthzTrans trans, Request req) { RolePermRequest from = (RolePermRequest)req; Pkey perm = from.getPerm(); - if(perm==null)return Result.err(Status.ERR_NotFound, "Permission not found"); + if (perm==null)return Result.err(Status.ERR_NotFound, "Permission not found"); Result<NsSplit> nss = q.deriveNsSplit(trans, perm.getType()); PermDAO.Data pd = new PermDAO.Data(); - if(nss.isOK()) { + if (nss.isOK()) { pd.ns=nss.value.ns; pd.type = nss.value.name; pd.instance = from.getPerm().getInstance(); @@ -351,7 +351,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo RolePermRequest from = (RolePermRequest)req; Result<NsSplit> nss = q.deriveNsSplit(trans, from.getRole()); RoleDAO.Data rd = new RoleDAO.Data(); - if(nss.isOK()) { + if (nss.isOK()) { rd.ns = nss.value.ns; rd.name = nss.value.name; trans.checkpoint(rd.fullName(), Env.ALWAYS); @@ -366,7 +366,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo PermRequest from = (PermRequest)req; Result<NsSplit> nss = q.deriveNsSplit(trans, from.getType()); PermDAO.Data pd = new PermDAO.Data(); - if(nss.isOK()) { + if (nss.isOK()) { pd.ns=nss.value.ns; pd.type = nss.value.name; pd.instance = from.getInstance(); @@ -396,7 +396,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo public Result<RoleDAO.Data> role(AuthzTrans trans, Request base) { RoleRequest from = (RoleRequest)base; Result<NsSplit> nss = q.deriveNsSplit(trans, from.getName()); - if(nss.isOK()) { + if (nss.isOK()) { RoleDAO.Data to = new RoleDAO.Data(); to.ns = nss.value.ns; to.name = nss.value.name; @@ -415,18 +415,18 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo @Override public Result<Roles> roles(AuthzTrans trans, List<RoleDAO.Data> from, Roles to, boolean filter) { final boolean needNS = trans.requested(REQD_TYPE.ns); - for(RoleDAO.Data frole : from) { + for (RoleDAO.Data frole : from) { // Only Add Data to view if User is allowed to see this Role - if(!filter || q.mayUser(trans, trans.user(), frole,Access.read).isOK()) { + if (!filter || q.mayUser(trans, trans.user(), frole,Access.read).isOK()) { Role role = new Role(); role.setName(frole.ns + '.' + frole.name); role.setDescription(frole.description); - if(needNS) { + if (needNS) { role.setNs(frole.ns); } - for(String p : frole.perms(false)) { // can see any Perms in the Role he has permission for + for (String p : frole.perms(false)) { // can see any Perms in the Role he has permission for Result<String[]> rpa = PermDAO.Data.decodeToArray(trans,q,p); - if(rpa.notOK()) + if (rpa.notOK()) return Result.err(rpa); String[] pa = rpa.value; @@ -451,10 +451,10 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo @Override public Result<Users> users(AuthzTrans trans, Collection<UserRoleDAO.Data> from, Users to) { List<User> cu = to.getUser(); - for(UserRoleDAO.Data urd : from) { + for (UserRoleDAO.Data urd : from) { User user = new User(); user.setId(urd.user); - if(urd.expires!=null) { + if (urd.expires!=null) { user.setExpires(Chrono.timeStamp(urd.expires)); } cu.add(user); @@ -471,7 +471,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo @Override public Result<UserRoles> userRoles(AuthzTrans trans, Collection<UserRoleDAO.Data> from, UserRoles to) { List<UserRole> cu = to.getUserRole(); - for(UserRoleDAO.Data urd : from) { + for (UserRoleDAO.Data urd : from) { UserRole ur = new UserRole(); ur.setUser(urd.user); ur.setRole(urd.role); @@ -510,15 +510,15 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo to.id=from.getId(); to.ns = Question.domain2ns(to.id); String passwd = from.getPassword(); - if(requiresPass) { + if (requiresPass) { String ok = trans.org().isValidPassword(trans, to.id,passwd); - if(ok.length()>0) { + if (ok.length()>0) { return Result.err(Status.ERR_BadData,ok); } } else { to.type=0; } - if(passwd != null) { + if (passwd != null) { to.cred = ByteBuffer.wrap(passwd.getBytes()); to.type = CredDAO.RAW; } else { @@ -536,7 +536,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo @Override public Result<Users> cred(List<CredDAO.Data> from, Users to) { List<User> cu = to.getUser(); - for(CredDAO.Data cred : from) { + for (CredDAO.Data cred : from) { User user = new User(); user.setId(cred.id); user.setExpires(Chrono.timeStamp(cred.expires)); @@ -549,7 +549,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo @Override public Result<Certs> cert(List<CertDAO.Data> from, Certs to) { List<Cert> lc = to.getCert(); - for(CertDAO.Data fcred : from) { + for (CertDAO.Data fcred : from) { Cert cert = new Cert(); cert.setId(fcred.id); cert.setX500(fcred.x500); @@ -573,9 +573,9 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo Bytification content, boolean enableApproval, Memo memo, MayChange mc) { Result<?> rMayChange; boolean needsAppr = enableApproval?trans.requested(REQD_TYPE.future):false; - if(!needsAppr && (needsAppr = (rMayChange=mc.mayChange()).notOK())) { - if(enableApproval) { - if(!trans.requested(AuthzTrans.REQD_TYPE.future)) { + if (!needsAppr && (needsAppr = (rMayChange=mc.mayChange()).notOK())) { + if (enableApproval) { + if (!trans.requested(AuthzTrans.REQD_TYPE.future)) { return Result.err(rMayChange); } } else { @@ -587,31 +587,31 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo GregorianCalendar expires = trans.org().expiration(start, Expiration.Future); XMLGregorianCalendar xgc; - if((xgc=from.getEnd())!=null) { + if ((xgc=from.getEnd())!=null) { GregorianCalendar fgc = xgc.toGregorianCalendar(); expires = expires.before(fgc)?expires:fgc; // Min of desired expiration, and Org expiration } //TODO needs two answers from this. What's the NSS, and may Change. FutureDAO.Data fto; - if(start.after(now) || needsAppr ) { + if (start.after(now) || needsAppr ) { //String user = trans.user(); fto = new FutureDAO.Data(); fto.target=table; fto.memo = memo.get(); fto.start = start.getTime(); fto.expires = expires.getTime(); - if(needsAppr) { // Need to add Approvers... + if (needsAppr) { // Need to add Approvers... /* Result<Data> rslt = mc.getNsd(); - if(rslt.notOKorIsEmpty())return Result.err(rslt); + if (rslt.notOKorIsEmpty())return Result.err(rslt); appr.addAll(mc.getNsd().value.responsible); try { //Note from 2013 Is this getting Approvers for user only? What about Delegates? // 3/25/2014. Approvers are set by Corporate policy. We don't have to worry here about what that means. // It is important to get Delegates, if necessary, at notification time // If we add delegates now, it will get all confused as to who is actually responsible. - for(Organization.User ou : org.getApprovers(trans, user)) { + for (Organization.User ou : org.getApprovers(trans, user)) { appr.add(ou.email); } } catch (Exception e) { @@ -638,7 +638,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo public Result<History> history(AuthzTrans trans, List<HistoryDAO.Data> history, final int sort) { History hist = new History(); List<Item> items = hist.getItem(); - for(HistoryDAO.Data data : history) { + for (HistoryDAO.Data data : history) { History.Item item = new History.Item(); item.setYYYYMM(Integer.toString(data.yr_mon)); Date date = Chrono.uuidToDate(data.id); @@ -651,7 +651,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo items.add(item); } - if(sort != 0) { + if (sort != 0) { TimeTaken tt = trans.start("Sort ", Env.SUB); try { java.util.Collections.sort(items, new Comparator<Item>() { @@ -673,7 +673,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo err.setMessageId(msgID); // AT&T Restful Error Format requires numbers "%" placements err.setText(Vars.convert(holder, text, var)); - for(String s : var) { + for (String s : var) { err.getVariables().add(s); } return err; @@ -761,10 +761,10 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo Approvals apprs = new Approvals(); List<Approval> lappr = apprs.getApprovals(); Approval a; - for(ApprovalDAO.Data appr : lAppr) { + for (ApprovalDAO.Data appr : lAppr) { a = new Approval(); a.setId(appr.id.toString()); - if(appr.ticket==null) { + if (appr.ticket==null) { a.setTicket(null); } else { a.setTicket(appr.ticket.toString()); @@ -784,12 +784,12 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo @Override public Result<List<ApprovalDAO.Data>> approvals(Approvals apprs) { List<ApprovalDAO.Data> lappr = new ArrayList<>(); - for(Approval a : apprs.getApprovals()) { + for (Approval a : apprs.getApprovals()) { ApprovalDAO.Data ad = new ApprovalDAO.Data(); String str = a.getId(); - if(str!=null)ad.id=UUID.fromString(str); + if (str!=null)ad.id=UUID.fromString(str); str = a.getTicket(); - if(str!=null)ad.ticket=UUID.fromString(str); + if (str!=null)ad.ticket=UUID.fromString(str); ad.user=a.getUser(); ad.approver=a.getApprover(); ad.type=a.getType(); @@ -798,7 +798,7 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo ad.memo=a.getMemo(); XMLGregorianCalendar xgc = a.getUpdated(); - if(xgc!=null)ad.updated=xgc.toGregorianCalendar().getTime(); + if (xgc!=null)ad.updated=xgc.toGregorianCalendar().getTime(); lappr.add(ad); } return Result.ok(lappr); @@ -809,11 +809,11 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo Delgs delgs = new Delgs(); List<Delg> ldelg = delgs.getDelgs(); Delg d; - for(DelegateDAO.Data del: lDelg) { + for (DelegateDAO.Data del: lDelg) { d = new Delg(); d.setUser(del.user); d.setDelegate(del.delegate); - if(del.expires!=null)d.setExpires(Chrono.timeStamp(del.expires)); + if (del.expires!=null)d.setExpires(Chrono.timeStamp(del.expires)); ldelg.add(d); } return Result.ok(delgs); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java index 4a088abc..128fdcd1 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/validation/ServiceValidator.java @@ -44,7 +44,7 @@ import org.onap.aaf.auth.validation.Validator; */ public class ServiceValidator extends Validator { public ServiceValidator perm(Result<PermDAO.Data> rpd) { - if(rpd.notOK()) { + if (rpd.notOK()) { msg(rpd.details); } else { perm(rpd.value); @@ -54,20 +54,20 @@ public class ServiceValidator extends Validator { public ServiceValidator perm(PermDAO.Data pd) { - if(pd==null) { + if (pd==null) { msg("Perm Data is null."); } else { ns(pd.ns); permType(pd.type,pd.ns); permInstance(pd.instance); permAction(pd.action); - if(pd.roles!=null) { - for(String role : pd.roles) { + if (pd.roles!=null) { + for (String role : pd.roles) { role(role); } } - if(pd.roles!=null) { - for(String r : pd.roles) { + if (pd.roles!=null) { + for (String r : pd.roles) { role(r); } } @@ -77,7 +77,7 @@ public class ServiceValidator extends Validator { } public ServiceValidator role(Result<RoleDAO.Data> rrd) { - if(rrd.notOK()) { + if (rrd.notOK()) { msg(rrd.details); } else { role(rrd.value); @@ -86,15 +86,15 @@ public class ServiceValidator extends Validator { } public ServiceValidator role(RoleDAO.Data pd) { - if(pd==null) { + if (pd==null) { msg("Role Data is null."); } else { ns(pd.ns); role(pd.name); - if(pd.perms!=null) { - for(String perm : pd.perms) { + if (pd.perms!=null) { + for (String perm : pd.perms) { String[] ps = perm.split("\\|"); - if(ps.length!=3) { + if (ps.length!=3) { msg("Perm [" + perm + "] in Role [" + pd.fullName() + "] is not correctly separated with '|'"); } else { permType(ps[0],null); @@ -109,7 +109,7 @@ public class ServiceValidator extends Validator { } public ServiceValidator delegate(Organization org, Result<DelegateDAO.Data> rdd) { - if(rdd.notOK()) { + if (rdd.notOK()) { msg(rdd.details); } else { delegate(org, rdd.value); @@ -118,7 +118,7 @@ public class ServiceValidator extends Validator { } public ServiceValidator delegate(Organization org, DelegateDAO.Data dd) { - if(dd==null) { + if (dd==null) { msg("Delegate Data is null."); } else { user(org,dd.user); @@ -129,7 +129,7 @@ public class ServiceValidator extends Validator { public ServiceValidator cred(AuthzTrans trans, Organization org, Result<CredDAO.Data> rcd, boolean isNew) { - if(rcd.notOK()) { + if (rcd.notOK()) { msg(rcd.details); } else { cred(trans, org,rcd.value,isNew); @@ -138,26 +138,26 @@ public class ServiceValidator extends Validator { } public ServiceValidator cred(AuthzTrans trans, Organization org, CredDAO.Data cd, boolean isNew) { - if(cd==null) { + if (cd==null) { msg("Cred Data is null."); } else { - if(!org.isValidCred(trans, cd.id)) { + if (!org.isValidCred(trans, cd.id)) { msg("ID [" + cd.id + "] is invalid in " + org.getName()); } String str = cd.id; int idx = str.indexOf('@'); - if(idx>0) { + if (idx>0) { str = str.substring(0,idx); } - if(org.supportsRealm(cd.id)) { + if (org.supportsRealm(cd.id)) { String resp = org.isValidID(trans, str); - if(isNew && (resp!=null && resp.length()>0)) { + if (isNew && (resp!=null && resp.length()>0)) { msg(cd.id,str); } } - if(cd.type==null) { + if (cd.type==null) { msg("Credential Type must be set"); } else { switch(cd.type) { @@ -174,7 +174,7 @@ public class ServiceValidator extends Validator { public ServiceValidator user(Organization org, String user) { - if(nob(user,ID_CHARS)) { + if (nob(user,ID_CHARS)) { msg("User [",user,"] is invalid."); } return this; @@ -188,25 +188,25 @@ public class ServiceValidator extends Validator { public ServiceValidator ns(Namespace ns) { ns(ns.name); - for(String s : ns.admin) { - if(nob(s,ID_CHARS)) { + for (String s : ns.admin) { + if (nob(s,ID_CHARS)) { msg("Admin [" + s + "] is invalid."); } } - for(String s : ns.owner) { - if(nob(s,ID_CHARS)) { + for (String s : ns.owner) { + if (nob(s,ID_CHARS)) { msg("Responsible [" + s + "] is invalid."); } } - if(ns.attrib!=null) { - for(Pair<String, String> at : ns.attrib) { - if(nob(at.x,NAME_CHARS)) { + if (ns.attrib!=null) { + for (Pair<String, String> at : ns.attrib) { + if (nob(at.x,NAME_CHARS)) { msg("Attribute tag [" + at.x + "] is invalid."); } - if(nob(at.x,NAME_CHARS)) { + if (nob(at.x,NAME_CHARS)) { msg("Attribute value [" + at.y + "] is invalid."); } } @@ -217,7 +217,7 @@ public class ServiceValidator extends Validator { } public ServiceValidator user_role(UserRoleDAO.Data urdd) { - if(urdd==null) { + if (urdd==null) { msg("UserRole is null"); } else { role(urdd.role); @@ -228,7 +228,7 @@ public class ServiceValidator extends Validator { } public ServiceValidator nullOrBlank(PermDAO.Data pd) { - if(pd==null) { + if (pd==null) { msg("Permission is null"); } else { nullOrBlank("NS",pd.ns). @@ -240,7 +240,7 @@ public class ServiceValidator extends Validator { } public ServiceValidator nullOrBlank(RoleDAO.Data rd) { - if(rd==null) { + if (rd==null) { msg("Role is null"); } else { nullOrBlank("NS",rd.ns). diff --git a/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java b/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java index 355da9a9..31fdde1f 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/authz/service/mapper/JU_Mapper_2_0.java @@ -370,7 +370,7 @@ public class JU_Mapper_2_0 { assertTrue(result.isOK()); assertEquals("Alls Perms added",5,result.value.getPerm().size()); List<Perm> mappedPerms = result.value.getPerm(); - for(int i=0; i<5; i++) { + for (int i=0; i<5; i++) { comparePerm(correctOrderPerms.get(i), mappedPerms.get(i)); } } @@ -492,7 +492,7 @@ public class JU_Mapper_2_0 { assertEquals(2, result.value.getRole().size()); result.value.getRole().stream().forEach( role -> { assertTrue(role.getPerms().isEmpty()); - if(namespaceRequested) { + if (namespaceRequested) { assertEquals(namespace, role.getNs()); } else { assertNull(role.getNs()); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java index c4876f29..be1d3922 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/AAFPermission.java @@ -50,7 +50,7 @@ public class AAFPermission implements Permission { type = name; this.instance = instance; this.action = action; - if(ns==null) { + if (ns==null) { key = type + '|' + instance + '|' + action; } else { key = ns + '|' + type + '|' + instance + '|' + action; @@ -64,7 +64,7 @@ public class AAFPermission implements Permission { type = name; this.instance = instance; this.action = action; - if(ns==null) { + if (ns==null) { key = type + '|' + instance + '|' + action; } else { key = ns + '|' + type + '|' + instance + '|' + action; @@ -87,7 +87,7 @@ public class AAFPermission implements Permission { String aafType; String aafInstance; String aafAction; - if(p instanceof AAFPermission) { + if (p instanceof AAFPermission) { AAFPermission ap = (AAFPermission)p; // Note: In AAF > 1.0, Accepting "*" from name would violate multi-tenancy // Current solution is only allow direct match on Type. @@ -125,15 +125,15 @@ public class AAFPermission implements Permission { } } boolean typeMatches; - if(aafNS==null) { - if(ns==null) { + if (aafNS==null) { + if (ns==null) { typeMatches = aafType.equals(type); } else { typeMatches = aafType.equals(ns+'.'+type); } - } else if(ns==null) { + } else if (ns==null) { typeMatches = type.equals(aafNS+'.'+aafType); - } else if(aafNS.length() == ns.length()) { + } else if (aafNS.length() == ns.length()) { typeMatches = aafNS.equals(ns) && aafType.equals(type); } else { // Allow for restructuring of NS/Perm structure typeMatches = (aafNS+'.'+aafType).equals(ns+'.'+type); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java index f64eb276..c12b2e6d 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/PermEval.java @@ -44,13 +44,13 @@ public class PermEval { * Changing this will break existing users, like Cassandra. Jonathan 9-4-2015 */ public static boolean evalInstance(String sInst, String pInst) { - if(sInst == null || pInst == null) { + if (sInst == null || pInst == null) { return false; } if (sInst == "" || pInst == "") { return false; } - if(ASTERIX.equals(sInst)) { + if (ASTERIX.equals(sInst)) { return true; // If Server's String is "*", then it accepts every Instance } char firstChar = pInst.charAt(0); @@ -63,29 +63,29 @@ public class PermEval { case START_INST_KEY_CHAR: // Evaluate a special Key field, i.e.:xyz:*:!df.* case ALT_START_INST_KEY_CHAR: // Also allow '/' as special Key Field, i.e. /xyz/*/!.* - if(sInst.charAt(0)==startChar) { // To compare key-to-key, both strings must be keys + if (sInst.charAt(0)==startChar) { // To compare key-to-key, both strings must be keys String[] skeys=Split.split(startChar,sInst); String[] pkeys=Split.split(startChar,pInst); - if(skeys.length!=pkeys.length) return false; + if (skeys.length!=pkeys.length) return false; boolean pass = true; - for(int i=1;pass && i<skeys.length;++i) { // We start at 1, because the first one, being ":" is always "" - if(ASTERIX.equals(skeys[i]))continue; // Server data accepts all for this key spot + for (int i=1;pass && i<skeys.length;++i) { // We start at 1, because the first one, being ":" is always "" + if (ASTERIX.equals(skeys[i]))continue; // Server data accepts all for this key spot pass = false; - for(String sItem : Split.split(LIST_SEP,skeys[i])) { // allow for "," definition in Action - if(pkeys[i].length()==0) { - if(pass=sItem.length()==0) { + for (String sItem : Split.split(LIST_SEP,skeys[i])) { // allow for "," definition in Action + if (pkeys[i].length()==0) { + if (pass=sItem.length()==0) { break; // Both Empty, keep checking } - } else if(sItem.charAt(0)==START_REGEX_CHAR) { // Check Server side when wildcarding like * - if(pass=pkeys[i].matches(sItem.substring(1))) { + } else if (sItem.charAt(0)==START_REGEX_CHAR) { // Check Server side when wildcarding like * + if (pass=pkeys[i].matches(sItem.substring(1))) { break; // Matches, keep checking } - } else if(skeys[i].endsWith(ASTERIX)) { - if(pass=endAsterixCompare(skeys[i],pkeys[i])) { + } else if (skeys[i].endsWith(ASTERIX)) { + if (pass=endAsterixCompare(skeys[i],pkeys[i])) { break; } - } else if(pass=sItem.equals(pkeys[i])) { + } else if (pass=sItem.equals(pkeys[i])) { break; // Equal, keep checking } } @@ -94,10 +94,10 @@ public class PermEval { } return false; // if first chars aren't the same, further String compare not necessary default: // Evaluate as String Compare - for(String sItem : Split.split(LIST_SEP,sInst)) { // allow for "," separator //TODO is this only for actions? - if((sItem.endsWith(ASTERIX)) && (endAsterixCompare(sInst, pInst))) { + for (String sItem : Split.split(LIST_SEP,sInst)) { // allow for "," separator //TODO is this only for actions? + if ((sItem.endsWith(ASTERIX)) && (endAsterixCompare(sInst, pInst))) { return true; - } else if(sItem.equals(pInst)) { + } else if (sItem.equals(pInst)) { return true; } } @@ -107,11 +107,11 @@ public class PermEval { private static boolean endAsterixCompare(String sInst, String pInst) { final int len = sInst.length()-1; - if(pInst.length()<len) { + if (pInst.length()<len) { return false; } - for(int j=0;j<len;++j) { - if(pInst.charAt(j)!=sInst.charAt(j)) { + for (int j=0;j<len;++j) { + if (pInst.charAt(j)!=sInst.charAt(j)) { return false; } } @@ -126,9 +126,9 @@ public class PermEval { * Action is not quite as complex. But we write it in this function so it can be consistent */ public static boolean evalAction(String sAction,String pAction) { - if(ASTERIX.equals(sAction))return true; // If Server's String is "*", then it accepts every Action - if(pAction == "") return false; - for(String sItem : Split.split(LIST_SEP,sAction)) { // allow for "," definition in Action + if (ASTERIX.equals(sAction))return true; // If Server's String is "*", then it accepts every Action + if (pAction == "") return false; + for (String sItem : Split.split(LIST_SEP,sAction)) { // allow for "," definition in Action if (pAction.charAt(0)==START_REGEX_CHAR? // First char sItem.matches(pAction.substring(1)): // Evaluate as Regular Expression sItem.equals(pAction)) // Evaluate as String Compare diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/TestConnectivity.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/TestConnectivity.java index e9c90288..ccba7c1a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/TestConnectivity.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/TestConnectivity.java @@ -51,24 +51,24 @@ import org.onap.aaf.misc.env.APIException; public class TestConnectivity { public static void main(String[] args) { - if(args.length<1) { + if (args.length<1) { System.out.println("Usage: ConnectivityTester <cadi_prop_files> [<AAF FQDN (i.e. aaf.dev.att.com)>]"); } else { print(true,"START OF CONNECTIVITY TESTS",new Date().toString(),System.getProperty("user.name"), "Note: All API Calls are /authz/perms/user/<AppID/Alias of the caller>"); - if(!args[0].contains(Config.CADI_PROP_FILES+'=')) { + if (!args[0].contains(Config.CADI_PROP_FILES+'=')) { args[0]=Config.CADI_PROP_FILES+'='+args[0]; } PropAccess access = new PropAccess(args); String aaflocate; - if(args.length>1) { + if (args.length>1) { aaflocate = "https://" + args[1]; access.setProperty(Config.AAF_LOCATE_URL, "https://" + args[1]); } else { aaflocate = access.getProperty(Config.AAF_LOCATE_URL); - if(aaflocate==null) { + if (aaflocate==null) { print(true,"Properties must contain ",Config.AAF_LOCATE_URL); } } @@ -81,7 +81,7 @@ public class TestConnectivity { print(true,"Test Connections driven by AAFLocator"); URI serviceURI = new URI(Defaults.AAF_URL); - for(URI uri : new URI[] { + for (URI uri : new URI[] { serviceURI, new URI(Defaults.OAUTH2_TOKEN_URL), new URI(Defaults.OAUTH2_INTROSPECT_URL), @@ -102,19 +102,19 @@ public class TestConnectivity { ///////// print(true,"Test Service for Perms driven by AAFLocator"); Locator<URI> locator = new AAFLocator(si,serviceURI); - for(SecuritySetter<HttpURLConnection> ss : lss) { + for (SecuritySetter<HttpURLConnection> ss : lss) { permTest(locator,ss); } ////////// print(true,"Test essential BasicAuth Service call, driven by AAFLocator"); - for(SecuritySetter<HttpURLConnection> ss : lss) { - if(ss instanceof HBasicAuthSS) { + for (SecuritySetter<HttpURLConnection> ss : lss) { + if (ss instanceof HBasicAuthSS) { basicAuthTest(new AAFLocator(si, serviceURI),ss); } } - } catch(Exception e) { + } catch (Exception e) { e.printStackTrace(System.err); } finally { print(true,"END OF TESTS"); @@ -131,7 +131,7 @@ public class TestConnectivity { try { HBasicAuthSS hbass = new HBasicAuthSS(si,true); - if(hbass==null || hbass.getID()==null) { + if (hbass==null || hbass.getID()==null) { access.log(Level.INFO, "BasicAuth Information is not available in configuration, BasicAuth tests will not be conducted... Continuing"); } else { access.log(Level.INFO, "BasicAuth Information found with ID",hbass.getID(),". BasicAuth tests will be performed."); @@ -143,7 +143,7 @@ public class TestConnectivity { try { HX509SS hxss = new HX509SS(user,si); - if(hxss==null || hxss.getID()==null) { + if (hxss==null || hxss.getID()==null) { access.log(Level.INFO, "X509 (Client certificate) Information is not available in configuration, X509 tests will not be conducted... Continuing"); } else { access.log(Level.INFO, "X509 (Client certificate) Information found with ID",hxss.getID(),". X509 tests will be performed."); @@ -155,7 +155,7 @@ public class TestConnectivity { String tokenURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL); String locateURL=access.getProperty(Config.AAF_LOCATE_URL); - if(tokenURL==null || (tokenURL.contains("/locate/") && locateURL!=null)) { + if (tokenURL==null || (tokenURL.contains("/locate/") && locateURL!=null)) { tokenURL=Defaults.OAUTH2_TOKEN_URL+"/token"; } @@ -168,7 +168,7 @@ public class TestConnectivity { } tokenURL = access.getProperty(Config.AAF_ALT_OAUTH2_TOKEN_URL); - if(tokenURL==null) { + if (tokenURL==null) { access.log(Level.INFO, "AAF Alternative OAUTH2 requires",Config.AAF_ALT_OAUTH2_TOKEN_URL, "OAuth2 tests to", tokenURL, "will not be conducted... Continuing"); } else { try { @@ -186,22 +186,22 @@ public class TestConnectivity { private static void print(Boolean strong, String ... args) { PrintStream out = System.out; out.println(); - if(strong) { - for(int i=0;i<70;++i) { + if (strong) { + for (int i=0;i<70;++i) { out.print('='); } out.println(); } - for(String s : args) { + for (String s : args) { out.print(strong?"== ":"------ "); out.print(s); - if(!strong) { + if (!strong) { out.print(" ------"); } out.println(); } - if(strong) { - for(int i=0;i<70;++i) { + if (strong) { + for (int i=0;i<70;++i) { out.print('='); } } @@ -212,8 +212,8 @@ public class TestConnectivity { URI uri; Socket socket; print(false,"TCP/IP Connect test to all Located Services for " + locatorURI.toString() ); - for(Item li = dl.first();li!=null;li=dl.next(li)) { - if((uri = dl.get(li)) == null) { + for (Item li = dl.first();li!=null;li=dl.next(li)) { + if ((uri = dl.get(li)) == null) { System.out.println("Locator Item empty"); } else { socket = new Socket(); @@ -238,14 +238,14 @@ public class TestConnectivity { private static void permTest(Locator<URI> dl, SecuritySetter<HttpURLConnection> ss) { try { URI uri = dl.get(dl.best()); - if(uri==null) { + if (uri==null) { System.out.print("No URI available using " + ss.getClass().getSimpleName()); System.out.println(); return; } else { System.out.print("Resolved to: " + uri + " using " + ss.getClass().getSimpleName()); } - if(ss instanceof HRenewingTokenSS) { + if (ss instanceof HRenewingTokenSS) { System.out.println(" " + ((HRenewingTokenSS)ss).tokenURL()); } else { System.out.println(); @@ -253,16 +253,16 @@ public class TestConnectivity { HClient client = new HClient(ss, uri, 3000); client.setMethod("GET"); String user = ss.getID(); - if(user.indexOf('@')<0) { + if (user.indexOf('@')<0) { user+="@isam.att.com"; } client.setPathInfo("/authz/perms/user/"+user); client.send(); Future<String> future = client.futureReadString(); - if(future.get(7000)) { + if (future.get(7000)) { System.out.println(future.body()); } else { - if(future.code()==401 && ss instanceof HX509SS) { + if (future.code()==401 && ss instanceof HX509SS) { System.out.println(" Authentication denied with 401 for Certificate.\n\t" + "This means Certificate isn't valid for this environment, and has attempted another method of Authentication"); } else { @@ -287,7 +287,7 @@ public class TestConnectivity { Future<String> future = client.futureReadString(); - if(future.get(7000)) { + if (future.get(7000)) { System.out.println("BasicAuth Validated"); } else { System.out.println("Failure " + future.code() + ":" + future.body()); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java index dd8b1262..dd3cde7e 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/cert/AAFListedCertIdentity.java @@ -69,13 +69,13 @@ public class AAFListedCertIdentity implements CertIdentity { public AAFListedCertIdentity(Access access, AAFCon<?> aafcon) throws APIException { synchronized(AAFListedCertIdentity.class) { - if(certIDs==null) { + if (certIDs==null) { String cip = access.getProperty(Config.AAF_CERT_IDS, null); - if(cip!=null) { + if (cip!=null) { certIDs = Split.split(',',cip); } } - if(certIDs!=null && certs==null) { + if (certIDs!=null && certs==null) { TimerTask cu = new CertUpdate(aafcon); cu.run(); // want this to run in this thread first... new Timer("AAF Identity Refresh Timer",true).scheduleAtFixedRate(cu, EIGHT_HOURS,EIGHT_HOURS); @@ -88,11 +88,11 @@ public class AAFListedCertIdentity implements CertIdentity { } public TaggedPrincipal identity(HttpServletRequest req, X509Certificate cert, byte[] certBytes) throws CertificateException { - if(cert==null && certBytes==null)return null; - if(certBytes==null)certBytes = cert.getEncoded(); + if (cert==null && certBytes==null)return null; + if (certBytes==null)certBytes = cert.getEncoded(); byte[] fingerprint = X509Taf.getFingerPrint(certBytes); String id = certs.get(new ByteArrayHolder(fingerprint)); - if(id!=null) { // Caller is Validated + if (id!=null) { // Caller is Validated return new X509Principal(id,cert,certBytes,null); } return null; @@ -121,19 +121,19 @@ public class AAFListedCertIdentity implements CertIdentity { TreeMap<ByteArrayHolder, String> newCertsMap = new TreeMap<>(); Map<String,Set<String>> newTrustMap = new TreeMap<>(); Set<String> userLookup = new HashSet<>(); - for(String s : certIDs) { + for (String s : certIDs) { userLookup.add(s); } - for(String authMech : authMechanisms) { + for (String authMech : authMechanisms) { Future<Users> fusr = aafcon.client(Config.AAF_DEFAULT_VERSION).read("/authz/users/perm/com.att.aaf.trust/"+authMech+"/authenticate", Users.class, aafcon.usersDF); - if(fusr.get(5000)) { + if (fusr.get(5000)) { List<User> users = fusr.value.getUser(); - if(users.isEmpty()) { + if (users.isEmpty()) { aafcon.access.log(Level.WARN, "AAF Lookup-No IDs in Role com.att.aaf.trustForID <> "+authMech); } else { aafcon.access.log(Level.INFO,"Loading Trust Authentication Info for",authMech); Set<String> hsUser = new HashSet<>(); - for(User u : users) { + for (User u : users) { userLookup.add(u.getId()); hsUser.add(u.getId()); } @@ -145,17 +145,17 @@ public class AAFListedCertIdentity implements CertIdentity { } - for(String u : userLookup) { + for (String u : userLookup) { Future<Certs> fc = aafcon.client(Config.AAF_DEFAULT_VERSION).read("/authn/cert/id/"+u, Certs.class, aafcon.certsDF); XMLGregorianCalendar now = Chrono.timeStamp(); - if(fc.get(5000)) { + if (fc.get(5000)) { List<Cert> certs = fc.value.getCert(); - if(certs.isEmpty()) { + if (certs.isEmpty()) { aafcon.access.log(Level.WARN, "No Cert Associations for",u); } else { - for(Cert c : fc.value.getCert()) { + for (Cert c : fc.value.getCert()) { XMLGregorianCalendar then =c.getExpires(); - if(then !=null && then.compare(now)>0) { + if (then !=null && then.compare(now)>0) { newCertsMap.put(new ByteArrayHolder(c.getFingerprint()), c.getId()); aafcon.access.log(Level.INIT,"Associating "+ c.getId() + " expiring " + Chrono.dateOnlyStamp(c.getExpires()) + " with " + c.getX500()); } @@ -168,7 +168,7 @@ public class AAFListedCertIdentity implements CertIdentity { certs = newCertsMap; trusted = newTrustMap; - } catch(Exception e) { + } catch (Exception e) { aafcon.access.log(e, "Failure to update Certificate Identities from AAF"); } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java index e878d740..55421262 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/ErrMessage.java @@ -76,7 +76,7 @@ public class ErrMessage { public StringBuilder toMsg(StringBuilder sb, Future<?> future) { try { toMsg(sb,errDF.newData().in(TYPE.JSON).load(future.body()).asObject()); - } catch(Exception e) { + } catch (Exception e) { //just print what we can sb.append(future.code()); sb.append(": "); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java index 0cf48de6..70ca577a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/client/Examples.java @@ -63,23 +63,23 @@ public class Examples { String className = null; String version = null; TYPE type = TYPE.JSON; // default - if(nameOrContentType.startsWith("application/")) { - for(String ct : nameOrContentType.split("\\s*,\\s*")) { - for(String elem : ct.split("\\s*;\\s*")) { - if(elem.endsWith("+json")) { + if (nameOrContentType.startsWith("application/")) { + for (String ct : nameOrContentType.split("\\s*,\\s*")) { + for (String elem : ct.split("\\s*;\\s*")) { + if (elem.endsWith("+json")) { type = TYPE.JSON; className = elem.substring(elem.indexOf('/')+1, elem.length()-5); - } else if(elem.endsWith("+xml")) { + } else if (elem.endsWith("+xml")) { type = TYPE.XML; className = elem.substring(elem.indexOf('/')+1, elem.length()-4); - } else if(elem.startsWith("version=")) { + } else if (elem.startsWith("version=")) { version = elem.substring(8); } } - if(className!=null && version!=null) + if (className!=null && version!=null) break; } - if(className==null) { + if (className==null) { throw new APIException(nameOrContentType + " does not contain Class Information"); } } else { @@ -91,9 +91,9 @@ public class Examples { if ("Void".equals(className)) return ""; - if("1.1".equals(version)) { + if ("1.1".equals(version)) { version = "v1_0"; - } else if(version!=null) { + } else if (version!=null) { version = "v" + version.replace('.', '_'); } else { version = "v2_0"; @@ -151,7 +151,7 @@ public class Examples { pkey.setAction("myAction"); rpr.setPerm(pkey); rpr.setRole("org.osaaf.myns.myrole"); - if(optional)setOptional(rpr); + if (optional)setOptional(rpr); return rpr; } @@ -200,7 +200,7 @@ public class Examples { pr.setType("org.osaaf.myns.myType"); pr.setInstance("myInstance"); pr.setAction("myAction"); - if(optional) { + if (optional) { pr.setDescription("Short and meaningful verbiage about the Permission"); setOptional(pr); @@ -217,7 +217,7 @@ public class Examples { pr.getRoles().add("org.osaaf.aaf.myRole"); pr.getRoles().add("org.osaaf.aaf.myRole2"); pr.setDescription("This is my description, and I'm sticking with it"); - if(optional) { + if (optional) { pr.setDescription("Short and meaningful verbiage about the Permission"); } return pr; @@ -262,7 +262,7 @@ public class Examples { UserRoleRequest urr = new UserRoleRequest(); urr.setRole("org.osaaf.myns.myRole"); urr.setUser("ab1234@people.osaaf.org"); - if(optional) setOptional(urr); + if (optional) setOptional(urr); return urr; } @@ -274,7 +274,7 @@ public class Examples { nr.getResponsible().add("cd5678@people.osaaf.org"); nr.getAdmin().add("zy9876@people.osaaf.org"); nr.getAdmin().add("xw5432@people.osaaf.org"); - if(optional) { + if (optional) { nr.setDescription("This is my Namespace to set up"); nr.setType("APP"); setOptional(nr); @@ -309,7 +309,7 @@ public class Examples { private static RoleRequest newRoleRequestv2_0(boolean optional) { RoleRequest rr = new RoleRequest(); rr.setName("org.osaaf.myns.myRole"); - if(optional) { + if (optional) { rr.setDescription("This is my Role"); setOptional(rr); } @@ -320,7 +320,7 @@ public class Examples { private static CredRequest newCredRequestv2_0(boolean optional) { CredRequest cr = new CredRequest(); cr.setId("myID@fully.qualified.domain"); - if(optional) { + if (optional) { cr.setType(2); cr.setEntry("0x125AB256344CE"); } else { diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java index edacdfdd..167fae9f 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFAuthn.java @@ -95,8 +95,8 @@ public class AAFAuthn<CLIENT> extends AbsUserCache<AAFPermission> { byte[] bytes = password.getBytes(); User<AAFPermission> usr = getUser(user,bytes); - if(usr != null && !usr.permExpired()) { - if(usr.principal==null) { + if (usr != null && !usr.permExpired()) { + if (usr.principal==null) { return "User already denied"; } else { return null; // good @@ -108,7 +108,7 @@ public class AAFAuthn<CLIENT> extends AbsUserCache<AAFPermission> { // Statement switch(cp.revalidate(state)) { case REVALIDATED: - if(usr!=null) { + if (usr!=null) { usr.principal = cp; } else { addUser(new User<AAFPermission>(cp,con.timeout)); @@ -139,13 +139,13 @@ public class AAFAuthn<CLIENT> extends AbsUserCache<AAFPermission> { public Resp revalidate(Object state) { try { Miss missed = missed(getName(),getCred()); - if(missed==null || missed.mayContinue()) { + if (missed==null || missed.mayContinue()) { Rcli<CLIENT> client = con.client(Config.AAF_DEFAULT_VERSION).forUser(con.basicAuth(getName(), new String(getCred()))); Future<String> fp = client.read( "/authn/basicAuth", "text/plain" ); - if(fp.get(con.timeout)) { + if (fp.get(con.timeout)) { expires = System.currentTimeMillis() + timeToLive; addUser(new User<AAFPermission>(this, expires)); return Resp.REVALIDATED; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java index cda6dfb9..b6644368 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFCon.java @@ -89,7 +89,7 @@ public abstract class AAFCon<CLIENT> implements Connector { */ public Rcli<CLIENT> client(String apiVersion) throws CadiException { Rcli<CLIENT> client = clients.get(apiVersion); - if(client==null) { + if (client==null) { client = rclient(initURI(),si.defSS); client.apiVersion(apiVersion) .readTimeout(connTimeout); @@ -136,12 +136,12 @@ public abstract class AAFCon<CLIENT> implements Connector { } protected AAFCon(Access access, String tag, SecurityInfoC<CLIENT> si) throws CadiException{ - if(tag==null) { + if (tag==null) { throw new CadiException("AAFCon cannot be constructed without a property tag or URL"); } else { String str = access.getProperty(tag,null); - if(str==null) { - if(tag.contains("://")) { // assume a URL + if (str==null) { + if (tag.contains("://")) { // assume a URL str = tag; } else { throw new CadiException("A URL or " + tag + " property is required."); @@ -152,18 +152,18 @@ public abstract class AAFCon<CLIENT> implements Connector { try { this.access = access; this.si = si; - if(si.defSS.getID().equals(SecurityInfoC.DEF_ID)) { // it's the Preliminary SS, try to get a better one + if (si.defSS.getID().equals(SecurityInfoC.DEF_ID)) { // it's the Preliminary SS, try to get a better one String mechid = access.getProperty(Config.AAF_APPID, null); - if(mechid==null) { + if (mechid==null) { mechid=access.getProperty(Config.OAUTH_CLIENT_ID,null); } String encpass = access.getProperty(Config.AAF_APPPASS, null); - if(encpass==null) { + if (encpass==null) { encpass = access.getProperty(Config.OAUTH_CLIENT_SECRET,null); } - if(encpass==null) { + if (encpass==null) { String alias = access.getProperty(Config.CADI_ALIAS, mechid); - if(alias==null) { + if (alias==null) { access.printf(Access.Level.WARN,"%s, %s or %s required before use.", Config.CADI_ALIAS, Config.AAF_APPID, Config.OAUTH_CLIENT_ID); set(si.defSS); } else { @@ -171,7 +171,7 @@ public abstract class AAFCon<CLIENT> implements Connector { set(si.defSS); } } else { - if(mechid!=null) { + if (mechid!=null) { si.defSS=basicAuth(mechid, encpass); set(si.defSS); } else { @@ -231,16 +231,16 @@ public abstract class AAFCon<CLIENT> implements Connector { * @return */ public static final AAFCon<?> obtain(Object servletRequest) { - if(servletRequest instanceof CadiWrap) { + if (servletRequest instanceof CadiWrap) { Lur lur = ((CadiWrap)servletRequest).getLur(); - if(lur != null) { - if(lur instanceof EpiLur) { + if (lur != null) { + if (lur instanceof EpiLur) { AbsAAFLur<?> aal = (AbsAAFLur<?>) ((EpiLur)lur).subLur(AbsAAFLur.class); - if(aal!=null) { + if (aal!=null) { return aal.aaf; } } else { - if(lur instanceof AbsAAFLur) { + if (lur instanceof AbsAAFLur) { return ((AbsAAFLur<?>)lur).aaf; } } @@ -265,7 +265,7 @@ public abstract class AAFCon<CLIENT> implements Connector { public AAFLurPerm newLur() throws CadiException { try { - if(lur==null) { + if (lur==null) { lur = new AAFLurPerm(this); return lur; } else { @@ -327,7 +327,7 @@ public abstract class AAFCon<CLIENT> implements Connector { public SecuritySetter<CLIENT> set(final SecuritySetter<CLIENT> ss) { si.set(ss); - for(Rcli<CLIENT> client : clients.values()) { + for (Rcli<CLIENT> client : clients.values()) { client.setSecuritySetter(ss); } return ss; @@ -338,14 +338,14 @@ public abstract class AAFCon<CLIENT> implements Connector { } public String defID() { - if(si!=null) { + if (si!=null) { return si.defSS.getID(); } return "unknown"; } public void invalidate() throws CadiException { - for(Rcli<CLIENT> client : clients.values()) { + for (Rcli<CLIENT> client : clients.values()) { client.invalidate(); } clients.clear(); @@ -353,9 +353,9 @@ public abstract class AAFCon<CLIENT> implements Connector { public String readableErrMsg(Future<?> f) { String text = f.body(); - if(text==null || text.length()==0) { + if (text==null || text.length()==0) { text = f.code() + ": **No Message**"; - } else if(text.contains("%")) { + } else if (text.contains("%")) { try { Error err = errDF.newData().in(TYPE.JSON).load(f.body()).asObject(); return Vars.convert(err.getText(),err.getVariables()); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java index cc70ae3c..9b5e9389 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFConHttp.java @@ -104,7 +104,7 @@ public class AAFConHttp extends AAFCon<HttpURLConnection> { */ @Override public SecuritySetter<HttpURLConnection> basicAuth(String user, String password) throws CadiException { - if(password.startsWith("enc:")) { + if (password.startsWith("enc:")) { try { password = access.decrypt(password, true); } catch (IOException e) { @@ -131,7 +131,7 @@ public class AAFConHttp extends AAFCon<HttpURLConnection> { */ @Override protected Rcli<HttpURLConnection> rclient(URI ignoredURI, SecuritySetter<HttpURLConnection> ss) throws CadiException { - if(hman.loc==null) { + if (hman.loc==null) { throw new CadiException("No Locator set in AAFConHttp"); } try { @@ -200,7 +200,7 @@ public class AAFConHttp extends AAFCon<HttpURLConnection> { protected URI initURI() { try { Item item = hman.loc.best(); - if(item!=null) { + if (item!=null) { return hman.loc.get(item); } } catch (LocatorException e) { diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java index 468bb915..35ef9990 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLocator.java @@ -53,7 +53,7 @@ public class AAFLocator extends AbsAAFLocator<BasicTrans> { public AAFLocator(SecurityInfoC<HttpURLConnection> si, URI locatorURI) throws LocatorException { super(si.access, nameFromLocatorURI(locatorURI), 10000L /* Wait at least 10 seconds between refreshes */); synchronized(sr) { - if(env==null) { + if (env==null) { env = new RosettaEnv(access.getProperties()); } } @@ -62,10 +62,10 @@ public class AAFLocator extends AbsAAFLocator<BasicTrans> { try { String[] path = Split.split('/',locatorURI.getPath()); String host = locatorURI.getHost(); - if(host==null) { + if (host==null) { host = locatorURI.getAuthority(); // this happens when no port } - if("AAF_LOCATE_URL".equals(host)) { + if ("AAF_LOCATE_URL".equals(host)) { URI uri = new URI( locatorURI.getScheme(), locatorURI.getUserInfo(), @@ -76,9 +76,9 @@ public class AAFLocator extends AbsAAFLocator<BasicTrans> { null ); client = createClient(si.defSS, uri, connectTimeout); - } else if(path.length>1 && "locate".equals(path[1])) { + } else if (path.length>1 && "locate".equals(path[1])) { StringBuilder sb = new StringBuilder(); - for(int i=3;i<path.length;++i) { + for (int i=3;i<path.length;++i) { sb.append('/'); sb.append(path[i]); } @@ -108,9 +108,9 @@ public class AAFLocator extends AbsAAFLocator<BasicTrans> { client.setMethod("GET"); client.send(); Future<Endpoints> fr = client.futureRead(epsDF, TYPE.JSON); - if(fr.get(client.timeout())) { + if (fr.get(client.timeout())) { List<EP> epl = new LinkedList<>(); - for(Endpoint endpoint : fr.value.getEndpoint()) { + for (Endpoint endpoint : fr.value.getEndpoint()) { epl.add(new EP(endpoint,latitude,longitude)); } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java index b1c600a0..dc0e2cae 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFLurPerm.java @@ -88,8 +88,8 @@ public class AAFLurPerm extends AbsAAFLur<AAFPermission> { private void attachOAuth2(AAFCon<?> con) throws APIException { String oauth2_url; Class<?> tmcls = Config.loadClass(access,"org.osaaf.cadi.oauth.TokenMgr"); - if(tmcls!=null) { - if((oauth2_url = con.access.getProperty(Config.CADI_OAUTH2_URL,null))!=null) { + if (tmcls!=null) { + if ((oauth2_url = con.access.getProperty(Config.CADI_OAUTH2_URL,null))!=null) { try { Constructor<?> tmconst = tmcls.getConstructor(AAFCon.class,String.class); Object tokMangr = tmconst.newInstance(con,oauth2_url); @@ -124,7 +124,7 @@ public class AAFLurPerm extends AbsAAFLur<AAFPermission> { // In the meantime, lookup User, create if necessary User<AAFPermission> user = getUser(principal); Principal p; - if(user!=null && user.principal == null) { + if (user!=null && user.principal == null) { p = new Principal() {// Create a holder for lookups private String n = name; public String getName() { @@ -135,20 +135,20 @@ public class AAFLurPerm extends AbsAAFLur<AAFPermission> { p = principal; } - if(user==null) { + if (user==null) { addUser(user = new User<AAFPermission>(p,aaf.userExpires)); // no password } // OK, done all we can, now get content boolean ok = fp.get(aaf.timeout); remote.set(Timing.millis(remoteStart)); - if(ok) { + if (ok) { success[0]=true; Map<String, Permission> newMap = user.newMap(); boolean willLog = aaf.access.willLog(Level.DEBUG); - for(Perm perm : fp.value.getPerm()) { + for (Perm perm : fp.value.getPerm()) { user.add(newMap,new AAFPermission(perm.getNs(),perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles())); - if(willLog) { + if (willLog) { aaf.access.log(Level.DEBUG, name,"has '",perm.getType(),'|',perm.getInstance(),'|',perm.getAction(),'\''); } } @@ -198,13 +198,13 @@ public class AAFLurPerm extends AbsAAFLur<AAFPermission> { // OK, done all we can, now get content boolean ok = fp.get(aaf.timeout); remote.set(Timing.millis(remoteStart)); - if(ok) { + if (ok) { success.set(true); Map<String,Permission> newMap = user.newMap(); boolean willLog = aaf.access.willLog(Level.DEBUG); - for(Perm perm : fp.value.getPerm()) { + for (Perm perm : fp.value.getPerm()) { user.add(newMap, new AAFPermission(perm.getNs(),perm.getType(),perm.getInstance(),perm.getAction(),perm.getRoles())); - if(willLog) { + if (willLog) { aaf.access.log(Level.DEBUG, name,"has",perm.getType(),perm.getInstance(),perm.getAction()); } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java index 2cfe1227..d4d11bbb 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTaf.java @@ -84,27 +84,27 @@ public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpT // Note: Either Carbon or Silicon based LifeForms ok String authz = req.getHeader("Authorization"); - if(authz != null && authz.startsWith("Basic ")) { - if(warn&&!req.isSecure()) { + if (authz != null && authz.startsWith("Basic ")) { + if (warn&&!req.isSecure()) { aaf.access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); } try { final CachedBasicPrincipal bp; - if(req.getUserPrincipal() instanceof CachedBasicPrincipal) { + if (req.getUserPrincipal() instanceof CachedBasicPrincipal) { bp = (CachedBasicPrincipal)req.getUserPrincipal(); } else { bp = new CachedBasicPrincipal(this,authz,aaf.getRealm(),aaf.userExpires); } // First try Cache final User<AAFPermission> usr = getUser(bp); - if(usr != null + if (usr != null && usr.principal instanceof GetCred && Hash.isEqual(bp.getCred(),((GetCred)usr.principal).getCred())) { return new BasicHttpTafResp(aaf.access,bp,bp.getName()+" authenticated by cached AAF password",RESP.IS_AUTHENTICATED,resp,aaf.getRealm(),false); } Miss miss = missed(bp.getName(), bp.getCred()); - if(miss!=null && !miss.mayContinue()) { + if (miss!=null && !miss.mayContinue()) { return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, "User/Pass Retry limit exceeded"), RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),true); @@ -120,8 +120,8 @@ public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpT @Override public BasicHttpTafResp code(Rcli<?> client) throws CadiException, APIException { Future<String> fp = client.read("/authn/basicAuth", "text/plain"); - if(fp.get(aaf.timeout)) { - if(usr!=null) { + if (fp.get(aaf.timeout)) { + if (usr!=null) { usr.principal = bp; } else { addUser(new User<AAFPermission>(bp,aaf.userExpires)); @@ -130,7 +130,7 @@ public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpT } else { // Note: AddMiss checks for miss==null, and is part of logic boolean rv= addMiss(bp.getName(),bp.getCred()); - if(rv) { + if (rv) { return new BasicHttpTafResp(aaf.access,null,buildMsg(bp,req, "user/pass combo invalid via AAF from " + req.getRemoteAddr()), RESP.TRY_AUTHENTICATING,resp,aaf.getRealm(),true); @@ -163,10 +163,10 @@ public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpT private String buildMsg(Principal pr, HttpServletRequest req, Object... msg) { StringBuilder sb = new StringBuilder(); - for(Object s : msg) { + for (Object s : msg) { sb.append(s.toString()); } - if(pr!=null) { + if (pr!=null) { sb.append(" for "); sb.append(pr.getName()); } @@ -181,7 +181,7 @@ public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpT public Resp revalidate(CachedPrincipal prin, Object state) { // !!!! TEST THIS.. Things may not be revalidated, if not BasicPrincipal - if(prin instanceof BasicPrincipal) { + if (prin instanceof BasicPrincipal) { Future<String> fp; try { Rcli<CLIENT> userAAF = aaf.client(Config.AAF_DEFAULT_VERSION).forUser(aaf.transferSS((BasicPrincipal)prin)); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java index db6ae963..43e71e56 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFTrustChecker.java @@ -53,7 +53,7 @@ public class AAFTrustChecker implements TrustChecker { id = env.getProperty(Config.CADI_ALIAS,env.getProperty(Config.AAF_APPID)); // share between components String str = env.getProperty(Config.CADI_TRUST_PERM); AAFPermission temp=null; - if(str!=null) { + if (str!=null) { String[] sp = Split.splitTrim('|', str); switch(sp.length) { case 3: @@ -72,7 +72,7 @@ public class AAFTrustChecker implements TrustChecker { id = access.getProperty(Config.CADI_ALIAS,access.getProperty(Config.AAF_APPID,null)); // share between components String str = access.getProperty(Config.CADI_TRUST_PERM,null); AAFPermission temp=null; - if(str!=null) { + if (str!=null) { String[] sp = Split.splitTrim('|', str); switch(sp.length) { case 3: @@ -111,11 +111,11 @@ public class AAFTrustChecker implements TrustChecker { } String principalName = tresp.getPrincipal().getName(); - if(principalName.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept + if (principalName.equals(id) // We do trust our own App Components: if a trust entry is made with self, always accept || lur.fish(tresp.getPrincipal(), perm)) { // Have Perm set by Config.CADI_TRUST_PERM String desc = " " + flds[0] + " validated using " + flds[2] + " by " + flds[1] + ','; return new TrustTafResp(tresp, new TrustPrincipal(tresp.getPrincipal(), flds[0]), desc); - } else if(principalName.equals(flds[0])) { // Ignore if same identity + } else if (principalName.equals(flds[0])) { // Ignore if same identity return tresp; } else { String desc = tresp.getPrincipal().getName() + " requested trust as " + flds[0] + ", but does not have Authorization"; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java index 3f6d7475..09f007c9 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLocator.java @@ -66,7 +66,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException { aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL, null); - if(aaf_locator_host==null) { + if (aaf_locator_host==null) { aaf_locator_uri = null; } else { try { @@ -82,19 +82,19 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> this.access = access; String lat = access.getProperty(Config.CADI_LATITUDE,null); String lng = access.getProperty(Config.CADI_LONGITUDE,null); - if(lat==null || lng==null) { + if (lat==null || lng==null) { throw new LocatorException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " properties are required."); } else { latitude = Double.parseDouble(lat); longitude = Double.parseDouble(lng); } - if(name.startsWith(Defaults.AAF_NS)) { + if (name.startsWith(Defaults.AAF_NS)) { String root_ns = access.getProperty(Config.AAF_ROOT_NS, null); - if(root_ns!=null) { + if (root_ns!=null) { name=name.replace(Defaults.AAF_NS, root_ns); } } - if(name.startsWith("http")) { // simple URL + if (name.startsWith("http")) { // simple URL this.name = name; this.version = Config.AAF_DEFAULT_VERSION; } else { @@ -118,11 +118,11 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> String version = Config.AAF_DEFAULT_VERSION; String pathInfo = null; int prev = key.indexOf("/locate"); - if(prev>0) { + if (prev>0) { prev = key.indexOf('/',prev+6); - if(prev>0) { + if (prev>0) { int next = key.indexOf('/',++prev); - if(next>0) { + if (next>0) { name = key.substring(prev, next); pathInfo=key.substring(next); } else { @@ -141,11 +141,11 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> } } - if(key.startsWith("http")) { - if(name!=null) { - if(locatorCreator != null) { + if (key.startsWith("http")) { + if (name!=null) { + if (locatorCreator != null) { AbsAAFLocator<?> aal = locatorCreator.create(name, version); - if(pathInfo!=null) { + if (pathInfo!=null) { aal.setPathInfo(pathInfo); } return aal; @@ -168,7 +168,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> protected static String nameFromLocatorURI(URI locatorURI) { String[] path = Split.split('/', locatorURI.getPath()); - if(path.length>2 && "locate".equals(path[1])) { + if (path.length>2 && "locate".equals(path[1])) { return path[2]; } else { return locatorURI.toString(); @@ -185,7 +185,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> public static void setCreatorSelf(final String hostname, final int port) { - if(locatorCreator!=null) { + if (locatorCreator!=null) { locatorCreator.setSelf(hostname,port); } } @@ -202,8 +202,8 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> private final boolean _refresh() { boolean rv = false; long now=System.currentTimeMillis(); - if(noEntries()) { - if(earliest<now) { + if (noEntries()) { + if (earliest<now) { synchronized(epList) { rv = refresh(); earliest = now + refreshWait; // call only up to 10 seconds. @@ -221,9 +221,9 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public URI get(Item item) throws LocatorException { - if(item==null) { + if (item==null) { return null; - } else if(item instanceof AAFLItem) { + } else if (item instanceof AAFLItem) { return getURI(((AAFLItem)item).uri); } else { throw new LocatorException(item.getClass().getName() + " does not belong to AAFLocator"); @@ -233,16 +233,16 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public boolean hasItems() { boolean isEmpty = epList.isEmpty(); - if(!isEmpty) { - for(Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) { + if (!isEmpty) { + for (Iterator<EP> iter = epList.iterator(); iter.hasNext(); ) { EP ep = iter.next(); - if(ep.valid) { + if (ep.valid) { return true; } } isEmpty = true; } - if(_refresh()) { // is refreshed... check again + if (_refresh()) { // is refreshed... check again isEmpty = epList.isEmpty(); } return !isEmpty; @@ -250,8 +250,8 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public void invalidate(Item item) throws LocatorException { - if(item!=null) { - if(item instanceof AAFLItem) { + if (item!=null) { + if (item instanceof AAFLItem) { AAFLItem ali =(AAFLItem)item; EP ep = ali.ep; synchronized(epList) { @@ -267,7 +267,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public Item best() throws LocatorException { - if(!hasItems()) { + if (!hasItems()) { throw new LocatorException("No Entries found for '" + aaf_locator_uri.toString() + "/locate/" + name + ':' + version + '\''); } List<EP> lep = new ArrayList<>(); @@ -275,14 +275,14 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> // Note: Deque is sorted on the way by closest distance Iterator<EP> iter = getIterator(); EP ep; - while(iter.hasNext()) { + while (iter.hasNext()) { ep = iter.next(); - if(ep.valid) { - if(first==null) { + if (ep.valid) { + if (first==null) { first = ep; lep.add(first); } else { - if(Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues. + if (Math.abs(ep.distance-first.distance)<.1) { // allow for nearby/precision issues. lep.add(ep); } else { break; @@ -298,7 +298,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> default: int rand = sr.nextInt(); // Sonar chokes without. int i = Math.abs(rand)%lep.size(); - if(i<0) { + if (i<0) { return null; } else { return new AAFLItem(iter,lep.get(i)); @@ -309,7 +309,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> private Iterator<EP> getIterator() { Object[] epa = epList.toArray(); - if(epa.length==0) { + if (epa.length==0) { _refresh(); epa = epList.toArray(); } @@ -329,12 +329,12 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public boolean hasNext() { - if(idx<0) { + if (idx<0) { return false; } else { Object obj; - while(idx<epa.length) { - if((obj=epa[idx])==null || !((EP)obj).valid) { + while (idx<epa.length) { + if ((obj=epa[idx])==null || !((EP)obj).valid) { ++idx; continue; } @@ -346,7 +346,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public EP next() { - if(!hasNext() ) { + if (!hasNext() ) { throw new NoSuchElementException(); } return (EP)epa[idx++]; @@ -354,7 +354,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public void remove() { - if(idx>=0 && idx<epa.length) { + if (idx>=0 && idx<epa.length) { synchronized(epList) { epList.remove(epa[idx]); } @@ -366,7 +366,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> public Item first() { Iterator<EP> iter = getIterator(); EP ep = AAFLItem.next(iter); - if(ep==null) { + if (ep==null) { return null; } return new AAFLItem(iter,ep); @@ -374,23 +374,23 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public Item next(Item prev) throws LocatorException { - if(prev==null) { + if (prev==null) { StringBuilder sb = new StringBuilder("Locator Item passed in next(item) is null."); int lines = 0; - for(StackTraceElement st : Thread.currentThread().getStackTrace()) { + for (StackTraceElement st : Thread.currentThread().getStackTrace()) { sb.append("\n\t"); sb.append(st.toString()); - if(++lines > 5) { + if (++lines > 5) { sb.append("\n\t..."); break; } } access.log(Level.ERROR, sb); } else { - if(prev instanceof AAFLItem) { + if (prev instanceof AAFLItem) { AAFLItem ali = (AAFLItem)prev; EP ep = AAFLItem.next(ali.iter); - if(ep!=null) { + if (ep!=null) { return new AAFLItem(ali.iter,ep); } } else { @@ -413,7 +413,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> private static EP next(Iterator<EP> iter) { EP ep=null; - while(iter.hasNext() && (ep==null || !ep.valid)) { + while (iter.hasNext() && (ep==null || !ep.valid)) { ep = iter.next(); } return ep; @@ -441,9 +441,9 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> @Override public int compareTo(EP o) { - if(distance<o.distance) { + if (distance<o.distance) { return -1; - } else if(distance>o.distance) { + } else if (distance>o.distance) { return 1; } else { return 0; @@ -491,7 +491,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> protected abstract URI getURI(); protected URI getURI(URI rv) throws LocatorException { - if(additional) { + if (additional) { try { return new URI(rv.getScheme(),rv.getUserInfo(),rv.getHost(),rv.getPort(),pathInfo,query,fragment); } catch (URISyntaxException e) { diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java index e347ffb6..cfecc533 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AbsAAFLur.java @@ -71,15 +71,15 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE @Override public final boolean handles(Principal principal) { - if(preemptiveLur!=null) { - if(preemptiveLur.handles(principal)) { + if (preemptiveLur!=null) { + if (preemptiveLur.handles(principal)) { return true; } } String userName=principal.getName(); - if(userName!=null) { - for(String s : supports) { - if(userName.endsWith(s)) + if (userName!=null) { + for (String s : supports) { + if (userName.endsWith(s)) return true; } } @@ -91,25 +91,25 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE // This is where you build AAF CLient Code. Answer the question "Is principal "bait" in the "pond" public boolean fish(Principal bait, Permission ... pond) { - if(preemptiveLur!=null && preemptiveLur.handles(bait)) { + if (preemptiveLur!=null && preemptiveLur.handles(bait)) { return preemptiveLur.fish(bait, pond); } else { - if(pond==null) { + if (pond==null) { return false; } - if(isDebug(bait)) { + if (isDebug(bait)) { boolean rv = false; StringBuilder sb = new StringBuilder("Log for "); sb.append(bait); - if(handles(bait)) { + if (handles(bait)) { User<PERM> user = getUser(bait); - if(user==null) { + if (user==null) { sb.append("\n\tUser is not in Cache"); } else { - if(user.noPerms()) { + if (user.noPerms()) { sb.append("\n\tUser has no Perms"); } - if(user.permExpired()) { + if (user.permExpired()) { sb.append("\n\tUser's perm expired ["); sb.append(new Date(user.permExpires())); sb.append(']'); @@ -119,15 +119,15 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE sb.append(']'); } } - if(user==null || user.permsUnloaded() || user.permExpired()) { + if (user==null || user.permsUnloaded() || user.permExpired()) { user = loadUser(bait); sb.append("\n\tloadUser called"); } for (Permission p : pond) { - if(user==null) { + if (user==null) { sb.append("\n\tUser was not Loaded"); break; - } else if(user.contains(p)) { + } else if (user.contains(p)) { sb.append("\n\tUser contains "); sb.append(p.getKey()); rv = true; @@ -136,7 +136,7 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE sb.append(p.getKey()); List<Permission> perms = new ArrayList<>(); user.copyPermsTo(perms); - for(Permission perm : perms) { + for (Permission perm : perms) { sb.append("\n\t\t"); sb.append(perm.getKey()); } @@ -151,16 +151,16 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE return rv; } else { boolean rv = false; - if(handles(bait)) { + if (handles(bait)) { User<PERM> user = getUser(bait); - if(user==null || user.permsUnloaded() || user.permExpired()) { + if (user==null || user.permsUnloaded() || user.permExpired()) { user = loadUser(bait); } - if(user==null) { + if (user==null) { return false; } else { - for(Permission p : pond) { - if(rv=user.contains(p)) { + for (Permission p : pond) { + if (rv=user.contains(p)) { break; } } @@ -172,21 +172,21 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE } public void fishAll(Principal bait, List<Permission> perms) { - if(preemptiveLur!=null && preemptiveLur.handles(bait)) { + if (preemptiveLur!=null && preemptiveLur.handles(bait)) { preemptiveLur.fishAll(bait, perms); } else { - if(isDebug(bait)) { + if (isDebug(bait)) { StringBuilder sb = new StringBuilder("Log for "); sb.append(bait); - if(handles(bait)) { + if (handles(bait)) { User<PERM> user = getUser(bait); - if(user==null) { + if (user==null) { sb.append("\n\tUser is not in Cache"); } else { - if(user.noPerms()) { + if (user.noPerms()) { sb.append("\n\tUser has no Perms"); } - if(user.permExpired()) { + if (user.permExpired()) { sb.append("\n\tUser's perm expired ["); sb.append(new Date(user.permExpires())); sb.append(']'); @@ -196,16 +196,16 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE sb.append(']'); } } - if(user==null || user.permsUnloaded() || user.permExpired()) { + if (user==null || user.permsUnloaded() || user.permExpired()) { user = loadUser(bait); sb.append("\n\tloadUser called"); } - if(user==null) { + if (user==null) { sb.append("\n\tUser was not Loaded"); } else { sb.append("\n\tCopying Perms "); user.copyPermsTo(perms); - for(Permission p : perms) { + for (Permission p : perms) { sb.append("\n\t\t"); sb.append(p.getKey()); } @@ -217,12 +217,12 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE } aaf.access.log(Level.INFO, sb); } else { - if(handles(bait)) { + if (handles(bait)) { User<PERM> user = getUser(bait); - if(user==null || user.permsUnloaded() || user.permExpired()) { + if (user==null || user.permsUnloaded() || user.permExpired()) { user = loadUser(bait); } - if(user!=null) { + if (user!=null) { user.copyPermsTo(perms); } } @@ -236,13 +236,13 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE } private boolean isDebug(Principal p) { - if(debug!=null) { - if(debug.length==1 && "all".equals(debug[0])) { + if (debug!=null) { + if (debug.length==1 && "all".equals(debug[0])) { return true; } String name = p.getName(); - for(String s : debug) { - if(s.equals(name)) { + for (String s : debug) { + if (s.equals(name)) { return true; } } @@ -260,15 +260,15 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE */ public<A> void fishOneOf(Principal princ, A obj, String type, String instance, List<Action<A>> actions) { User<PERM> user = getUser(princ); - if(user==null || user.permsUnloaded() || user.permExpired()) { + if (user==null || user.permsUnloaded() || user.permExpired()) { user = loadUser(princ); } - if(user!=null) { + if (user!=null) { ReuseAAFPermission perm = new ReuseAAFPermission(type,instance); - for(Action<A> action : actions) { + for (Action<A> action : actions) { perm.setAction(action.getName()); - if(user.contains(perm)) { - if(action.exec(obj))return; + if (user.contains(perm)) { + if (action.exec(obj))return; } } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java index 83204d1b..a2642221 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Agent.java @@ -112,10 +112,10 @@ public class Agent { public static void main(String[] args) { int exitCode = 0; doExit = true; - if(args.length>0 && "cadi".equals(args[0])) { + if (args.length>0 && "cadi".equals(args[0])) { String[] newArgs = new String[args.length-1]; System.arraycopy(args, 1, newArgs, 0, newArgs.length); - if(newArgs.length==0) { + if (newArgs.length==0) { System.out.println(HASHES); System.out.println("Note: Cadi CmdLine is a separate component. When running with\n\t" + "Agent, always preface with \"cadi\",\n\tex: cadi keygen [<keyfile>]"); @@ -127,7 +127,7 @@ public class Agent { AAFSSO aafsso=null; PropAccess access; - if(args.length>1 && args[0].equals("validate") ) { + if (args.length>1 && args[0].equals("validate") ) { int idx = args[1].indexOf('='); aafsso = null; access = new PropAccess( @@ -138,7 +138,7 @@ public class Agent { aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() { @Override public Properties process(String[] args, Properties props) { - if(args.length>1) { + if (args.length>1) { if (!args[0].equals("keypairgen")) { props.put("aaf_id", args[1]); } @@ -149,23 +149,23 @@ public class Agent { access = aafsso.access(); } - if(aafsso!=null && aafsso.loginOnly()) { + if (aafsso!=null && aafsso.loginOnly()) { aafsso.setLogDefault(); aafsso.writeFiles(); System.out.println("AAF SSO information created in ~/.aaf"); } else { env = new RosettaEnv(access.getProperties()); Deque<String> cmds = new ArrayDeque<String>(); - for(String p : args) { - if("-noexit".equalsIgnoreCase(p)) { + for (String p : args) { + if ("-noexit".equalsIgnoreCase(p)) { doExit = false; - } else if(p.indexOf('=') < 0) { + } else if (p.indexOf('=') < 0) { cmds.add(p); } } - if(cmds.size()==0) { - if(aafsso!=null) { + if (cmds.size()==0) { + if (aafsso!=null) { aafsso.setLogDefault(); } // NOTE: CHANGE IN CMDS should be reflected in AAFSSO constructor, to get FQI->aaf-id or not @@ -209,18 +209,18 @@ public class Agent { Trans trans = env.newTrans(); String token; - if((token=access.getProperty("oauth_token"))!=null) { + if ((token=access.getProperty("oauth_token"))!=null) { trans.setProperty("oauth_token", token); } try { - if(aafsso!=null) { + if (aafsso!=null) { // show Std out again aafsso.setLogDefault(); aafsso.setStdErrDefault(); // if CM_URL can be obtained, add to sso.props, if written String cm_url = getProperty(access,env,false, Config.CM_URL,Config.CM_URL+": "); - if(cm_url!=null) { + if (cm_url!=null) { aafsso.addProp(Config.CM_URL, cm_url); } aafsso.writeFiles(); @@ -255,7 +255,7 @@ public class Agent { keypairGen(trans, access, cmds); break; case "config": - if(access.getProperty(Config.CADI_PROP_FILES)!=null) { + if (access.getProperty(Config.CADI_PROP_FILES)!=null) { // Get Properties from initialization Prop Files config(trans,access,null,cmds); } else { @@ -280,11 +280,11 @@ public class Agent { } finally { StringBuilder sb = new StringBuilder(); trans.auditTrail(4, sb, Trans.REMOTE); - if(sb.length()>0) { + if (sb.length()>0) { trans.info().log("Trans Info\n",sb); } } - if(aafsso!=null) { + if (aafsso!=null) { aafsso.close(); } } @@ -292,13 +292,13 @@ public class Agent { e.printStackTrace(); } } - if(exitCode != 0 && doExit) { + if (exitCode != 0 && doExit) { System.exit(exitCode); } } private static synchronized AAFCon<?> aafcon(PropAccess access) throws APIException, CadiException, LocatorException { - if(aafcon==null) { + if (aafcon==null) { aafcon = new AAFConHttp(access,Config.CM_URL); } return aafcon; @@ -306,17 +306,17 @@ public class Agent { private static String getProperty(PropAccess pa, Env env, boolean secure, String tag, String prompt, Object ... def) { String value; - if((value=pa.getProperty(tag))==null) { - if(secure) { + if ((value=pa.getProperty(tag))==null) { + if (secure) { value = new String(AAFSSO.cons.readPassword(prompt, def)); } else { value = AAFSSO.cons.readLine(prompt,def).trim(); } - if(value!=null) { - if(value.length()>0) { + if (value!=null) { + if (value.length()>0) { pa.setProperty(tag,value); env.setProperty(tag,value); - } else if(def.length==1) { + } else if (def.length==1) { value=def[0].toString(); pa.setProperty(tag,value); env.setProperty(tag,value); @@ -327,7 +327,7 @@ public class Agent { } private static String fqi(Deque<String> cmds) { - if(cmds.size()<1) { + if (cmds.size()<1) { String alias = env.getProperty(Config.CADI_ALIAS); return alias!=null?alias:AAFSSO.cons.readLine("AppID: "); } @@ -335,7 +335,7 @@ public class Agent { } private static String machine(Deque<String> cmds) throws UnknownHostException { - if(cmds.size()>0) { + if (cmds.size()>0) { return cmds.removeFirst(); } else { String mach = env.getProperty(Config.HOSTNAME); @@ -345,7 +345,7 @@ public class Agent { private static String[] machines(Deque<String> cmds) { String machines; - if(cmds.size()>0) { + if (cmds.size()>0) { machines = cmds.removeFirst(); } else { machines = AAFSSO.cons.readLine("Machines (sep by ','): "); @@ -365,11 +365,11 @@ public class Agent { arti.setCa(AAFSSO.cons.readLine("CA: (%s): ","aaf")); String resp = AAFSSO.cons.readLine("Types [file,pkcs12,jks,script] (%s): ", PKCS12); - for(String s : Split.splitTrim(',', resp)) { + for (String s : Split.splitTrim(',', resp)) { arti.getType().add(s); } // Always do Script - if(!resp.contains(SCRIPT)) { + if (!resp.contains(SCRIPT)) { arti.getType().add(SCRIPT); } @@ -384,7 +384,7 @@ public class Agent { TimeTaken tt = trans.start("Create Artifact", Env.REMOTE); try { Future<Artifacts> future = aafcon.client(CM_VER).create("/cert/artifacts", artifactsDF, artifacts); - if(future.get(TIMEOUT)) { + if (future.get(TIMEOUT)) { trans.info().printf("Call to AAF Certman successful %s, %s",arti.getMechid(), arti.getMachine()); } else { trans.error().printf("Call to AAF Certman failed, %s", @@ -396,10 +396,10 @@ public class Agent { } private static String toNotification(String notification) { - if(notification==null) { + if (notification==null) { notification=""; - } else if(notification.length()>0) { - if(notification.indexOf(':')<0) { + } else if (notification.length()>0) { + if (notification.indexOf(':')<0) { notification = "mailto:" + notification; } } @@ -416,17 +416,17 @@ public class Agent { Future<Artifacts> future = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF,"Authorization","Bearer " + trans.getProperty("oauth_token")); - if(future.get(TIMEOUT)) { + if (future.get(TIMEOUT)) { boolean printed = false; - for(Artifact a : future.value.getArtifact()) { + for (Artifact a : future.value.getArtifact()) { AAFSSO.cons.printf("AppID: %s\n",a.getMechid()); AAFSSO.cons.printf(" Sponsor: %s\n",a.getSponsor()); AAFSSO.cons.printf("Machine: %s\n",a.getMachine()); AAFSSO.cons.printf("CA: %s\n",a.getCa()); StringBuilder sb = new StringBuilder(); boolean first = true; - for(String t : a.getType()) { - if(first) {first=false;} + for (String t : a.getType()) { + if (first) {first=false;} else{sb.append(',');} sb.append(t); } @@ -438,7 +438,7 @@ public class Agent { AAFSSO.cons.printf("Notification %s\n",a.getNotification()); printed = true; } - if(!printed) { + if (!printed) { AAFSSO.cons.printf("Artifact for %s %s does not exist\n", mechID, machine); } } else { @@ -453,7 +453,7 @@ public class Agent { String mechID = fqi(cmds); String machine = machine(cmds); String[] newmachs = machines(cmds); - if(machine==null || newmachs == null) { + if (machine==null || newmachs == null) { trans.error().log("No machines listed to copy to"); } else { TimeTaken tt = trans.start("Copy Artifact", Env.REMOTE); @@ -461,13 +461,13 @@ public class Agent { Future<Artifacts> future = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(future.get(TIMEOUT)) { + if (future.get(TIMEOUT)) { boolean printed = false; - for(Artifact a : future.value.getArtifact()) { - for(String m : newmachs) { + for (Artifact a : future.value.getArtifact()) { + for (String m : newmachs) { a.setMachine(m); Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, future.value); - if(fup.get(TIMEOUT)) { + if (fup.get(TIMEOUT)) { trans.info().printf("Copy of %s %s successful to %s",mechID,machine,m); } else { trans.error().printf("Call to AAF Certman failed, %s", @@ -477,7 +477,7 @@ public class Agent { printed = true; } } - if(!printed) { + if (!printed) { AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine); } } else { @@ -498,9 +498,9 @@ public class Agent { Future<Artifacts> fread = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(fread.get(TIMEOUT)) { + if (fread.get(TIMEOUT)) { Artifacts artifacts = new Artifacts(); - for(Artifact a : fread.value.getArtifact()) { + for (Artifact a : fread.value.getArtifact()) { Artifact arti = new Artifact(); artifacts.getArtifact().add(arti); @@ -510,18 +510,18 @@ public class Agent { arti.setCa(AAFSSO.cons.readLine("CA: (%s): ",a.getCa())); StringBuilder sb = new StringBuilder(); boolean first = true; - for(String t : a.getType()) { - if(first) {first=false;} + for (String t : a.getType()) { + if (first) {first=false;} else{sb.append(',');} sb.append(t); } String resp = AAFSSO.cons.readLine("Types [file,jks,pkcs12] (%s): ", sb); - for(String s : Split.splitTrim(',', resp)) { + for (String s : Split.splitTrim(',', resp)) { arti.getType().add(s); } // Always do Script - if(!resp.contains(SCRIPT)) { + if (!resp.contains(SCRIPT)) { arti.getType().add(SCRIPT); } @@ -533,11 +533,11 @@ public class Agent { arti.setNotification(toNotification(AAFSSO.cons.readLine("Notification (%s):", a.getNotification()))); } - if(artifacts.getArtifact().size()==0) { + if (artifacts.getArtifact().size()==0) { AAFSSO.cons.printf("Artifact for %s %s does not exist", mechID, machine); } else { Future<Artifacts> fup = aafcon.client(CM_VER).update("/cert/artifacts", artifactsDF, artifacts); - if(fup.get(TIMEOUT)) { + if (fup.get(TIMEOUT)) { trans.info().printf("Call to AAF Certman successful %s, %s",mechID,machine); } else { trans.error().printf("Call to AAF Certman failed, %s", @@ -562,7 +562,7 @@ public class Agent { Future<Void> future = aafcon.client(CM_VER) .delete("/cert/artifacts/"+mechid+"/"+machine,"application/json" ); - if(future.get(TIMEOUT)) { + if (future.get(TIMEOUT)) { trans.info().printf("Call to AAF Certman successful %s, %s",mechid,machine); } else { trans.error().printf("Call to AAF Certman failed, %s %s, %s", @@ -581,7 +581,7 @@ public class Agent { String machine = machine(cmds); String[] fqdns = Split.split(':', machine); String key; - if(fqdns.length>1) { + if (fqdns.length>1) { key = fqdns[0]; machine = fqdns[1]; } else { @@ -592,27 +592,27 @@ public class Agent { try { Future<Artifacts> acf = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+key, artifactsDF); - if(acf.get(TIMEOUT)) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + if (acf.get(TIMEOUT)) { + if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { AAFSSO.cons.printf("===> There are no artifacts for %s on machine '%s'\n", mechID, key); } else { - for(Artifact a : acf.value.getArtifact()) { + for (Artifact a : acf.value.getArtifact()) { String osID = System.getProperty("user.name"); - if(a.getOsUser().equals(osID)) { + if (a.getOsUser().equals(osID)) { CertificateRequest cr = new CertificateRequest(); cr.setMechid(a.getMechid()); cr.setSponsor(a.getSponsor()); - for(int i=0;i<fqdns.length;++i) { + for (int i=0;i<fqdns.length;++i) { cr.getFqdns().add(fqdns[i]); } Future<String> f = aafcon.client(CM_VER) .updateRespondString("/cert/" + a.getCa()+"?withTrust",reqDF, cr); - if(f.get(TIMEOUT)) { + if (f.get(TIMEOUT)) { CertInfo capi = certDF.newData().in(TYPE.JSON).load(f.body()).asObject(); - for(String type : a.getType()) { + for (String type : a.getType()) { PlaceArtifact pa = placeArtifact.get(type); - if(pa!=null) { - if(rv = pa.place(trans, capi, a,machine)) { + if (pa!=null) { + if (rv = pa.place(trans, capi, a,machine)) { notifyPlaced(a,rv); } } @@ -646,28 +646,28 @@ public class Agent { try { Future<Artifacts> acf = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(acf.get(TIMEOUT)) { + if (acf.get(TIMEOUT)) { // Have to wait for JDK 1.7 source... //switch(artifact.getType()) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { AAFSSO.cons.printf("No Artifacts found for %s on %s ", mechID, machine); } else { String id = aafcon.defID(); boolean allowed; - for(Artifact a : acf.value.getArtifact()) { + for (Artifact a : acf.value.getArtifact()) { allowed = id!=null && (id.equals(a.getSponsor()) || (id.equals(a.getMechid()) && aafcon.securityInfo().defSS.getClass().isAssignableFrom(HBasicAuthSS.class))); - if(!allowed) { + if (!allowed) { Future<String> pf = aafcon.client(CM_VER).read("/cert/may/" + a.getNs()+"|certman|"+a.getCa()+"|showpass","*/*"); - if(pf.get(TIMEOUT)) { + if (pf.get(TIMEOUT)) { allowed = true; } else { trans.error().log(errMsg.toMsg(pf)); } } - if(allowed) { + if (allowed) { File dir = new File(a.getDir()); Properties props = new Properties(); FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".cred.props")); @@ -681,12 +681,12 @@ public class Agent { } File f = new File(dir,a.getNs()+".keyfile"); - if(f.exists()) { + if (f.exists()) { Symm symm = Symm.obtain(f); - for(Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) { + for (Iterator<Entry<Object,Object>> iter = props.entrySet().iterator(); iter.hasNext();) { Entry<Object,Object> en = iter.next(); - if(en.getValue().toString().startsWith("enc:")) { + if (en.getValue().toString().startsWith("enc:")) { System.out.printf("%s=%s\n", en.getKey(), symm.depass(en.getValue().toString())); } } @@ -712,9 +712,9 @@ public class Agent { File dir = new File(access.getProperty(Config.CADI_ETCDIR,".")); // default to current Directory File f = new File(dir,ns+".key"); - if(f.exists()) { + if (f.exists()) { String line = AAFSSO.cons.readLine("%s exists. Overwrite? (y/n): ", f.getCanonicalPath()); - if(!"Y".equalsIgnoreCase(line)) { + if (!"Y".equalsIgnoreCase(line)) { System.out.println("Canceling..."); return; } @@ -733,9 +733,9 @@ public class Agent { final String fqi = fqi(cmds); final String rootFile = FQI.reverseDomain(fqi); final File dir = new File(pa.getProperty(Config.CADI_ETCDIR, ".")); - if(dir.exists()) { + if (dir.exists()) { System.out.println("Writing to " + dir.getCanonicalFile()); - } else if(dir.mkdirs()) { + } else if (dir.mkdirs()) { System.out.println("Created directory " + dir.getCanonicalFile()); } else { System.err.println("Unable to create or write to " + dir.getCanonicalPath()); @@ -751,14 +751,14 @@ public class Agent { PrintStream psProps; File fLocProps = new File(dir,rootFile + ".location.props"); - if(!fLocProps.exists()) { + if (!fLocProps.exists()) { psProps = new PrintStream(new FileOutputStream(fLocProps)); try { psProps.println(HASHES); psProps.print("# Configuration File generated on "); psProps.println(new Date().toString()); psProps.println(HASHES); - for(String tag : LOC_TAGS) { + for (String tag : LOC_TAGS) { psProps.print(tag); psProps.print('='); psProps.println(getProperty(pa, trans, false, tag, "%s: ",tag)); @@ -789,7 +789,7 @@ public class Agent { psProps.println(fLocProps.getCanonicalPath()); File fkf = new File(dir,rootFile+".keyfile"); - if(!fkf.exists()) { + if (!fkf.exists()) { CmdLine.main(new String[] {"keygen",fkf.toString()}); } Symm filesymm = Symm.obtain(fkf); @@ -803,30 +803,30 @@ public class Agent { String cts = pa.getProperty(Config.CADI_TRUSTSTORE); - if(cts!=null) { + if (cts!=null) { File origTruststore = new File(cts); - if(!origTruststore.exists()) { + if (!origTruststore.exists()) { // Try same directory as cadi_prop_files String cpf = pa.getProperty(Config.CADI_PROP_FILES); - if(cpf!=null) { - for(String f : Split.split(File.pathSeparatorChar, cpf)) { + if (cpf!=null) { + for (String f : Split.split(File.pathSeparatorChar, cpf)) { File fcpf = new File(f); - if(fcpf.exists()) { + if (fcpf.exists()) { int lastSep = cts.lastIndexOf(File.pathSeparator); origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts); - if(origTruststore.exists()) { + if (origTruststore.exists()) { break; } } } - if(!origTruststore.exists()) { + if (!origTruststore.exists()) { throw new CadiException(cts + " does not exist"); } } } File newTruststore = new File(dir,origTruststore.getName()); - if(!newTruststore.exists()) { + if (!newTruststore.exists()) { Files.copy(origTruststore.toPath(), newTruststore.toPath()); } @@ -834,31 +834,31 @@ public class Agent { directedPut(pa, filesymm, normal,creds, Config.CADI_TRUSTSTORE_PASSWORD,null); } - if(aafcon!=null) { // get Properties from Remote AAF + if (aafcon!=null) { // get Properties from Remote AAF final String locator = getProperty(pa,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "); Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator)) .read("/configure/"+fqi+"/aaf", configDF); - if(acf.get(TIMEOUT)) { - for(Props props : acf.value.getProps()) { + if (acf.get(TIMEOUT)) { + for (Props props : acf.value.getProps()) { directedPut(pa, filesymm, normal,creds, props.getTag(),props.getValue()); } ok = true; - } else if(acf.code()==401){ + } else if (acf.code()==401){ trans.error().log("Bad Password sent to AAF"); } else { trans.error().log(errMsg.toMsg(acf)); } } else { String cpf = pa.getProperty(Config.CADI_PROP_FILES); - if(cpf!=null){ - for(String f : Split.split(File.pathSeparatorChar, cpf)) { + if (cpf!=null){ + for (String f : Split.split(File.pathSeparatorChar, cpf)) { System.out.format("Reading %s\n",f); FileInputStream fis = new FileInputStream(f); try { Properties props = new Properties(); props.load(fis); - for(Entry<Object, Object> prop : props.entrySet()) { + for (Entry<Object, Object> prop : props.entrySet()) { directedPut(pa, filesymm, normal,creds, prop.getKey().toString(),prop.getValue().toString()); } } finally { @@ -868,21 +868,21 @@ public class Agent { } ok = true; } - if(ok) { - for(Entry<String, String> es : normal.entrySet()) { + if (ok) { + for (Entry<String, String> es : normal.entrySet()) { psProps.print(es.getKey()); psProps.print('='); psProps.println(es.getValue()); } - for(Entry<String, String> es : creds.entrySet()) { + for (Entry<String, String> es : creds.entrySet()) { psCredProps.print(es.getKey()); psCredProps.print('='); psCredProps.println(es.getValue()); } File newFile = new File(dir,rootFile+".props"); - if(newFile.exists()) { + if (newFile.exists()) { File backup = new File(dir,rootFile+".props.backup"); newFile.renameTo(backup); System.out.println("Backed up to " + backup.getCanonicalPath()); @@ -891,7 +891,7 @@ public class Agent { System.out.println("Created " + newFile.getCanonicalPath()); fProps = newFile; - if(fSecureProps.exists()) { + if (fSecureProps.exists()) { File backup = new File(dir,fSecureProps.getName()+".backup"); fSecureProps.renameTo(backup); System.out.println("Backed up to " + backup.getCanonicalPath()); @@ -925,17 +925,17 @@ public class Agent { private static List<String> LOC_TAGS = Arrays.asList(new String[] {Config.CADI_LATITUDE, Config.CADI_LONGITUDE}); private static void directedPut(final PropAccess orig, final Symm symm, final Map<String,String> main, final Map<String,String> secured, final String tag, final String value) throws IOException { - if(!LOC_TAGS.contains(tag)) { // Location already covered + if (!LOC_TAGS.contains(tag)) { // Location already covered String val = value==null?orig.getProperty(tag):value; - if(tag.endsWith("_password")) { - if(val.length()>4) { - if(val.startsWith("enc:")) { + if (tag.endsWith("_password")) { + if (val.length()>4) { + if (val.startsWith("enc:")) { val = orig.decrypt(val, true); } val = "enc:" + symm.enpass(val); } } - if(CRED_TAGS.contains(tag)) { + if (CRED_TAGS.contains(tag)) { secured.put(tag, val); } else { main.put(tag, val); @@ -950,12 +950,12 @@ public class Agent { @Override public Void code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<Perms> fc = client.read("/authz/perms/user/"+aafcon.defID(),permDF); - if(fc.get(aafcon.timeout)) { + if (fc.get(aafcon.timeout)) { System.out.print("Success connecting to "); System.out.println(client.getURI()); System.out.print(" Permissions for "); System.out.println(aafcon.defID()); - for(Perm p : fc.value.getPerm()) { + for (Perm p : fc.value.getPerm()) { System.out.print('\t'); System.out.print(p.getType()); System.out.print('|'); @@ -995,16 +995,16 @@ public class Agent { Future<Artifacts> acf = aafcon.client(CM_VER) .read("/cert/artifacts/"+mechID+'/'+machine, artifactsDF); - if(acf.get(TIMEOUT)) { + if (acf.get(TIMEOUT)) { // Have to wait for JDK 1.7 source... //switch(artifact.getType()) { - if(acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { + if (acf.value.getArtifact()==null || acf.value.getArtifact().isEmpty()) { AAFSSO.cons.printf("No Artifacts found for %s on %s", mechID, machine); } else { String id = aafcon.defID(); GregorianCalendar now = new GregorianCalendar(); - for(Artifact a : acf.value.getArtifact()) { - if(id.equals(a.getMechid())) { + for (Artifact a : acf.value.getArtifact()) { + if (id.equals(a.getMechid())) { File dir = new File(a.getDir()); Properties props = new Properties(); FileInputStream fis = new FileInputStream(new File(dir,a.getNs()+".props")); @@ -1017,14 +1017,14 @@ public class Agent { String prop; File f; - if((prop=trans.getProperty(Config.CADI_KEYFILE))==null || + if ((prop=trans.getProperty(Config.CADI_KEYFILE))==null || !(f=new File(prop)).exists()) { trans.error().printf("Keyfile must exist to check Certificates for %s on %s", a.getMechid(), a.getMachine()); } else { String ksf = trans.getProperty(Config.CADI_KEYSTORE); String ksps = trans.getProperty(Config.CADI_KEYSTORE_PASSWORD); - if(ksf==null || ksps == null) { + if (ksf==null || ksps == null) { trans.error().printf("Properties %s and %s must exist to check Certificates for %s on %s", Config.CADI_KEYSTORE, Config.CADI_KEYSTORE_PASSWORD,a.getMechid(), a.getMachine()); } else { @@ -1040,7 +1040,7 @@ public class Agent { X509Certificate cert = (X509Certificate)ks.getCertificate(mechID); String msg = null; - if(cert==null) { + if (cert==null) { msg = String.format("X509Certificate does not exist for %s on %s in %s", a.getMechid(), a.getMachine(), ksf); trans.error().log(msg); @@ -1049,7 +1049,7 @@ public class Agent { GregorianCalendar renew = new GregorianCalendar(); renew.setTime(cert.getNotAfter()); renew.add(GregorianCalendar.DAY_OF_MONTH,-1*a.getRenewDays()); - if(renew.after(now)) { + if (renew.after(now)) { msg = String.format("X509Certificate for %s on %s has been checked on %s. It expires on %s; it will not be renewed until %s.\n", a.getMechid(), a.getMachine(),Chrono.dateOnlyStamp(now),cert.getNotAfter(),Chrono.dateOnlyStamp(renew)); trans.info().log(msg); @@ -1059,7 +1059,7 @@ public class Agent { a.getMechid(), a.getMachine(),cert.getNotAfter()); cmds.offerLast(mechID); cmds.offerLast(machine); - if(placeCerts(trans,aafcon,cmds)) { + if (placeCerts(trans,aafcon,cmds)) { msg = String.format("X509Certificate for %s on %s has been renewed. Ensure services using are refreshed.\n", a.getMechid(), a.getMachine()); exitCode = 10; // Refreshed @@ -1070,7 +1070,7 @@ public class Agent { } } } - if(msg!=null) { + if (msg!=null) { FileOutputStream fos = new FileOutputStream(a.getDir()+'/'+a.getNs()+".msg"); try { fos.write(msg.getBytes()); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java index b5353828..7e91afae 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/ArtifactDir.java @@ -65,10 +65,10 @@ public abstract class ArtifactDir implements PlaceArtifact { try { // Obtain/setup directory as required dir = new File(arti.getDir()); - if(processed.get("dir")==null) { - if(!dir.exists()) { + if (processed.get("dir")==null) { + if (!dir.exists()) { Chmod.to755.chmod(dir); - if(!dir.mkdirs()) { + if (!dir.mkdirs()) { throw new CadiException("Could not create " + dir); } } @@ -80,8 +80,8 @@ public abstract class ArtifactDir implements PlaceArtifact { // Obtain Issuers boolean first = true; StringBuilder issuers = new StringBuilder(); - for(String dn : certInfo.getCaIssuerDNs()) { - if(first) { + for (String dn : certInfo.getCaIssuerDNs()) { + if (first) { first=false; } else { issuers.append(':'); @@ -91,10 +91,10 @@ public abstract class ArtifactDir implements PlaceArtifact { addProperty(Config.CADI_X509_ISSUERS,issuers.toString()); } symm = (Symm)processed.get("symm"); - if(symm==null) { + if (symm==null) { // CADI Key Gen File f = new File(dir,arti.getNs() + ".keyfile"); - if(!f.exists()) { + if (!f.exists()) { write(f,Chmod.to400,Symm.keygen()); } symm = Symm.obtain(f); @@ -148,7 +148,7 @@ public abstract class ArtifactDir implements PlaceArtifact { FileOutputStream fos = new FileOutputStream(f); PrintStream ps = new PrintStream(fos); try { - for(String s : data) { + for (String s : data) { ps.print(s); } } finally { @@ -186,31 +186,31 @@ public abstract class ArtifactDir implements PlaceArtifact { private void validate(Artifact a) throws CadiException { StringBuilder sb = new StringBuilder(); - if(a.getDir()==null) { + if (a.getDir()==null) { sb.append("File Artifacts require a path"); } - if(a.getNs()==null) { - if(sb.length()>0) { + if (a.getNs()==null) { + if (sb.length()>0) { sb.append('\n'); } sb.append("File Artifacts require an AAF Namespace"); } - if(sb.length()>0) { + if (sb.length()>0) { throw new CadiException(sb.toString()); } } private boolean placeProperties(Artifact arti) throws CadiException { - if(encodeds.size()==0) { + if (encodeds.size()==0) { return true; } boolean first=processed.get("dir")==null; try { File f = new File(dir,arti.getNs()+".cred.props"); - if(f.exists()) { - if(first) { + if (f.exists()) { + if (first) { File backup = File.createTempFile(f.getName()+'.', ".backup",dir); f.renameTo(backup); } else { @@ -222,8 +222,8 @@ public abstract class ArtifactDir implements PlaceArtifact { PrintWriter pw = new PrintWriter(new FileWriter(f,!first)); try { // Write a Header - if(first) { - for(int i=0;i<60;++i) { + if (first) { + for (int i=0;i<60;++i) { pw.print('#'); } pw.println(); @@ -233,12 +233,12 @@ public abstract class ArtifactDir implements PlaceArtifact { pw.print("# on "); pw.println(Chrono.dateStamp()); pw.println("# @copyright 2016, AT&T"); - for(int i=0;i<60;++i) { + for (int i=0;i<60;++i) { pw.print('#'); } pw.println(); - for(String prop : encodeds) { - if( prop.startsWith("cm_") + for (String prop : encodeds) { + if ( prop.startsWith("cm_") || prop.startsWith(Config.HOSTNAME) || prop.startsWith(Config.AAF_ENV)) { pw.println(prop); @@ -246,8 +246,8 @@ public abstract class ArtifactDir implements PlaceArtifact { } } - for(String prop : encodeds) { - if(prop.startsWith("cadi")) { + for (String prop : encodeds) { + if (prop.startsWith("cadi")) { pw.println(prop); } } @@ -256,16 +256,16 @@ public abstract class ArtifactDir implements PlaceArtifact { } Chmod.to644.chmod(f); - if(first) { + if (first) { // Challenge f = new File(dir,arti.getNs()+".chal"); - if(f.exists()) { + if (f.exists()) { f.delete(); } pw = new PrintWriter(new FileWriter(f)); try { - for(String prop : encodeds) { - if(prop.startsWith("Challenge")) { + for (String prop : encodeds) { + if (prop.startsWith("Challenge")) { pw.println(prop); } } @@ -274,7 +274,7 @@ public abstract class ArtifactDir implements PlaceArtifact { } Chmod.to400.chmod(f); } - } catch(Exception e) { + } catch (Exception e) { throw new CadiException(e); } return true; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java index 40f31706..642b2d29 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/Factory.java @@ -119,7 +119,7 @@ public class Factory { public static KeyPair generateKeyPair(Trans trans) { TimeTaken tt; - if(trans!=null) { + if (trans!=null) { tt = trans.start("Generate KeyPair", Env.SUB); } else { tt = null; @@ -127,7 +127,7 @@ public class Factory { try { return keygen.generateKeyPair(); } finally { - if(tt!=null) { + if (tt!=null) { tt.done(); } } @@ -146,7 +146,7 @@ public class Factory { base64.encode(bais, baos); sb.append(new String(baos.toByteArray())); - if(sb.charAt(sb.length()-1)!='\n') { + if (sb.charAt(sb.length()-1)!='\n') { sb.append('\n'); } sb.append("-----END "); @@ -215,7 +215,7 @@ public class Factory { public static Collection<? extends Certificate> toX509Certificate(List<String> x509s) throws CertificateException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { - for(String x509 : x509s) { + for (String x509 : x509s) { baos.write(x509.getBytes()); } } catch (IOException e) { @@ -246,16 +246,16 @@ public class Factory { } public static String toString(Trans trans, Certificate cert) throws IOException, CertException { - if(trans.debug().isLoggable()) { + if (trans.debug().isLoggable()) { StringBuilder sb = new StringBuilder("Certificate to String"); - if(cert instanceof X509Certificate) { + if (cert instanceof X509Certificate) { sb.append(" - "); sb.append(((X509Certificate)cert).getSubjectDN()); } trans.debug().log(sb); } try { - if(cert==null) { + if (cert==null) { throw new CertException("Certificate not built"); } return textBuilder("CERTIFICATE",cert.getEncoded()); @@ -283,18 +283,18 @@ public class Factory { ByteArrayOutputStream baos = new ByteArrayOutputStream(); String line; boolean notStarted = true; - while((line=br.readLine())!=null) { - if(notStarted) { - if(line.startsWith("-----")) { + while ((line=br.readLine())!=null) { + if (notStarted) { + if (line.startsWith("-----")) { notStarted = false; - if(hs!=null) { + if (hs!=null) { hs.set(line); } } else { continue; } } - if(line.length()>0 && + if (line.length()>0 && !line.startsWith("-----") && line.indexOf(':')<0) { // Header elements baos.write(line.getBytes()); @@ -310,7 +310,7 @@ public class Factory { private String line; public StripperInputStream(Reader rdr) { - if(rdr instanceof BufferedReader) { + if (rdr instanceof BufferedReader) { br = (BufferedReader)rdr; } else { br = new BufferedReader(rdr); @@ -330,16 +330,16 @@ public class Factory { @Override public int read() throws IOException { - if(line==null || idx>=line.length()) { - while((line=br.readLine())!=null) { - if(line.length()>0 && + if (line==null || idx>=line.length()) { + while ((line=br.readLine())!=null) { + if (line.length()>0 && !line.startsWith("-----") && line.indexOf(':')<0) { // Header elements break; } } - if(line==null) { + if (line==null) { return -1; } idx = 0; @@ -352,7 +352,7 @@ public class Factory { */ @Override public void close() throws IOException { - if(created!=null) { + if (created!=null) { created.close(); } } @@ -379,13 +379,13 @@ public class Factory { @Override public int read() throws IOException { - if(duo==null || idx>=duo.length) { + if (duo==null || idx>=duo.length) { int read = is.read(trio); - if(read==-1) { + if (read==-1) { return -1; } duo = Symm.base64.decode(trio); - if(duo==null || duo.length==0) { + if (duo==null || duo.length==0) { return -1; } idx=0; @@ -399,7 +399,7 @@ public class Factory { */ @Override public void close() throws IOException { - if(created!=null) { + if (created!=null) { created.close(); } } @@ -477,7 +477,7 @@ public class Factory { */ public static synchronized Provider getSecurityProvider(String providerType, String[][] params) throws CertException { Provider p = Security.getProvider(providerType); - if(p!=null) { + if (p!=null) { switch(providerType) { case "PKCS12": diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java index e85b903f..b91e8734 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactInKeystore.java @@ -53,7 +53,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { File fks = new File(dir,arti.getNs()+'.'+(kst==Agent.PKCS12?"p12":kst)); try { KeyStore jks = KeyStore.getInstance(kst); - if(fks.exists()) { + if (fks.exists()) { File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); fks.renameTo(backup); } @@ -65,10 +65,10 @@ public class PlaceArtifactInKeystore extends ArtifactDir { X509Certificate x509; List<X509Certificate> chainList = new ArrayList<>(); Set<X509Certificate> caSet = new HashSet<>(); - for(Certificate c : certColl) { + for (Certificate c : certColl) { x509 = (X509Certificate)c; // Is a Root (self-signed, anyway) - if(x509.getSubjectDN().equals(x509.getIssuerDN())) { + if (x509.getSubjectDN().equals(x509.getIssuerDN())) { caSet.add(x509); } else { chainList.add(x509); @@ -98,7 +98,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { addEncProperty(Config.CADI_KEY_PASSWORD, keyPass); addProperty(Config.CADI_ALIAS, arti.getMechid()); // Set<Attribute> attribs = new HashSet<>(); -// if(kst.equals("pkcs12")) { +// if (kst.equals("pkcs12")) { // // Friendly Name // attribs.add(new PKCS12Attribute("1.2.840.113549.1.9.20", arti.getNs())); // } @@ -119,7 +119,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { // Change out to TrustStore // NOTE: PKCS12 does NOT support Trusted Entries. Put in JKS Always fks = new File(dir,arti.getNs()+".trust.jks"); - if(fks.exists()) { + if (fks.exists()) { File backup = File.createTempFile(fks.getName()+'.', ".backup",dir); fks.renameTo(backup); } @@ -136,7 +136,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { // Add Trusted Certificates, but PKCS12 doesn't support Certificate[] trustCAs = new Certificate[caSet.size()]; caSet.toArray(trustCAs); - for(int i=0; i<trustCAs.length;++i) { + for (int i=0; i<trustCAs.length;++i) { jks.setCertificateEntry("ca_" + arti.getCa() + '_' + i, trustCAs[i]); } // Write out diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactOnStream.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactOnStream.java index b5dcfbc5..fcc1f623 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactOnStream.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactOnStream.java @@ -39,13 +39,13 @@ public class PlaceArtifactOnStream implements PlaceArtifact { public boolean place(Trans trans, CertInfo capi, Artifact a, String machine) { String lineSeparator = System.lineSeparator(); - if(capi.getNotes()!=null && capi.getNotes().length()>0) { + if (capi.getNotes()!=null && capi.getNotes().length()>0) { trans.info().printf("Warning: %s" + lineSeparator, capi.getNotes()); } out.printf("Challenge: %s" + lineSeparator, capi.getChallenge()); out.printf("PrivateKey:" + lineSeparator + "%s" + lineSeparator, capi.getPrivatekey()); out.println("Certificate Chain:"); - for(String c : capi.getCerts()) { + for (String c : capi.getCerts()) { out.println(c); } return true; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java index 2393c4c8..5ee1abe2 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PlaceArtifactScripts.java @@ -40,7 +40,7 @@ public class PlaceArtifactScripts extends ArtifactDir { String filename = arti.getNs()+".check.sh"; File f1 = new File(dir,filename); String email = arti.getNotification() + '\n'; - if(email.startsWith("mailto:")) { + if (email.startsWith("mailto:")) { email=email.substring(7); } else { email=arti.getOsUser() + '\n'; @@ -48,8 +48,8 @@ public class PlaceArtifactScripts extends ArtifactDir { StringBuilder classpath = new StringBuilder(); boolean first = true; - for(String pth : Split.split(File.pathSeparatorChar, System.getProperty("java.class.path"))) { - if(first) { + for (String pth : Split.split(File.pathSeparatorChar, System.getProperty("java.class.path"))) { + if (first) { first=false; } else { classpath.append(File.pathSeparatorChar); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java index 38890681..f3ff3898 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AAFToken.java @@ -35,10 +35,10 @@ public class AAFToken { long lsb = uuid.getLeastSignificantBits(); long msb = uuid.getMostSignificantBits(); int sum=35; // AAF - for(int i=0;i<Long.SIZE;i+=8) { + for (int i=0;i<Long.SIZE;i+=8) { sum+=((lsb>>i) & 0xFF); } - for(int i=0;i<Long.SIZE;i+=8) { + for (int i=0;i<Long.SIZE;i+=8) { sum+=((((msb>>i) & 0xFF))<<0xB); } sum+=(sr.nextInt()&0xEFC00000); // this is just to not leave zeros laying around @@ -54,11 +54,11 @@ public class AAFToken { public static final UUID fromToken(String token) { byte[] bytes = Hash.fromHexNo0x(token); - if(bytes==null) { + if (bytes==null) { return null; } ByteBuffer bb = ByteBuffer.wrap(bytes); - if(bb.capacity()!=CAPACITY ) { + if (bb.capacity()!=CAPACITY ) { return null; // not a CADI Token } byte b1 = bb.get(); @@ -68,14 +68,14 @@ public class AAFToken { byte b3 = (byte)(0x3F&bb.get()); int sum=35; - for(int i=0;i<Long.SIZE;i+=8) { + for (int i=0;i<Long.SIZE;i+=8) { sum+=((lsb>>i) & 0xFF); } - for(int i=0;i<Long.SIZE;i+=8) { + for (int i=0;i<Long.SIZE;i+=8) { sum+=((((msb>>i) & 0xFF))<<0xB); } - if(b1!=((byte)sum) || + if (b1!=((byte)sum) || b2!=((byte)(sum>>8)) || b3!=((byte)((sum>>16)))) { return null; // not a CADI Token diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java index 26a8a69d..29d0933c 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/AbsOTafLur.java @@ -45,15 +45,15 @@ public abstract class AbsOTafLur { protected AbsOTafLur(final PropAccess access, final String token_url, final String introspect_url) throws CadiException { this.access = access; String ci; - if((ci = access.getProperty(Config.AAF_APPID,null))==null) { - if((ci = access.getProperty(Config.CADI_ALIAS,null))==null) { + if ((ci = access.getProperty(Config.AAF_APPID,null))==null) { + if ((ci = access.getProperty(Config.CADI_ALIAS,null))==null) { throw new CadiException(Config.AAF_APPID + REQUIRED_FOR_OAUTH2); } } client_id = ci; synchronized(access) { - if(tokenClientPool==null) { + if (tokenClientPool==null) { tokenClientPool = new Pool<TokenClient>(new TCCreator(access)); } try { @@ -76,7 +76,7 @@ public abstract class AbsOTafLur { throw new CadiException(e1); } - if((url = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null))==null) { + if ((url = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null))==null) { throw new CadiException(Config.AAF_OAUTH2_TOKEN_URL + REQUIRED_FOR_OAUTH2); } @@ -85,7 +85,7 @@ public abstract class AbsOTafLur { } catch (NumberFormatException e) { throw new CadiException("Bad format for " + Config.AAF_CONN_TIMEOUT, e); } - if((enc_secret= access.getProperty(Config.AAF_APPPASS,null))==null) { + if ((enc_secret= access.getProperty(Config.AAF_APPPASS,null))==null) { throw new CadiException(Config.AAF_APPPASS + REQUIRED_FOR_OAUTH2); } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java index 100b58ec..0e57dee8 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/HRenewingTokenSS.java @@ -54,14 +54,14 @@ public class HRenewingTokenSS extends HAuthorizationHeader { tc.client_creds(access); setUser(tc.client_id()); String defaultNS = FQI.reverseDomain(tc.client_id()); - if(nss.length>0) { + if (nss.length>0) { boolean hasDefault = false; - for(String ns : nss) { - if(ns.equals(defaultNS)) { + for (String ns : nss) { + if (ns.equals(defaultNS)) { hasDefault = true; } } - if(hasDefault) { + if (hasDefault) { scopes=nss; } else { String[] nssPlus = new String[nss.length+1]; @@ -86,7 +86,7 @@ public class HRenewingTokenSS extends HAuthorizationHeader { Result<TimedToken> token; try { token = tc.getToken(Kind.OAUTH,scopes); - if(token.isOK()) { + if (token.isOK()) { return "Bearer " + token.value.getAccessToken(); } else { throw new IOException("Token cannot be obtained: " + token.code + '-' + token.error); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java index b4b4b1e3..27e92142 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2HttpTaf.java @@ -52,14 +52,14 @@ public class OAuth2HttpTaf implements HttpTaf { @Override public TafResp validate(LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { String authz = req.getHeader("Authorization"); - if(authz != null && authz.length()>7 && authz.startsWith("Bearer ")) { - if(!req.isSecure()) { + if (authz != null && authz.length()>7 && authz.startsWith("Bearer ")) { + if (!req.isSecure()) { access.log(Level.WARN,"WARNING! OAuth has been used over an insecure channel"); } try { String tkn = authz.substring(7); Result<OAuth2Principal> rp = tmgr.toPrincipal(tkn,Hash.hashSHA256(tkn.getBytes())); - if(rp.isOK()) { + if (rp.isOK()) { return new OAuth2HttpTafResp(access,rp.value,rp.value.getName()+" authenticated by Bearer Token",RESP.IS_AUTHENTICATED,resp,false); } else { return new OAuth2HttpTafResp(access,null,rp.error,RESP.FAIL,resp,true); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java index 5f4009d5..1a1adcc5 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/OAuth2Lur.java @@ -55,16 +55,16 @@ public class OAuth2Lur implements Lur { public boolean fish(Principal bait, Permission ... pond) { boolean rv = false; - if(bait instanceof OAuth2Principal) { + if (bait instanceof OAuth2Principal) { OAuth2Principal oap = (OAuth2Principal)bait; for (Permission p : pond ) { AAFPermission apond = (AAFPermission)p; TokenPerm tp = oap.tokenPerm(); - if(tp==null) { + if (tp==null) { } else { - for(Permission perm : tp.perms()) { - if(perm.match(apond)) { + for (Permission perm : tp.perms()) { + if (perm.match(apond)) { return true; } } @@ -78,8 +78,8 @@ public class OAuth2Lur implements Lur { public void fishAll(Principal bait, List<Permission> permissions) { OAuth2Principal oap = (OAuth2Principal)bait; TokenPerm tp = oap.tokenPerm(); - if(tp!=null) { - for(AAFPermission p : tp.perms()) { + if (tp!=null) { + for (AAFPermission p : tp.perms()) { permissions.add(p); } } @@ -96,7 +96,7 @@ public class OAuth2Lur implements Lur { @Override public boolean handles(Principal p) { - if(p!=null && p instanceof BearerPrincipal) { + if (p!=null && p instanceof BearerPrincipal) { return ((BearerPrincipal)p).getBearer()!=null; } return false; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java index 3b4e074a..58ecaa84 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClient.java @@ -80,7 +80,7 @@ public class TokenClient { ss = null; authn_method = am; synchronized(tcf) { - if(introspectDF==null) { + if (introspectDF==null) { tokenDF = tkCon.env().newDataFactory(Token.class); introspectDF = tkCon.env().newDataFactory(Introspect.class); } @@ -106,9 +106,9 @@ public class TokenClient { } public void client_creds(Access access) throws CadiException { - if(okind=='A') { + if (okind=='A') { String alias = access.getProperty(Config.CADI_ALIAS, null); - if(alias == null) { + if (alias == null) { client_creds(access.getProperty(Config.AAF_APPID, null),access.getProperty(Config.AAF_APPPASS, null)); } else { client_creds(alias,null); @@ -129,15 +129,15 @@ public class TokenClient { * @throws IOException */ public void client_creds(final String client_id, final String client_secret) throws CadiException { - if(client_id==null) { + if (client_id==null) { throw new CadiException("client_creds:client_id is null"); } this.client_id = client_id; default_scope = FQI.reverseDomain(client_id); - if(client_secret!=null) { + if (client_secret!=null) { try { - if(client_secret.startsWith("enc:")) { + if (client_secret.startsWith("enc:")) { final String temp = factory.access.decrypt(client_secret, false); // this is a more powerful, but non-thread-safe encryption hash = Hash.hashSHA256(temp.getBytes()); this.enc_client_secret = factory.symm.encode(temp.getBytes()); @@ -159,7 +159,7 @@ public class TokenClient { }; } authn_method = AUTHN_METHOD.client_credentials; - } catch(IOException | NoSuchAlgorithmException e) { + } catch (IOException | NoSuchAlgorithmException e) { throw new CadiException(e); } } else { @@ -193,9 +193,9 @@ public class TokenClient { */ public void password(final String user, final String password) throws CadiException { this.username = user; - if(password!=null) { + if (password!=null) { try { - if(password.startsWith("enc:")) { + if (password.startsWith("enc:")) { final String temp = factory.access.decrypt(password, false); // this is a more powerful, but non-thread-safe encryption hash = Hash.hashSHA256(temp.getBytes()); this.enc_password = factory.symm.encode(temp.getBytes()); @@ -226,7 +226,7 @@ public class TokenClient { public void clearEndUser() { username = null; enc_password = null; - if(client_id!=null && enc_client_secret!=null) { + if (client_id!=null && enc_client_secret!=null) { authn_method = AUTHN_METHOD.client_credentials; } else { authn_method = AUTHN_METHOD.password; @@ -244,7 +244,7 @@ public class TokenClient { public void clearToken(final char kind, final String ... scopes) throws CadiException { final String scope = addScope(scopes); char c; - if(kind==Kind.OAUTH) { + if (kind==Kind.OAUTH) { c = okind; } else { c = kind; @@ -261,13 +261,13 @@ public class TokenClient { public Result<TimedToken> getToken(final char kind, final String ... scopes) throws LocatorException, CadiException, APIException { final String scope = addScope(scopes); char c; - if(kind==Kind.OAUTH) { + if (kind==Kind.OAUTH) { c = okind; } else { c = kind; } final String key = TokenClientFactory.getKey(c,client_id,username,hash,scope); - if(ss==null) { + if (ss==null) { throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); } @@ -285,7 +285,7 @@ public class TokenClient { public Result<Token> code(Rcli<?> client) throws CadiException, ConnectException, APIException { // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test Future<Token> f = client.postForm(null,tokenDF,paramsa); - if(f.get(timeout)) { + if (f.get(timeout)) { return Result.ok(f.code(),f.value); } else { return Result.err(f.code(), f.body()); @@ -293,7 +293,7 @@ public class TokenClient { } }); - if(rt.isOK()) { + if (rt.isOK()) { try { return Result.ok(rt.code,factory.putTimedToken(key,rt.value, hash)); } catch (IOException e) { @@ -306,11 +306,11 @@ public class TokenClient { } } }); - if(rtt.isOK()) { // not validated for Expired + if (rtt.isOK()) { // not validated for Expired TimedToken tt = rtt.value; - if(tt.expired()) { + if (tt.expired()) { rtt = refreshToken(tt); - if(rtt.isOK()) { + if (rtt.isOK()) { tkCon.access.printf(Level.INFO, "Refreshed token %s to %s",tt.getAccessToken(),rtt.value.getAccessToken()); return Result.ok(200,rtt.value); } else { @@ -328,7 +328,7 @@ public class TokenClient { } public Result<TimedToken> refreshToken(Token token) throws APIException, LocatorException, CadiException { - if(ss==null) { + if (ss==null) { throw new APIException("client_creds(...) must be set before obtaining Access Tokens"); } final List<String> params = new ArrayList<>(); @@ -344,7 +344,7 @@ public class TokenClient { public Result<Token> code(Rcli<?> client) throws CadiException, ConnectException, APIException { // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test Future<Token> f = client.postForm(null,tokenDF,paramsa); - if(f.get(timeout)) { + if (f.get(timeout)) { return Result.ok(f.code(),f.value); } else { return Result.err(f.code(), f.body()); @@ -352,21 +352,21 @@ public class TokenClient { } }); String key = TokenClientFactory.getKey(okind,client_id, username, hash, scope); - if(rt.isOK()) { + if (rt.isOK()) { try { return Result.ok(200,factory.putTimedToken(key, rt.value, hash)); } catch (IOException e) { //TODO what to do here? return Result.err(999, e.getMessage()); } - } else if(rt.code==404) { + } else if (rt.code==404) { factory.deleteFromDisk(key); } return Result.err(rt); } public Result<Introspect> introspect(final String token) throws APIException, LocatorException, CadiException { - if(ss==null) { + if (ss==null) { throw new APIException("client_creds(...) must be set before introspecting Access Tokens"); } @@ -380,7 +380,7 @@ public class TokenClient { params.toArray(paramsa); // /token?grant_type=client_credential&scope=com.att.aaf+com.att.test Future<Introspect> f = client.postForm(null,introspectDF,paramsa); - if(f.get(timeout)) { + if (f.get(timeout)) { return Result.ok(f.code(),f.value); } else { return Result.err(f.code(), f.body()); @@ -394,8 +394,8 @@ public class TokenClient { String rv = null; StringBuilder scope=null; boolean first = true; - for(String s : scopes) { - if(first) { + for (String s : scopes) { + if (first) { scope = new StringBuilder(); scope.append("scope="); first=false; @@ -404,7 +404,7 @@ public class TokenClient { } scope.append(s); } - if(scope!=null) { + if (scope!=null) { rv=scope.toString(); } return rv; @@ -432,11 +432,11 @@ public class TokenClient { // Set Credentials appropriate switch(authn_method) { case client_credentials: - if(client_id!=null) { + if (client_id!=null) { params.add("client_id="+client_id); } - if(enc_client_secret!=null) { + if (enc_client_secret!=null) { try { params.add("client_secret="+URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); } catch (IOException e) { @@ -444,17 +444,17 @@ public class TokenClient { } } - if(username!=null) { + if (username!=null) { params.add("username="+username); } break; case refresh_token: - if(client_id!=null) { + if (client_id!=null) { params.add("client_id="+client_id); } - if(enc_client_secret!=null) { + if (enc_client_secret!=null) { try { params.add("client_secret="+URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); } catch (IOException e) { @@ -464,22 +464,22 @@ public class TokenClient { break; case password: - if(client_id!=null) { + if (client_id!=null) { params.add("client_id="+client_id); } - if(enc_client_secret!=null) { + if (enc_client_secret!=null) { try { params.add("client_secret="+ URLEncoder.encode(new String(factory.symm.decode(enc_client_secret)),UTF_8)); } catch (IOException e) { throw new APIException("Error Decrypting Password",e); } } - if(username!=null) { + if (username!=null) { params.add("username="+username); } - if(enc_password!=null) { + if (enc_password!=null) { try { params.add("password="+ URLEncoder.encode(new String(factory.symm.decode(enc_password)),UTF_8)); } catch (IOException e) { diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java index 8a7118c7..21b65f1a 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenClientFactory.java @@ -63,10 +63,10 @@ public class TokenClientFactory extends Persist<Token,TimedToken> { private TokenClientFactory(Access pa) throws APIException, GeneralSecurityException, IOException, CadiException { super(pa, new RosettaEnv(pa.getProperties()),Token.class,"outgoing"); - if(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null)==null) { + if (access.getProperty(Config.AAF_OAUTH2_TOKEN_URL,null)==null) { access.getProperties().put(Config.AAF_OAUTH2_TOKEN_URL, Defaults.OAUTH2_TOKEN_URL); // Default to AAF } - if(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,null)==null) { + if (access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL,null)==null) { access.getProperties().put(Config.AAF_OAUTH2_INTROSPECT_URL, Defaults.OAUTH2_INTROSPECT_URL); // Default to AAF); } @@ -75,7 +75,7 @@ public class TokenClientFactory extends Persist<Token,TimedToken> { } public synchronized static final TokenClientFactory instance(Access access) throws APIException, GeneralSecurityException, IOException, CadiException { - if(instance==null) { + if (instance==null) { instance = new TokenClientFactory(access); } return instance; @@ -96,16 +96,16 @@ public class TokenClientFactory extends Persist<Token,TimedToken> { public<INTR> TokenClient newClient(final String tagOrURL, final int timeout) throws CadiException, LocatorException, APIException { AAFConHttp ach; - if(tagOrURL==null) { + if (tagOrURL==null) { throw new CadiException("parameter tagOrURL cannot be null."); } else { ach = aafcons.get(tagOrURL); - if(ach==null) { + if (ach==null) { aafcons.put(tagOrURL, ach=new AAFConHttp(access,tagOrURL)); } } char okind; - if( Config.AAF_OAUTH2_TOKEN_URL.equals(tagOrURL) || + if ( Config.AAF_OAUTH2_TOKEN_URL.equals(tagOrURL) || Config.AAF_OAUTH2_INTROSPECT_URL.equals(tagOrURL) || tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_TOKEN_URL, null)) || tagOrURL.equals(access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL, null)) @@ -136,19 +136,19 @@ public class TokenClientFactory extends Persist<Token,TimedToken> { try { StringBuilder sb = new StringBuilder(client_id); sb.append('_'); - if(username!=null) { + if (username!=null) { sb.append(username); } sb.append('_'); sb.append(tokenSource); byte[] tohash=scope.getBytes(); - if(hash!=null && hash.length>0) { + if (hash!=null && hash.length>0) { byte temp[] = new byte[hash.length+tohash.length]; System.arraycopy(tohash, 0, temp, 0, tohash.length); System.arraycopy(hash, 0, temp, tohash.length, hash.length); tohash = temp; } - if(scope!=null && scope.length()>0) { + if (scope!=null && scope.length()>0) { sb.append(Hash.toHexNo0x(Hash.hashSHA256(tohash))); } return sb.toString(); @@ -170,12 +170,12 @@ public class TokenClientFactory extends Persist<Token,TimedToken> { private static final Pattern locatePattern = Pattern.compile("https://.*/locate/.*"); public Locator<URI> bestLocator(final String locatorURL ) throws LocatorException, URISyntaxException { - if(locatorURL==null) { + if (locatorURL==null) { throw new LocatorException("Cannot have a null locatorURL in bestLocator"); } - if(locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) { + if (locatorURL.startsWith("https://AAF_LOCATE_URL/") || locatePattern.matcher(locatorURL).matches()) { return new AAFLocator(hsi,new URI(locatorURL)); - } else if(locatorURL.indexOf(',')>0) { // multiple URLs is a Property Locator + } else if (locatorURL.indexOf(',')>0) { // multiple URLs is a Property Locator return new PropertyLocator(locatorURL); } else { return new SingleEndpointLocator(locatorURL); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java index 147621fc..5a4e7f0c 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenMgr.java @@ -55,12 +55,12 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { private TokenMgr(PropAccess access, String tokenURL, String introspectURL) throws APIException, CadiException { super(access,new RosettaEnv(access.getProperties()),Introspect.class,"introspect"); synchronized(access) { - if(permsDF==null) { + if (permsDF==null) { permsDF = env.newDataFactory(Perms.class); introspectDF = env.newDataFactory(Introspect.class); } } - if("dbToken".equals(tokenURL) && "dbIntrospect".equals(introspectURL)) { + if ("dbToken".equals(tokenURL) && "dbIntrospect".equals(introspectURL)) { tpLoader = new TokenPermLoader() { // null Loader @Override public Result<TokenPerm> load(String accessToken, byte[] cred) @@ -72,7 +72,7 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { RemoteTokenPermLoader rtpl = new RemoteTokenPermLoader(tokenURL, introspectURL); // default is remote String i = access.getProperty(Config.AAF_APPID,null); String p = access.getProperty(Config.AAF_APPPASS, null); - if(i==null || p==null) { + if (i==null || p==null) { throw new CadiException(Config.AAF_APPID + " and " + Config.AAF_APPPASS + " must be set to initialize TokenMgr"); } rtpl.introCL.client_creds(i,p); @@ -83,7 +83,7 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { private TokenMgr(PropAccess access, TokenPermLoader tpl) throws APIException, CadiException { super(access,new RosettaEnv(access.getProperties()),Introspect.class,"incoming"); synchronized(access) { - if(permsDF==null) { + if (permsDF==null) { permsDF = env.newDataFactory(Perms.class); introspectDF = env.newDataFactory(Introspect.class); } @@ -94,7 +94,7 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { public static synchronized TokenMgr getInstance(final PropAccess access, final String tokenURL, final String introspectURL) throws APIException, CadiException { String key; TokenMgr tm = tmmap.get(key=tokenURL+'/'+introspectURL); - if(tm==null) { + if (tm==null) { tmmap.put(key, tm=new TokenMgr(access,tokenURL,introspectURL)); } return tm; @@ -111,7 +111,7 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { } } }); - if(tp.isOK()) { + if (tp.isOK()) { return Result.ok(200, new OAuth2Principal(tp.value,hash)); } else { return Result.err(tp); @@ -143,7 +143,7 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { int timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); tokenCL = tcf.newClient(tokenURL, timeout); - if(introspectURL.equals(tokenURL)) { + if (introspectURL.equals(tokenURL)) { introCL = tokenCL; } else { introCL = tcf.newClient(introspectURL, @@ -159,7 +159,7 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { long start = System.currentTimeMillis(); try { Result<Introspect> ri = introCL.introspect(accessToken); - if(ri.isOK()) { + if (ri.isOK()) { return Result.ok(ri.code, new TokenPerm(TokenMgr.this,permsDF,ri.value,cred,getPath(accessToken))); } else { return Result.err(ri); @@ -172,7 +172,7 @@ public class TokenMgr extends Persist<Introspect, TokenPerm> { public void clear(Principal p, StringBuilder report) { TokenPerm tp = tpmap.remove(p.getName()); - if(tp==null) { + if (tp==null) { report.append("Nothing to clear"); } else { report.append("Cleared "); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java index daac8f43..6efd9ce3 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TokenPerm.java @@ -49,7 +49,7 @@ public class TokenPerm extends Persisting<Introspect>{ public TokenPerm(Persist<Introspect,?> p, RosettaDF<Perms> permsDF, Introspect ti, byte[] hash, Path path) throws APIException { super(p,ti,ti.getExp(),hash,path); // ti.getExp() is seconds after Jan 1, 1970 ) this.introspect = ti; - if(ti.getContent()==null || ti.getContent().length()==0) { + if (ti.getContent()==null || ti.getContent().length()==0) { perms = NULL_PERMS; } else { LoadPermissions lp; @@ -96,7 +96,7 @@ public class TokenPerm extends Persisting<Introspect>{ InJson ij = new InJson(); Parsed<State> pd = ij.newParsed(); boolean inPerms = false, inPerm = false; - while((pd = ij.parse(r,pd.reuse())).valid()) { + while ((pd = ij.parse(r,pd.reuse())).valid()) { switch(pd.event) { case Parse.START_DOC: perms = new ArrayList<>(); @@ -105,22 +105,22 @@ public class TokenPerm extends Persisting<Introspect>{ inPerms = "perm".equals(pd.name); break; case '{': - if(inPerms) { + if (inPerms) { inPerm=true; pi.clear(); } break; case ',': - if(inPerm) { + if (inPerm) { pi.eval(pd); } break; case '}': - if(inPerms) { - if(inPerm) { + if (inPerms) { + if (inPerm) { pi.eval(pd); AAFPermission perm = pi.create(); - if(perm!=null) { + if (perm!=null) { perms.add(perm); } } @@ -128,7 +128,7 @@ public class TokenPerm extends Persisting<Introspect>{ } break; case Parse.END_ARRAY: - if(inPerms) { + if (inPerms) { inPerms=false; } break; @@ -146,7 +146,7 @@ public class TokenPerm extends Persisting<Introspect>{ ns=type=instance=action=null; } public void eval(Parsed<State> pd) { - if(pd.hasName()) { + if (pd.hasName()) { switch(pd.name) { case "ns": ns=pd.sb.toString(); @@ -164,7 +164,7 @@ public class TokenPerm extends Persisting<Introspect>{ } } public AAFPermission create() { - if(type!=null && instance!=null && action !=null) { + if (type!=null && instance!=null && action !=null) { return new AAFPermission(ns,type, instance, action); } else { return null; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java index 77348390..c07332d1 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/oauth/TzHClient.java @@ -69,10 +69,10 @@ public class TzHClient extends TzClient { } public <RET> RET best (Retryable<RET> retryable) throws CadiException, LocatorException, APIException { - if(token == null || tokenSS==null) { + if (token == null || tokenSS==null) { throw new CadiException("OAuth2 Token has not been set"); } - if(token.expired()) { + if (token.expired()) { //TODO Refresh? throw new CadiException("Expired Token"); } else { diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java index 688f30b1..8c2cc82d 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/obasic/OBasicHttpTaf.java @@ -87,20 +87,20 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { final String user; String password=null; byte[] cred=null; - if(req instanceof BasicCred) { + if (req instanceof BasicCred) { BasicCred bc = (BasicCred)req; user = bc.getUser(); cred = bc.getCred(); } else { String authz = req.getHeader("Authorization"); - if(authz != null && authz.startsWith("Basic ")) { - if(!req.isSecure()) { + if (authz != null && authz.startsWith("Basic ")) { + if (!req.isSecure()) { access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); } try { String temp = Symm.base64noSplit.decode(authz.substring(6)); int colon = temp.lastIndexOf(':'); - if(colon>0) { + if (colon>0) { user = temp.substring(0,colon); password = temp.substring(colon+1); } else { @@ -108,7 +108,7 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { access.encrypt(temp)); return new BasicHttpTafResp(access,null,"Malformed BasicAuth entry",RESP.FAIL,resp,realm,false); } - if(!rbac.validate(user,Type.PASSWORD,password.getBytes(),req)) { + if (!rbac.validate(user,Type.PASSWORD,password.getBytes(),req)) { return new BasicHttpTafResp(access,null,buildMsg(null,req,"user/pass combo invalid for ",user,"from",req.getRemoteAddr()), RESP.TRY_AUTHENTICATING,resp,realm,true); } @@ -122,10 +122,10 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { } try { - if(password==null && cred!=null) { + if (password==null && cred!=null) { password = new String(cred); cred = Hash.hashSHA256(cred); - } else if(password!=null && cred==null) { + } else if (password!=null && cred==null) { cred = Hash.hashSHA256(password.getBytes()); } Pooled<TokenClient> pclient = tokenClientPool.get(); @@ -133,13 +133,13 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { pclient.content.password(user, password); String scope=FQI.reverseDomain(client_id); Result<TimedToken> rtt = pclient.content.getToken('B',scope); - if(rtt.isOK()) { - if(rtt.value.expired()) { + if (rtt.isOK()) { + if (rtt.value.expired()) { return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: Token Expired",RESP.FAIL,resp,realm,true); } else { TimedToken tt = rtt.value; Result<OAuth2Principal> prin = tkMgr.toPrincipal(tt.getAccessToken(), cred); - if(prin.isOK()) { + if (prin.isOK()) { return new BasicHttpTafResp(access,prin.value,"BasicAuth/OAuth Token Authentication",RESP.IS_AUTHENTICATED,resp,realm,true); } else { return new BasicHttpTafResp(access,null,"BasicAuth/OAuth Token: " + prin.code + ' ' + prin.error,RESP.FAIL,resp,realm,true); @@ -159,7 +159,7 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { StringBuilder sb = new StringBuilder(); - if(pr!=null) { + if (pr!=null) { sb.append("user="); sb.append(pr.getName()); sb.append(','); @@ -168,9 +168,9 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { sb.append(req.getRemoteAddr()); sb.append(",port="); sb.append(req.getRemotePort()); - if(msg.length>0) { + if (msg.length>0) { sb.append(",msg=\""); - for(Object s : msg) { + for (Object s : msg) { sb.append(s.toString()); } sb.append('"'); @@ -180,9 +180,9 @@ public class OBasicHttpTaf extends AbsOTafLur implements HttpTaf { @Override public Resp revalidate(CachedPrincipal prin, Object state) { -// if(prin instanceof BasicPrincipal) { +// if (prin instanceof BasicPrincipal) { // BasicPrincipal ba = (BasicPrincipal)prin; -// if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { +// if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { // return Resp.UNVALIDATED; // } // return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java index c67f986e..b85e311d 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/olur/OLur.java @@ -56,13 +56,13 @@ public class OLur extends AbsOTafLur implements Lur { @Override public boolean fish(Principal bait, Permission ... pond) { TokenPerm tp; - if(bait instanceof OAuth2Principal) { + if (bait instanceof OAuth2Principal) { OAuth2Principal oa2p = (OAuth2Principal)bait; tp = oa2p.tokenPerm(); } else { tp=null; } - if(tp==null) { + if (tp==null) { // if no Token Perm preset, get try { Pooled<TokenClient> tcp = tokenClientPool.get(); @@ -73,7 +73,7 @@ public class OLur extends AbsOTafLur implements Lur { scopeSet.add(tc.defaultScope()); AAFPermission ap; for (Permission p : pond) { - if(p instanceof AAFPermission) { + if (p instanceof AAFPermission) { ap = (AAFPermission)p; scopeSet.add(ap.getNS()); } @@ -82,9 +82,9 @@ public class OLur extends AbsOTafLur implements Lur { scopeSet.toArray(scopes); Result<TimedToken> rtt = tc.getToken(Kind.getKind(bait),scopes); - if(rtt.isOK()) { + if (rtt.isOK()) { Result<TokenPerm> rtp = tkMgr.get(rtt.value.getAccessToken(), bait.getName().getBytes()); - if(rtp.isOK()) { + if (rtp.isOK()) { tp = rtp.value; } } @@ -97,8 +97,8 @@ public class OLur extends AbsOTafLur implements Lur { } boolean rv = false; - if(tp!=null) { - if(tkMgr.access.willLog(Level.DEBUG)) { + if (tp!=null) { + if (tkMgr.access.willLog(Level.DEBUG)) { StringBuilder sb = new StringBuilder("AAF Permissions for user "); sb.append(bait.getName()); sb.append(", from token "); @@ -117,7 +117,7 @@ public class OLur extends AbsOTafLur implements Lur { access.log(Level.DEBUG, sb); } for (Permission p : pond) { - if(rv) { + if (rv) { break; } for (AAFPermission perm : tp.perms()) { @@ -135,7 +135,7 @@ public class OLur extends AbsOTafLur implements Lur { */ @Override public void fishAll(Principal bait, List<Permission> permissions) { - if(bait instanceof OAuth2Principal) { + if (bait instanceof OAuth2Principal) { for (AAFPermission p : ((OAuth2Principal)bait).tokenPerm().perms()) { permissions.add(p); } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java index d87ee780..472bb529 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persist.java @@ -67,7 +67,7 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { df = env.newDataFactory(cls); tmap = new ConcurrentHashMap<>(); synchronized(Persist.class) { - if(clean==null) { + if (clean==null) { clean = new Timer(true); clean.schedule(new Clean(access), 20000, CLEAN_CHECK); } @@ -85,14 +85,14 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { return df; } public Result<CT> get(final String key, final byte[] hash, Loader<CT> rl) throws CadiException, APIException, LocatorException { - if(key==null) { + if (key==null) { return null; } Holder<Path> hp = new Holder<Path>(null); CT ct = tmap.get(key); // Make sure cached Item is synced with Disk, but only even Minute to save Disk hits - if(ct!=null && ct.checkSyncTime()) { // check File Time only every SYNC Period (2 min) - if(ct.hasBeenTouched()) { + if (ct!=null && ct.checkSyncTime()) { // check File Time only every SYNC Period (2 min) + if (ct.hasBeenTouched()) { tmap.remove(key); ct = null; access.log(Level.DEBUG,"File for",key,"has been touched, removing memory entry"); @@ -100,12 +100,12 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { } // If not currently in memory, check with Disk (which might have been updated by other processes) - if(ct==null) { + if (ct==null) { Holder<Long> hl = new Holder<Long>(0L); T t; - if((t = readDisk(df, hash, key, hp, hl))!=null) { + if ((t = readDisk(df, hash, key, hp, hl))!=null) { try { - if((ct = newCacheable(t,hl.get(),hash,hp.get()))!=null) { + if ((ct = newCacheable(t,hl.get(),hash,hp.get()))!=null) { tmap.put(key, ct); } access.log(Level.DEBUG,"Read Token from",key); @@ -115,16 +115,16 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { } // if not read, then ct still==null // If not in memory, or on disk, get from Remote... IF reloadable (meaning, isn't hitting too often, etc). - if(ct==null || ct.checkReloadable()) { + if (ct==null || ct.checkReloadable()) { // Load from external (if makes sense) Result<CT> rtp = rl.load(key); - if(rtp.isOK()) { + if (rtp.isOK()) { ct = rtp.value; try { Path p = getPath(key); writeDisk(df, ct.get(),ct.getHash(),p,ct.expires()); access.log(Level.DEBUG, "Writing token",key); - } catch(CadiException e) { + } catch (CadiException e) { throw e; } catch (Exception e) { throw new CadiException(e); @@ -134,7 +134,7 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { } } - if(ct!=null) { + if (ct!=null) { tmap.put(key, ct); } } else { @@ -186,23 +186,23 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { final long now = System.currentTimeMillis(); final long dayFromNow = now + ONE_DAY; final Metrics metrics = new Metrics(); - for(final Persist<?,?> persist : allPersists) { + for (final Persist<?,?> persist : allPersists) { // Clear memory - if(access.willLog(Level.DEBUG)) { + if (access.willLog(Level.DEBUG)) { access.log(Level.DEBUG, "Persist: Cleaning memory cache for",persist.tokenPath.toAbsolutePath()); } - for(Entry<String, ?> es : persist.tmap.entrySet()) { + for (Entry<String, ?> es : persist.tmap.entrySet()) { ++metrics.mexists; Persistable<?> p = (Persistable<?>)es.getValue(); - if(p.checkSyncTime()) { - if(p.count()==0) { + if (p.checkSyncTime()) { + if (p.count()==0) { ++metrics.mremoved; persist.tmap.remove(es.getKey()); access.printf(Level.DEBUG, "Persist: removed cached item %s from memory\n", es.getKey()); } else { p.clearCount(); } - } else if(Files.exists(p.path())) { + } else if (Files.exists(p.path())) { } } @@ -220,19 +220,19 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if(attrs.isRegularFile()) { + if (attrs.isRegularFile()) { ++metrics.dexists; try { long exp = persist.readExpiration(file)*1000; // readExpiration is seconds from 1970 - if(now > exp) { // cover for bad token + if (now > exp) { // cover for bad token sb.append("\n\tFile "); sb.append(file.getFileName()); sb.append(" expired "); sb.append(Chrono.dateTime(new Date(exp))); persist.deleteFromDisk(file); ++metrics.dremoved; - } else if(exp > dayFromNow) { + } else if (exp > dayFromNow) { sb.append("\n\tFile "); sb.append(file.toString()); sb.append(" data corrupted."); @@ -273,14 +273,14 @@ public abstract class Persist<T,CT extends Persistable<T>> extends PersistFile { // We want to print some activity of Persistence Check at least hourly, even if no activity has occurred, but not litter the log if nothing is happening boolean go=false; Level level=Level.WARN; - if(access.willLog(Level.INFO)) { + if (access.willLog(Level.INFO)) { go = true; level=Level.INFO; - } else if(access.willLog(Level.WARN)) { + } else if (access.willLog(Level.WARN)) { go = metrics.mremoved>0 || metrics.dremoved>0 || --hourly <= 0; } - if(go) { + if (go) { access.printf(level, "Persist Cache: removed %d of %d items from memory and %d of %d from disk", metrics.mremoved, metrics.mexists, metrics.dremoved, metrics.dexists); hourly = 3600000/CLEAN_CHECK; diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java index 7aab519d..c7d71488 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/PersistFile.java @@ -63,8 +63,8 @@ public class PersistFile { this.access = access; tokenPath = Paths.get(access.getProperty(Config.CADI_TOKEN_DIR,"tokens"), sub_dir); try { - if(!Files.exists(tokenPath)) { - if(isWindows) { + if (!Files.exists(tokenPath)) { + if (isWindows) { // Sorry Windows users, you need to secure your own paths Files.createDirectories(tokenPath); } else { @@ -77,7 +77,7 @@ public class PersistFile { throw new CadiException(e); } synchronized(LOCK) { - if(symm==null) { + if (symm==null) { symm = Symm.obtain(access); } } @@ -94,7 +94,7 @@ public class PersistFile { final OutputStream dos = Files.newOutputStream(tpath, StandardOpenOption.CREATE,StandardOpenOption.WRITE); try { // Write Expires so that we can read unencrypted. - for(int i=0;i<Long.SIZE;i+=8) { + for (int i=0;i<Long.SIZE;i+=8) { dos.write((byte)((expires>>i)&0xFF)); } @@ -104,10 +104,10 @@ public class PersistFile { CipherOutputStream os = enc.outputStream(dos, true); try { int size = cred==null?0:cred.length; - for(int i=0;i<Integer.SIZE;i+=8) { + for (int i=0;i<Integer.SIZE;i+=8) { os.write((byte)((size>>i)&0xFF)); } - if(cred!=null) { + if (cred!=null) { os.write(cred); } df.newData().load(t).to(os); @@ -128,7 +128,7 @@ public class PersistFile { return null; } }); - } catch(Exception e) { + } catch (Exception e) { throw new CadiException(e); } finally { dos.close(); @@ -141,7 +141,7 @@ public class PersistFile { } public <T> T readDisk(final RosettaDF<T> df, final byte[] cred, final String filename,final Holder<Path> hp, final Holder<Long> hl) throws CadiException { - if(hp.get()==null) { + if (hp.get()==null) { hp.set(Paths.get(tokenDir,filename)); } return readDisk(df,cred,hp.get(),hl); @@ -150,13 +150,13 @@ public class PersistFile { public <T> T readDisk(final RosettaDF<T> df, final byte[] cred, final Path target, final Holder<Long> hexpired) throws CadiException { // Try from Disk T t = null; - if(Files.exists(target)) { + if (Files.exists(target)) { try { final InputStream is = Files.newInputStream(target,StandardOpenOption.READ); try { // Read Expired unencrypted long exp=0; - for(int i=0;i<Long.SIZE;i+=8) { + for (int i=0;i<Long.SIZE;i+=8) { exp |= ((long)is.read()<<i); } hexpired.set(exp); @@ -167,19 +167,19 @@ public class PersistFile { CipherInputStream dis = enc.inputStream(is,false); try { int size=0; - for(int i=0;i<Integer.SIZE;i+=8) { + for (int i=0;i<Integer.SIZE;i+=8) { size |= ((int)dis.read()<<i); } - if(size>256) { + if (size>256) { throw new CadiException("Invalid size in Token Persistence"); - } else if(cred!=null && size!=cred.length) { + } else if (cred!=null && size!=cred.length) { throw new CadiException(HASH_NO_MATCH); } - if(cred!=null) { + if (cred!=null) { byte[] array = new byte[size]; - if(dis.read(array)>0) { - for(int i=0;i<size;++i) { - if(cred[i]!=array[i]) { + if (dis.read(array)>0) { + for (int i=0;i<size;++i) { + if (cred[i]!=array[i]) { throw new CadiException(HASH_NO_MATCH); } } @@ -205,11 +205,11 @@ public class PersistFile { public long readExpiration(final Path target) throws CadiException { long exp=0L; - if(Files.exists(target)) { + if (Files.exists(target)) { try { final InputStream is = Files.newInputStream(target,StandardOpenOption.READ); try { - for(int i=0;i<Long.SIZE;i+=8) { + for (int i=0;i<Long.SIZE;i+=8) { exp |= ((long)is.read()<<i); } } finally { @@ -246,7 +246,7 @@ public class PersistFile { public FileTime getFileTime(String filename, Holder<Path> hp) throws IOException { Path p = hp.get(); - if(p==null) { + if (p==null) { hp.set(p=Paths.get(tokenDir,filename)); } return Files.getLastModifiedTime(p); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java index dd136a2a..bde60777 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/persist/Persisting.java @@ -54,7 +54,7 @@ public class Persisting<T> implements Persistable<T> { } count=0; nextCheck=0; - if(hash==null) { + if (hash==null) { this.hash = EMPTY; } else { this.hash = hash; @@ -80,7 +80,7 @@ public class Persisting<T> implements Persistable<T> { public boolean hasBeenTouched() { try { FileTime modT = Files.getLastModifiedTime(path); - if(lastTouched==null) { + if (lastTouched==null) { lastTouched = modT; return true; } else { @@ -98,7 +98,7 @@ public class Persisting<T> implements Persistable<T> { @Override public synchronized boolean checkSyncTime() { long temp=System.currentTimeMillis(); - if(nextCheck==0 || nextCheck<temp) { + if (nextCheck==0 || nextCheck<temp) { nextCheck = temp+SYNC_TIME; return true; } @@ -123,11 +123,11 @@ public class Persisting<T> implements Persistable<T> { @Override public boolean match(byte[] hashIn) { - if(hash==null || hashIn==null || hash.length!=hashIn.length) { + if (hash==null || hashIn==null || hash.length!=hashIn.length) { return false; } - for(int i=0;i<hashIn.length;++i) { - if(hash[i]!=hashIn[i]) { + for (int i=0;i<hashIn.length;++i) { + if (hash[i]!=hashIn[i]) { return false; } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java index 32ff8109..4ae1b97f 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/Registrar.java @@ -45,7 +45,7 @@ public class Registrar<ENV extends BasicEnv> { timer = new Timer(REGISTRAR,true); timer.schedule(new RegistrationTimerTask(env), START, INTERVAL); - if(shutdownHook) { + if (shutdownHook) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { close(env); @@ -61,18 +61,18 @@ public class Registrar<ENV extends BasicEnv> { } @Override public void run() { - for(Iterator<Registrant<ENV>> iter = registrants.iterator(); iter.hasNext();) { + for (Iterator<Registrant<ENV>> iter = registrants.iterator(); iter.hasNext();) { Registrant<ENV> reg = iter.next(); Result<Void> rv = reg.update(env); synchronized(LOCK) { - if(rv.isOK()) { - if(erroringTimer!=null) { + if (rv.isOK()) { + if (erroringTimer!=null) { erroringTimer.cancel(); erroringTimer = null; } } else { // Account for different Registrations not being to same place - if(erroringTimer==null) { + if (erroringTimer==null) { erroringTimer = new Timer(REGISTRAR + " error re-check ",true); erroringTimer.schedule(new RegistrationTimerTask(env),20000,20000); } @@ -94,7 +94,7 @@ public class Registrar<ENV extends BasicEnv> { timer.cancel(); Registrant<ENV> r; - while(registrants.peek()!=null) { + while (registrants.peek()!=null) { r = registrants.pop(); r.cancel(env); } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java index ae7ded3a..49d40ab4 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RemoteRegistrant.java @@ -67,12 +67,12 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { } timeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF)); String aaf_locate = access.getProperty(Config.AAF_LOCATE_URL,null); - if(aaf_locate==null) { + if (aaf_locate==null) { throw new CadiException(Config.AAF_LOCATE_URL + " is required."); } else { // Note: want Property Locator or Single, not AAFLocator, because we want the core service, not what it can find try { - if(aaf_locate.indexOf(',')>=0) { + if (aaf_locate.indexOf(',')>=0) { locator = new PropertyLocator(aaf_locate); } else { locator = new SingleEndpointLocator(aaf_locate); @@ -88,23 +88,23 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { try { String hostnameToRegister = access.getProperty(Config.AAF_REGISTER_AS, null); - if(hostnameToRegister==null) { + if (hostnameToRegister==null) { hostnameToRegister = access.getProperty(Config.HOSTNAME, null); } - if(hostnameToRegister==null) { + if (hostnameToRegister==null) { hostnameToRegister = Inet4Address.getLocalHost().getHostName(); } mep.setHostname(hostnameToRegister); String latitude = access.getProperty(Config.CADI_LATITUDE, null); - if(latitude==null) { + if (latitude==null) { latitude = access.getProperty("AFT_LATITUDE", null); } String longitude = access.getProperty(Config.CADI_LONGITUDE, null); - if(longitude==null) { + if (longitude==null) { longitude = access.getProperty("AFT_LONGITUDE", null); } - if(latitude==null || longitude==null) { + if (latitude==null || longitude==null) { throw new CadiException(Config.CADI_LATITUDE + " and " + Config.CADI_LONGITUDE + " is required"); } else { mep.setLatitude(Float.parseFloat(latitude)); @@ -117,11 +117,11 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { mep.setMajor(split.length>0?Integer.parseInt(split[0]):0); String subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); - if(subprotocols==null) { + if (subprotocols==null) { mep.setProtocol("http"); } else { mep.setProtocol("https"); - for(String s : Split.split(',', subprotocols)) { + for (String s : Split.split(',', subprotocols)) { mep.getSubprotocol().add(s); } } @@ -130,7 +130,7 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { } meps = new MgmtEndpoints(); meps.getMgmtEndpoint().add(mep); - for(RemoteRegistrant<ENV> rr : others) { + for (RemoteRegistrant<ENV> rr : others) { meps.getMgmtEndpoint().add(rr.mep); } } @@ -141,7 +141,7 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { Rcli<?> client = aafcon.client(locator); try { Future<MgmtEndpoints> fup = client.update("/registration",mgmtEndpointsDF,meps); - if(fup.get(timeout)) { + if (fup.get(timeout)) { access.log(Level.INFO, "Registration complete to",client.getURI()); return Result.ok(fup.code(),null); } else { @@ -164,7 +164,7 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { Rcli<?> client = aafcon.client(locator); try { Future<MgmtEndpoints> fup = client.delete("/registration",mgmtEndpointsDF,meps); - if(fup.get(timeout)) { + if (fup.get(timeout)) { access.log(Level.INFO, "Deregistration complete on",client.getURI()); return Result.ok(fup.code(),null); } else { diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java index 77be3449..38d4852f 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/sso/AAFSSO.java @@ -95,7 +95,7 @@ public class AAFSSO { System.setErr(os); sso = new File(dot_aaf, "sso.props"); - if(sso.exists()) { + if (sso.exists()) { InputStream propStream = new FileInputStream(sso); try { diskprops.load(propStream); @@ -114,8 +114,8 @@ public class AAFSSO { if (sso.exists()) { Properties temp = new Properties(); // Keep only these - for(Entry<Object, Object> es : diskprops.entrySet()) { - if(Config.CADI_LATITUDE.equals(es.getKey()) || + for (Entry<Object, Object> es : diskprops.entrySet()) { + if (Config.CADI_LATITUDE.equals(es.getKey()) || Config.CADI_LONGITUDE.equals(es.getKey()) || Config.AAF_DEFAULT_REALM.equals(es.getKey())) { temp.setProperty(es.getKey().toString(), es.getValue().toString()); @@ -143,15 +143,15 @@ public class AAFSSO { } } - for(Entry<Object, Object> es : diskprops.entrySet()) { + for (Entry<Object, Object> es : diskprops.entrySet()) { nargs.add(es.getKey().toString() + '=' + es.getValue().toString()); } String[] naargs = new String[nargs.size()]; nargs.toArray(naargs); access = new PropAccess(os, naargs); - if(loginOnly) { - for(String tag : new String[] {Config.AAF_APPID, Config.AAF_APPPASS, + if (loginOnly) { + for (String tag : new String[] {Config.AAF_APPID, Config.AAF_APPPASS, Config.CADI_ALIAS, Config.CADI_KEYSTORE,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { access.getProperties().remove(tag); diskprops.remove(tag); @@ -159,7 +159,7 @@ public class AAFSSO { touchDiskprops=true; // TODO Do we want to require reset of Passwords at least every Eight Hours. // } else if (sso.lastModified() > (System.currentTimeMillis() - EIGHT_HOURS)) { -// for(String tag : new String[] {Config.AAF_APPPASS,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { +// for (String tag : new String[] {Config.AAF_APPPASS,Config.CADI_KEYSTORE_PASSWORD,Config.CADI_KEY_PASSWORD}) { // access.getProperties().remove(tag); // diskprops.remove(tag); // } @@ -175,7 +175,7 @@ public class AAFSSO { String alias, appID; alias = access.getProperty(Config.CADI_ALIAS); - if(alias==null) { + if (alias==null) { appID = access.getProperty(Config.AAF_APPID); user=appID; } else { @@ -183,7 +183,7 @@ public class AAFSSO { appID=null; } - if(appID!=null && access.getProperty(Config.AAF_APPPASS)==null) { + if (appID!=null && access.getProperty(Config.AAF_APPPASS)==null) { char[] password = cons.readPassword("Password for %s: ", appID); String app_pass = access.encrypt(new String(password)); access.setProperty(Config.AAF_APPPASS,app_pass); @@ -193,7 +193,7 @@ public class AAFSSO { String keystore=access.getProperty(Config.CADI_KEYSTORE); String keystore_pass=access.getProperty(Config.CADI_KEYSTORE_PASSWORD); - if(user==null || (alias!=null && (keystore==null || keystore_pass==null))) { + if (user==null || (alias!=null && (keystore==null || keystore_pass==null))) { String select = null; String name; for (File tsf : dot_aaf.listFiles()) { @@ -201,7 +201,7 @@ public class AAFSSO { if (!name.contains("trust") && (name.endsWith(".jks") || name.endsWith(".p12"))) { setLogDefault(); select = cons.readLine("Use %s for Identity? (y/n): ",tsf.getName()); - if("y".equalsIgnoreCase(select)) { + if ("y".equalsIgnoreCase(select)) { keystore = tsf.getCanonicalPath(); access.setProperty(Config.CADI_KEYSTORE, keystore); addProp(Config.CADI_KEYSTORE, keystore); @@ -218,7 +218,7 @@ public class AAFSSO { } } } - if(alias==null) { + if (alias==null) { user = appID = cons.readLine(Config.AAF_APPID + ": "); access.setProperty(Config.AAF_APPID, appID); addProp(Config.AAF_APPID, appID); @@ -229,7 +229,7 @@ public class AAFSSO { } } else { encrypted_pass = access.getProperty(Config.CADI_KEYSTORE_PASSWORD); - if(encrypted_pass == null) { + if (encrypted_pass == null) { keystore_pass = null; encrypted_pass = access.getProperty(Config.AAF_APPPASS); } else { @@ -298,9 +298,9 @@ public class AAFSSO { } String locateUrl = access.getProperty(Config.AAF_LOCATE_URL); - if(locateUrl==null) { + if (locateUrl==null) { locateUrl=AAFSSO.cons.readLine("AAF Locator URL=https://"); - if(locateUrl==null || locateUrl.length()==0) { + if (locateUrl==null || locateUrl.length()==0) { err = new StringBuilder(Config.AAF_LOCATE_URL); err.append(" is required."); ok = false; @@ -315,10 +315,10 @@ public class AAFSSO { access.setProperty(Config.AAF_URL, Defaults.AAF_URL); access.setProperty(Config.CM_URL, Defaults.CM_URL); String cadiLatitude = access.getProperty(Config.CADI_LATITUDE); - if(cadiLatitude==null) { + if (cadiLatitude==null) { System.out.println("# If you do not know your Global Coordinates, we suggest bing.com/maps"); cadiLatitude=AAFSSO.cons.readLine("cadi_latitude[0.000]="); - if(cadiLatitude==null || cadiLatitude.isEmpty()) { + if (cadiLatitude==null || cadiLatitude.isEmpty()) { cadiLatitude="0.000"; } access.setProperty(Config.CADI_LATITUDE, cadiLatitude); @@ -326,9 +326,9 @@ public class AAFSSO { } String cadiLongitude = access.getProperty(Config.CADI_LONGITUDE); - if(cadiLongitude==null) { + if (cadiLongitude==null) { cadiLongitude=AAFSSO.cons.readLine("cadi_longitude[0.000]="); - if(cadiLongitude==null || cadiLongitude.isEmpty()) { + if (cadiLongitude==null || cadiLongitude.isEmpty()) { cadiLongitude="0.000"; } access.setProperty(Config.CADI_LONGITUDE, cadiLongitude); @@ -336,7 +336,7 @@ public class AAFSSO { } String cadi_truststore = access.getProperty(Config.CADI_TRUSTSTORE); - if(cadi_truststore==null) { + if (cadi_truststore==null) { String name; String select; for (File tsf : dot_aaf.listFiles()) { @@ -344,7 +344,7 @@ public class AAFSSO { if (name.contains("trust") && (name.endsWith(".jks") || name.endsWith(".p12"))) { select = cons.readLine("Use %s for TrustStore? (y/n):",tsf.getName()); - if("y".equalsIgnoreCase(select)) { + if ("y".equalsIgnoreCase(select)) { cadi_truststore=tsf.getCanonicalPath(); access.setProperty(Config.CADI_TRUSTSTORE, cadi_truststore); addProp(Config.CADI_TRUSTSTORE, cadi_truststore); @@ -353,12 +353,12 @@ public class AAFSSO { } } } - if(cadi_truststore!=null) { - if(cadi_truststore.indexOf(File.separatorChar)<0) { + if (cadi_truststore!=null) { + if (cadi_truststore.indexOf(File.separatorChar)<0) { cadi_truststore=dot_aaf.getPath()+File.separator+cadi_truststore; } String cadi_truststore_password = access.getProperty(Config.CADI_TRUSTSTORE_PASSWORD); - if(cadi_truststore_password==null) { + if (cadi_truststore_password==null) { cadi_truststore_password=AAFSSO.cons.readLine("cadi_truststore_password[%s]=","changeit"); cadi_truststore_password = access.encrypt(cadi_truststore_password); access.setProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadi_truststore_password); @@ -381,7 +381,7 @@ public class AAFSSO { } public void setLogDefault(Level level) { - if(access!=null) { + if (access!=null) { access.setLogLevel(level); } System.setOut(stdOutOrig); @@ -392,7 +392,7 @@ public class AAFSSO { } public void addProp(String key, String value) { - if(key==null || value==null) { + if (key==null || value==null) { return; } touchDiskprops=true; @@ -400,7 +400,7 @@ public class AAFSSO { } public void writeFiles() throws IOException { - if(touchDiskprops) { + if (touchDiskprops) { // Store Creds, if they work if (diskprops != null) { if (!dot_aaf.exists()) { diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java index 8cb4e906..5e642c67 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/test/TestHClient.java @@ -44,14 +44,14 @@ public class TestHClient { try { PropAccess access = new PropAccess(args); String aaf_url = access.getProperty(Config.AAF_URL); - if(aaf_url == null) { + if (aaf_url == null) { access.log(Level.ERROR, Config.AAF_URL," is required"); } else { HMangr hman = null; try { SecurityInfoC<HttpURLConnection> si = SecurityInfoC.instance(access, HttpURLConnection.class); AbsAAFLocator<BasicTrans> loc = new AAFLocator(si,new URI(aaf_url)); - for(Item item = loc.first(); item!=null; item=loc.next(item)) { + for (Item item = loc.first(); item!=null; item=loc.next(item)) { System.out.println(loc.get(item)); } @@ -62,7 +62,7 @@ public class TestHClient { @Override public Void code(Rcli<?> cli) throws APIException, CadiException { Future<String> ft = cli.read(path,"application/json"); - if(ft.get(10000)) { + if (ft.get(10000)) { System.out.println("Hurray,\n"+ft.body()); } else { System.out.println("not quite: " + ft.code()); @@ -70,7 +70,7 @@ public class TestHClient { return null; }}); } finally { - if(hman!=null) { + if (hman!=null) { hman.close(); } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java index 70550451..60e5b44a 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_ArtifactDir.java @@ -110,14 +110,14 @@ public class JU_ArtifactDir { try { ArtifactDir.write(writableFile, Chmod.to755, (String[])null); fail("Should've thrown an exception"); - } catch(NullPointerException e) { + } catch (NullPointerException e) { } KeyStore ks = KeyStore.getInstance(Agent.PKCS12); try { ArtifactDir.write(writableFile, Chmod.to755, ks, luggagePassword.toCharArray()); fail("Should've thrown an exception"); - } catch(CadiException e) { + } catch (CadiException e) { } ks.load(null, null); diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java index 76c31b8d..69709d9f 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_Factory.java @@ -331,8 +331,8 @@ public class JU_Factory { private String join(String delim, List<String> rawLines) { StringBuilder sb = new StringBuilder(); boolean first = true; - for(String s : rawLines) { - if(first) { + for (String s : rawLines) { + if (first) { first = false; } else { sb.append(delim); diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java index 1a653ab2..777ca16d 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/cm/test/JU_PlaceArtifactInKeystore.java @@ -141,8 +141,8 @@ public class JU_PlaceArtifactInKeystore { baos.write(br.readLine().getBytes()); // Here comes the hacky part baos.write("\n".getBytes()); - while((line=br.readLine())!=null) { - if(line.length()>0) { + while ((line=br.readLine())!=null) { + if (line.length()>0) { baos.write(line.getBytes()); baos.write("\n".getBytes()); } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java index 537e218f..24e30a46 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_AAFToken.java @@ -49,7 +49,7 @@ public class JU_AAFToken { @Test public void testRandom() throws CadiException { - for(int i=0;i<100;++i) { + for (int i=0;i<100;++i) { UUID uuid = UUID.randomUUID(); String token = AAFToken.toToken(uuid); UUID uuid2 = AAFToken.fromToken(token); diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java index ef22b792..03c99d2a 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/oauth/test/JU_OAuthTest.java @@ -109,21 +109,21 @@ public class JU_OAuthTest { TokenClient tc; Result<TimedToken> rtt; - if(true) { + if (true) { tc = tcf.newClient(tokenServiceURL, 3000); tc.client_creds(client_id,client_secret); tc.password(access.getProperty("cadi_username"),access.getProperty("cadi_password")); rtt = tc.getToken(Kind.BASIC_AUTH,"org.osaaf.aaf","org.osaaf.test"); - if(rtt.isOK()) { + if (rtt.isOK()) { print(rtt.value); rtt = tc.refreshToken(rtt.value); - if(rtt.isOK()) { + if (rtt.isOK()) { print(rtt.value); TokenClient ic = tcf.newClient(tokenIntrospectURL,3000); ic.client_creds(client_id,client_secret); Result<Introspect> ri = ic.introspect(rtt.value.getAccessToken()); - if(ri.isOK()) { + if (ri.isOK()) { print(ri.value); } else { System.out.println(ri.code + ' ' + ri.error); @@ -145,28 +145,28 @@ public class JU_OAuthTest { } // ISAM Test - if(true) { + if (true) { System.out.println("**** ISAM TEST ****"); tokenServiceURL=access.getProperty(Config.AAF_ALT_OAUTH2_TOKEN_URL); client_id=access.getProperty(Config.AAF_ALT_CLIENT_ID); client_secret=access.getProperty(Config.AAF_ALT_CLIENT_SECRET); - if(tokenServiceURL!=null) { + if (tokenServiceURL!=null) { tc = tcf.newClient(tokenServiceURL, 3000); tc.client_creds(client_id, client_secret); int at = username.indexOf('@'); tc.password(at>=0?username.substring(0, at):username,access.getProperty("cadi_password")); rtt = tc.getToken("org.osaaf.aaf","org.osaaf.test"); - if(rtt.isOK()) { + if (rtt.isOK()) { print(rtt.value); rtt = tc.refreshToken(rtt.value); - if(rtt.isOK()) { + if (rtt.isOK()) { print(rtt.value); tc = tcf.newClient(tokenAltIntrospectURL, 3000); tc.client_creds(client_id, client_secret); Result<Introspect> rti = tc.introspect(rtt.value.getAccessToken()); - if(rti.isOK()) { + if (rti.isOK()) { System.out.print("Normal ISAM "); print(rti.value); } else { @@ -177,12 +177,12 @@ public class JU_OAuthTest { tc = tcf.newClient(tokenIntrospectURL, 3000); tc.client_creds(client_id, client_secret); rti = tc.introspect(rtt.value.getAccessToken()); - if(rti.isOK()) { + if (rti.isOK()) { System.out.print("AAF with ISAM Token "); print(rti.value); } else { System.out.println(rti.code + ' ' + rti.error); - if(rti.code!=404) { + if (rti.code!=404) { Assert.fail(rti.code + ' ' + rti.error); } } @@ -214,14 +214,14 @@ public class JU_OAuthTest { // private TokenClient testROPCFlow(final String url, final String client_id, final String client_secret, String user, String password, final String ... scope) throws Exception { // TokenClient tclient = tcf.newClient(url,3000); // tclient.client_creds(client_id, client_secret); -// if(user!=null && password!=null) { +// if (user!=null && password!=null) { // tclient.password(user,password); // } // Result<TimedToken> rt = tclient.getToken(scope); -// if(rt.isOK()) { +// if (rt.isOK()) { // print(rt.value); // Result<Introspect> rti = tclient.introspect(rt.value.getAccessToken()); -// if(rti.isOK()) { +// if (rti.isOK()) { // print(rti.value); // } else { // printAndFail(rti); @@ -237,7 +237,7 @@ public class JU_OAuthTest { @Override public String code(Rcli<?> client) throws CadiException, ConnectException, APIException { Future<String> future = client.read(null,"text/plain"); - if(future.get(3000)) { + if (future.get(3000)) { return future.value; } else { throw new APIException(future.code() + future.body()); @@ -263,7 +263,7 @@ public class JU_OAuthTest { } private void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { + if (ti==null || ti.getClientId()==null) { System.out.println("Empty Introspect"); return; } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java b/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java index 8881e76e..4e51579d 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/client/sample/Sample.java @@ -70,7 +70,7 @@ public class Sample { */ public Principal checkUserPass(String fqi, String pass) throws IOException, CadiException { String ok = aafAuthn.validate(fqi, pass); - if(ok==null) { + if (ok==null) { System.out.println("Success!"); /* UnAuthPrincipal means that it is not coming from the official Authorization chain. @@ -127,14 +127,14 @@ public class Sample { String user = myAccess.getProperty("user_fqi"); String pass= myAccess.getProperty("user_pass"); - if(user==null || pass==null) { + if (user==null || pass==null) { System.err.println("This Sample class requires properties user_fqi and user_pass"); } else { pass = myAccess.decrypt(pass, false); // Note, with "false", decryption will only happen if starts with "enc:" // See the CODE for Java Methods used Principal fqi = Sample.singleton().checkUserPass(user,pass); - if(fqi==null) { + if (fqi==null) { System.out.println("OK, normally, you would cease processing for an " + "unauthenticated user, but for the purpose of Sample, we'll keep going.\n"); fqi=new UnAuthPrincipal(user); @@ -146,10 +146,10 @@ public class Sample { // note, default String for perm String permS = myAccess.getProperty("perm","org.osaaf.aaf.access|*|read"); String[] permA = Split.splitTrim('|', permS); - if(permA.length>2) { + if (permA.length>2) { final Permission perm = new AAFPermission(null, permA[0],permA[1],permA[2]); // See the CODE for Java Methods used - if(singleton().oneAuthorization(fqi, perm)) { + if (singleton().oneAuthorization(fqi, perm)) { System.out.printf("Success: %s has %s\n",fqi.getName(),permS); } else { System.out.printf("%s does NOT have %s\n",fqi.getName(),permS); @@ -160,11 +160,11 @@ public class Sample { // Another form, you can get ALL permissions in a list // See the CODE for Java Methods used List<Permission> permL = singleton().allAuthorization(fqi); - if(permL.size()==0) { + if (permL.size()==0) { System.out.printf("User %s has no Permissions THAT THE CALLER CAN SEE\n",fqi.getName()); } else { System.out.print("Success:\n"); - for(Permission p : permL) { + for (Permission p : permL) { System.out.printf("\t%s has %s\n",fqi.getName(),p.getKey()); } } 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 cce7b5f3..da85702d 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 @@ -76,7 +76,7 @@ public abstract class AbsAuthentication<CLIENT> implements SecuritySetter<CLIENT } protected String headValue() throws IOException { - if(headValue==null) { + if (headValue==null) { return ""; } else { return new String(symm.decode(headValue)); @@ -93,7 +93,7 @@ public abstract class AbsAuthentication<CLIENT> implements SecuritySetter<CLIENT } public boolean isDenied() { - if(lastMiss>0 && lastMiss>System.currentTimeMillis()) { + if (lastMiss>0 && lastMiss>System.currentTimeMillis()) { return true; } else { lastMiss=0L; @@ -102,17 +102,17 @@ public abstract class AbsAuthentication<CLIENT> implements SecuritySetter<CLIENT } public synchronized int setLastResponse(int httpcode) { - if(httpcode == 401) { + if (httpcode == 401) { ++count; - if(lastMiss==0L && count>MAX_TEMP_COUNT) { + if (lastMiss==0L && count>MAX_TEMP_COUNT) { lastMiss=System.currentTimeMillis()+WAIT_TIME; } - // if(count>MAX_SPAM_COUNT) { + // 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) { + 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); } 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 0c38bd90..baac6daa 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 @@ -56,7 +56,7 @@ public abstract class AbsTransferSS<CLIENT> implements SecuritySetter<CLIENT> { private void init(TaggedPrincipal principal, String app) { this.principal=principal; - if(principal==null) { + if (principal==null) { return; } else { value = principal.getName() + ':' + 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 b414487b..6b486b8e 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 @@ -268,20 +268,20 @@ public abstract class Rcli<CT> { @Override public void transfer(OutputStream os) throws IOException, APIException { PrintStream ps; - if(os instanceof PrintStream) { + if (os instanceof PrintStream) { ps = (PrintStream)os; } else { ps = new PrintStream(os); } boolean first = true; - for(String fp : formParam) { - if(fp!=null) { - if(first) { + for (String fp : formParam) { + if (fp!=null) { + if (first) { first = false; } else { ps.print('&'); } - if(fp.endsWith("=")) { + if (fp.endsWith("=")) { first = true; } ps.print(fp); @@ -376,7 +376,7 @@ public abstract class Rcli<CT> { client.setMethod(GET); client.addHeader(ACCEPT, accept); - for(int i=1;i<headers.length;i=i+2) { + for (int i=1;i<headers.length;i=i+2) { client.addHeader(headers[i-1],headers[i]); } client.setPathInfo(pp.path()); @@ -393,7 +393,7 @@ public abstract class Rcli<CT> { EClient<CT> client = client(); client.setMethod(GET); client.addHeader(ACCEPT, accept); - for(int i=1;i<headers.length;i=i+2) { + for (int i=1;i<headers.length;i=i+2) { client.addHeader(headers[i-1],headers[i]); } client.setPathInfo(pp.path()); @@ -410,7 +410,7 @@ public abstract class Rcli<CT> { EClient<CT> client = client(); client.setMethod(GET); client.addHeader(ACCEPT, typeString(df.getTypeClass())); - for(int i=1;i<headers.length;i=i+2) { + for (int i=1;i<headers.length;i=i+2) { client.addHeader(headers[i-1],headers[i]); } client.setPathInfo(pp.path()); @@ -664,7 +664,7 @@ public abstract class Rcli<CT> { throw new CadiException("Invalid incoming URI",e); } String name; - for(Enumeration<String> en = req.getHeaderNames();en.hasMoreElements();) { + for (Enumeration<String> en = req.getHeaderNames();en.hasMoreElements();) { name = en.nextElement(); client.addHeader(name,req.getHeader(name)); } @@ -673,7 +673,7 @@ public abstract class Rcli<CT> { client.setPathInfo(pathParam); String meth = req.getMethod(); client.setMethod(meth); - if(!"GET".equals(meth)) { + if (!"GET".equals(meth)) { client.setPayload(new EClient.Transfer() { @Override public void transfer(OutputStream os) throws IOException, APIException { @@ -682,7 +682,7 @@ public abstract class Rcli<CT> { // reuse Buffers Pooled<byte[]> pbuff = buffPool.get(); try { - while((read=is.read(pbuff.content))>=0) { + while ((read=is.read(pbuff.content))>=0) { os.write(pbuff.content,0,read); } } finally { @@ -704,21 +704,21 @@ public abstract class Rcli<CT> { public ParsePath(final String origPath) { path = origPath; - if(origPath==null) { + 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) { + if (oneCallQueryParams==null) { + if (query>=0) { queryParams = path.substring(query+1,queryEnd); } else { queryParams=null; } } else { - if(query>=0) { + if (query>=0) { queryParams = oneCallQueryParams + '&' + path.substring(query+1,queryEnd); } else { queryParams = oneCallQueryParams; @@ -729,12 +729,12 @@ public abstract class Rcli<CT> { } public String path() { - if(query>=0) { - if(pound>=0) { + if (query>=0) { + if (pound>=0) { return path.substring(pound+1); } return path.substring(0,query); - } else if(pound>=0) { + } else if (pound>=0) { return path.substring(0,pound); } else { return path; @@ -746,7 +746,7 @@ public abstract class Rcli<CT> { } public String frag() { - if(pound>=0) { + if (pound>=0) { return path.substring(pound+1); } else { return null; 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 e9de27e7..0e2a4b16 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 @@ -51,7 +51,7 @@ public class Result<T> { public String toString() { StringBuilder sb = new StringBuilder("Code: "); sb.append(code); - if(error!=null) { + if (error!=null) { sb.append(" = "); sb.append(error); } 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 3c38ff8d..c2f56458 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 @@ -38,7 +38,7 @@ public class HAuthorizationHeader extends AbsAuthentication<HttpURLConnection> { @Override public void setSecurity(HttpURLConnection huc) throws CadiException { - if(isDenied()) { + if (isDenied()) { throw new CadiException(REPEAT_OFFENDER); } try { @@ -46,7 +46,7 @@ public class HAuthorizationHeader extends AbsAuthentication<HttpURLConnection> { } catch (IOException e) { throw new CadiException(e); } - if(securityInfo!=null && huc instanceof HttpsURLConnection) { + 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 e4ab6d72..7e5cbd3b 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 @@ -48,7 +48,7 @@ public class HBasicAuthSS extends HAuthorizationHeader implements BasicAuth { public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, String user, String pass, boolean asDefault) throws IOException { this(si, user,pass); - if(asDefault) { + if (asDefault) { si.set(this); } } @@ -59,7 +59,7 @@ public class HBasicAuthSS extends HAuthorizationHeader implements BasicAuth { public HBasicAuthSS(BasicPrincipal bp, SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws IOException { this(si, bp.getName(),new String(bp.getCred())); - if(asDefault) { + 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 1d3d9547..d8852834 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 @@ -111,13 +111,13 @@ public class HClient implements EClient<HttpURLConnection> { public void send() throws APIException { try { // Build URL from given URI plus current Settings - if(uri.getPath()==null) { + if (uri.getPath()==null) { throw new APIException("Invalid URL entered for HClient"); } StringBuilder pi=null; - if(pathinfo!=null) { // additional pathinfo + if (pathinfo!=null) { // additional pathinfo pi = new StringBuilder(uri.getPath()); - if(!pathinfo.startsWith("/")) { + if (!pathinfo.startsWith("/")) { pi.append('/'); } pi.append(pathinfo); @@ -133,7 +133,7 @@ public class HClient implements EClient<HttpURLConnection> { ); huc = getConnection(sendURI, pi); huc.setRequestMethod(meth); - if(ss!=null) { + if (ss!=null) { ss.setSecurity(huc); } if (headers != null) @@ -153,7 +153,7 @@ public class HClient implements EClient<HttpURLConnection> { throw new APIException(e); } finally { // ensure all these are reset after sends meth=pathinfo=null; - if(headers!=null) { + if (headers!=null) { headers.clear(); } pathinfo = query = fragment = ""; @@ -200,7 +200,7 @@ public class HClient implements EClient<HttpURLConnection> { huc.setReadTimeout(timeout); respCode = huc.getResponseCode(); ss.setLastResponse(respCode); - if(evalInfo(huc)) { + if (evalInfo(huc)) { return true; } else { extractError(); @@ -216,13 +216,13 @@ public class HClient implements EClient<HttpURLConnection> { private void extractError() { InputStream is = huc.getErrorStream(); try { - if(is==null) { + if (is==null) { is = huc.getInputStream(); } - if(is!=null) { + if (is!=null) { errContent = new StringBuilder(); int c; - while((c=is.read())>=0) { + while ((c=is.read())>=0) { errContent.append((char)c); } } @@ -274,7 +274,7 @@ public class HClient implements EClient<HttpURLConnection> { } public void close() { - if(huc!=null) { + if (huc!=null) { huc.disconnect(); } } @@ -382,12 +382,12 @@ public class HClient implements EClient<HttpURLConnection> { int read; InputStream is; OutputStream os = resp.getOutputStream(); - if(respCode==expected) { + if (respCode==expected) { is = huc.getInputStream(); // reuse Buffers Pooled<byte[]> pbuff = Rcli.buffPool.get(); try { - while((read=is.read(pbuff.content))>=0) { + while ((read=is.read(pbuff.content))>=0) { os.write(pbuff.content,0,read); } } finally { @@ -396,14 +396,14 @@ public class HClient implements EClient<HttpURLConnection> { return true; } else { is = huc.getErrorStream(); - if(is==null) { + if (is==null) { is = huc.getInputStream(); } - if(is!=null) { + if (is!=null) { errContent = new StringBuilder(); Pooled<byte[]> pbuff = Rcli.buffPool.get(); try { - while((read=is.read(pbuff.content))>=0) { + while ((read=is.read(pbuff.content))>=0) { os.write(pbuff.content,0,read); } } finally { 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 da349efc..8e3138af 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 @@ -49,7 +49,7 @@ public class HMangr { public HMangr(Access access, Locator<URI> loc) throws LocatorException { readTimeout = 10000; connectionTimeout=3000; - if(loc == null) { + if (loc == null) { throw new LocatorException("Null Locator passed"); } this.loc = loc; @@ -79,20 +79,20 @@ public class HMangr { do { Item item; // if no previous state, get the best - if(retryable.item()==null) { + if (retryable.item()==null) { item = loc.best(); - if(item==null) { + if (item==null) { throw new LocatorException("No Services Found for " + loc); } retryable.item(item); retryable.lastClient = null; } - if(client==null) { + if (client==null) { item = retryable.item(); URI uri=loc.get(item); - if(uri==null) { + if (uri==null) { loc.invalidate(retryable.item()); - if(loc.hasItems()) { + if (loc.hasItems()) { retryable.item(loc.next(retryable.item())); continue; } else { @@ -116,22 +116,22 @@ public class HMangr { retryable.item(loc.next(item)); try { Throwable ec = e.getCause(); - if(ec instanceof java.net.ConnectException) { - if(client!=null && loc.hasItems()) { + 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()) { + } 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())) { + } 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); @@ -148,7 +148,7 @@ public class HMangr { loc.invalidate(item); retryable.item(loc.next(item)); } - } while(retry); + } while (retry); } finally { retryable.lastClient = client; } @@ -172,9 +172,9 @@ public class HMangr { RET ret = null; // make sure we have all current references: loc.refresh(); - for(Item li=loc.first();li!=null;li=loc.next(li)) { + for (Item li=loc.first();li!=null;li=loc.next(li)) { URI uri=loc.get(li); - if(host!=null && !host.equals(uri.getHost())) { + if (host!=null && !host.equals(uri.getHost())) { break; } try { @@ -182,14 +182,14 @@ public class HMangr { 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) { + 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) { + } 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())) { + } 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); @@ -203,7 +203,7 @@ public class HMangr { } } - if(ret == null && notify) + if (ret == null && notify) throw new LocatorException("No available clients to call"); return ret; } 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 0f1c8b41..1fecce2b 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 @@ -37,7 +37,7 @@ public class HNoAuthSS extends AbsAuthentication<HttpURLConnection> { @Override public void setSecurity(HttpURLConnection client) throws CadiException { - if(securityInfo!=null && client instanceof HttpsURLConnection) { + 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 674936d7..cbd7b33e 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 @@ -81,9 +81,9 @@ public class HRcli extends Rcli<HttpURLConnection> { */ protected EClient<HttpURLConnection> client() throws CadiException { try { - if(uri==null) { + if (uri==null) { Item item = hman.loc.best(); - if(item==null) { + if (item==null) { throw new CadiException("No service available for " + hman.loc.toString()); } uri = hman.loc.get(item); 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 d792be49..3f3517f2 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 @@ -41,9 +41,9 @@ public class HSecurityInfoInit implements SecurityInfoInit<HttpURLConnection> { @Override public SecuritySetter<HttpURLConnection> bestDefault(SecurityInfoC<HttpURLConnection> si) throws CadiException { try { - if(si.defaultAlias!=null) { + if (si.defaultAlias!=null) { si.set(new HX509SS(si)); - } else if(si.access.getProperty(Config.AAF_APPID, null)!=null && + } else if (si.access.getProperty(Config.AAF_APPID, null)!=null && si.access.getProperty(Config.AAF_APPPASS, null)!=null) { si.set(new HBasicAuthSS(si)); } 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 c527ed02..f68c1f61 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 @@ -44,14 +44,14 @@ public class HTransferSS extends AbsTransferSS<HttpURLConnection> { @Override public void setSecurity(HttpURLConnection huc) throws CadiException { - if(defSS==null) { + if (defSS==null) { throw new CadiException("Need App Credentials to send message"); } defSS.setSecurity(huc); - if(value!=null) { + if (value!=null) { huc.addRequestProperty(Config.CADI_USER_CHAIN, value); } - if(securityInfo!=null) { + if (securityInfo!=null) { securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); } } 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 cb8e6ce0..f441186e 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 @@ -68,8 +68,8 @@ public class HX509SS implements SecuritySetter<HttpURLConnection> { public HX509SS(final String sendAlias, SecurityInfoC<HttpURLConnection> si, boolean asDefault) throws APIException, CadiException { securityInfo = si; - if((alias=sendAlias) == null) { - if(si.defaultAlias == null) { + 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; @@ -78,16 +78,16 @@ public class HX509SS implements SecuritySetter<HttpURLConnection> { priv=null; X509KeyManager[] xkms = si.getKeyManagers(); - if(xkms==null || xkms.length==0) { + 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) { + 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) { + for (int i=0;cert==null&&i<xkms.length;++i) { X509Certificate[] chain = xkms[i].getCertificateChain(alias); - if(chain!=null&&chain.length>0) { + if (chain!=null&&chain.length>0) { algo = chain[0].getSigAlgName(); pub = chain[0].getEncoded(); ByteArrayOutputStream baos = new ByteArrayOutputStream(pub.length*2); @@ -99,17 +99,17 @@ public class HX509SS implements SecuritySetter<HttpURLConnection> { } catch (CertificateEncodingException | IOException e) { throw new CadiException(e); } - if(algo==null) { + if (algo==null) { throw new APIException("X509 Security Setter not configured"); } } @Override public void setSecurity(HttpURLConnection huc) throws CadiException { - if(huc instanceof HttpsURLConnection) { + if (huc instanceof HttpsURLConnection) { securityInfo.setSocketFactoryOn((HttpsURLConnection)huc); } - if(alias==null) { // must be a one-way + if (alias==null) { // must be a one-way huc.setRequestProperty(AbsAuthentication.AUTHORIZATION, cert); // Test Signed content 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 1fc4b83e..8357129f 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 @@ -46,7 +46,7 @@ public class DNSLocator implements Locator<URI> { this.protocol = protocol; this.access = access; int dash = range.indexOf('-'); - if(dash<0) { + if (dash<0) { startPort = endPort = Integer.parseInt(range); } else { startPort = Integer.parseInt(range.substring(0,dash)); @@ -57,15 +57,15 @@ public class DNSLocator implements Locator<URI> { public DNSLocator(Access access, String aaf_locate) throws LocatorException { this.access = access; - if(aaf_locate==null) { + if (aaf_locate==null) { throw new LocatorException("Null passed into DNSLocator constructor"); } int start, port; - if(aaf_locate.startsWith("https:")) { + if (aaf_locate.startsWith("https:")) { protocol = "https:"; start = 9; // https:// port = 443; - } else if(aaf_locate.startsWith("http:")) { + } else if (aaf_locate.startsWith("http:")) { protocol = "http:"; start = 8; // http:// port = 80; @@ -83,8 +83,8 @@ public class DNSLocator implements Locator<URI> { @Override public boolean hasItems() { - for(Host h : hosts) { - if(h.status==Status.OK) { + for (Host h : hosts) { + if (h.status==Status.OK) { return true; } } @@ -100,7 +100,7 @@ public class DNSLocator implements Locator<URI> { @Override public Item best() throws LocatorException { // not a good "best" - for(int i=0;i<hosts.length;++i) { + for (int i=0;i<hosts.length;++i) { switch(hosts[i].status) { case OK: return new DLItem(i); @@ -110,7 +110,7 @@ public class DNSLocator implements Locator<URI> { break; case UNTRIED: try { - if(hosts[i].ia.isReachable(CHECK_TIME)) { + if (hosts[i].ia.isReachable(CHECK_TIME)) { hosts[i].status = Status.OK; return new DLItem(i); } @@ -133,7 +133,7 @@ public class DNSLocator implements Locator<URI> { @Override public Item next(Item item) throws LocatorException { DLItem di = (DLItem)item; - if(++di.cnt<hosts.length) { + if (++di.cnt<hosts.length) { return di; } else { return null; @@ -146,8 +146,8 @@ public class DNSLocator implements Locator<URI> { 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) { + for (int j=startPort; j<=endPort; ++j) { + for (int i=0;i<ias.length;++i) { temp[++cnt] = new Host(ias[i], j, suffix); } } @@ -162,10 +162,10 @@ public class DNSLocator implements Locator<URI> { private void parsePorts(String aaf_locate, int defaultPort) throws LocatorException { int slash, start; int colon = aaf_locate.indexOf(':'); - if(colon > 0) { + if (colon > 0) { start = colon + 1; int left = aaf_locate.indexOf('[', start); - if(left > 0) { + 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 + ')'); @@ -176,7 +176,7 @@ public class DNSLocator implements Locator<URI> { if (dash == (right - 1) || dash == (left + 1)) { throw new LocatorException("Missing ports in brackets in DNSLocator constructor. (requested URL " + aaf_locate + ')'); } - if(dash < 0) { + if (dash < 0) { startPort = endPort = Integer.parseInt(aaf_locate.substring(left + 1, right)); } else { startPort = Integer.parseInt(aaf_locate.substring(left + 1, dash)); @@ -188,7 +188,7 @@ public class DNSLocator implements Locator<URI> { if (slash == start) { throw new LocatorException("Missing port before '/' in DNSLocator constructor. (requested URL " + aaf_locate + ')'); } - if(slash < 0) { + if (slash < 0) { startPort = endPort = Integer.parseInt(aaf_locate.substring(start)); } else { startPort = endPort = Integer.parseInt(aaf_locate.substring(start, slash)); 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 26b8817b..93cefc58 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 @@ -74,15 +74,15 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { this.invalidateTime = invalidateTime; double distance = Double.MAX_VALUE; - for(int i=0;i<urlstrs.length;++i) { + for (int i=0;i<urlstrs.length;++i) { String[] info = Split.split('/', urlstrs[i]); - if(info.length<3) { + 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) { + } catch (LocatorException le) { failures[i] = System.currentTimeMillis()+invalidateTime; } @@ -90,15 +90,15 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { distances[i]=d; // find preferred server - if(d<distance) { + 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) { + for (int i=0;i<urlstrs.length;++i) { + if (i!=preferred) { access.printf(Level.INIT,"Alternate Client is %s",urlstrs[i]); } } @@ -117,7 +117,7 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { @Override public Item best() throws LocatorException { - if(failures[preferred]==0L) { + if (failures[preferred]==0L) { return new HPItem(preferred); } else { long now = System.currentTimeMillis(); @@ -125,9 +125,9 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { 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) { + for (int i=0;i<urlstrs.length;++i) { + if (failures[i]<now && distances[i]<d) { + if (clients[i]!=null) { best = i; break; } else { @@ -135,13 +135,13 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { } } } - if(best<0 && tickle) { + if (best<0 && tickle) { tickle=false; - if(refresh()) { + if (refresh()) { // try again - for(int i=0;i<urlstrs.length;++i) { - if(failures[i]==0L && distances[i]<d) { - if(clients[i]!=null) { + for (int i=0;i<urlstrs.length;++i) { + if (failures[i]==0L && distances[i]<d) { + if (clients[i]!=null) { best = i; break; } @@ -154,9 +154,9 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { * 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) { + if (tickle) { synchronized(clients) { - if(refreshThread==null) { + if (refreshThread==null) { refreshThread = new Thread(new Runnable(){ @Override public void run() { @@ -170,7 +170,7 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { } } - if(best<0) { + if (best<0) { throw new LocatorException("No Clients available"); } @@ -183,8 +183,8 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { 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()) { + if (c==null) { + if (failures[hpi.idx]>System.currentTimeMillis()) { throw new LocatorException("Client requested is invalid"); } else { synchronized(clients) { @@ -192,7 +192,7 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { failures[hpi.idx]=0L; } } - } else if(failures[hpi.idx]>0){ + } else if (failures[hpi.idx]>0){ throw new LocatorException("Client requested is invalid"); } return c; @@ -200,7 +200,7 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { public String info(Item item) { HPItem hpi = (HPItem)item; - if(hpi!=null && hpi.idx<urlstrs.length) { + if (hpi!=null && hpi.idx<urlstrs.length) { return urlstrs[hpi.idx]; } else { return "Invalid Item"; @@ -209,8 +209,8 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { @Override public boolean hasItems() { - for(int i=0;i<clients.length;++i) { - if(clients[i]!=null && failures[i]==0L) { + for (int i=0;i<clients.length;++i) { + if (clients[i]!=null && failures[i]==0L) { return true; } } @@ -233,7 +233,7 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { @Override public Item next(Item item) throws LocatorException { HPItem hpi = (HPItem)item; - if(++hpi.idx>=clients.length) { + if (++hpi.idx>=clients.length) { return null; } return hpi; @@ -244,11 +244,11 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { 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 + for (int i=0;i<clients.length;++i) { + if (failures[i]>0L && (failures[i]<now || force)) { // retry try { synchronized(clients) { - if(clients[i]==null) { + if (clients[i]==null) { clients[i]=_newClient(urlstrs[i]); } failures[i]=0L; @@ -264,8 +264,8 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { @Override public void destroy() { - for(int i=0;i<clients.length;++i) { - if(clients[i]!=null) { + for (int i=0;i<clients.length;++i) { + if (clients[i]!=null) { _destroy(clients[i]); clients[i] = null; } @@ -289,8 +289,8 @@ public abstract class HotPeerLocator<CLIENT> implements Locator<CLIENT> { } 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 + 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; } 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 c1073315..eb0ecf11 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 @@ -61,7 +61,7 @@ public class PropertyLocator implements Locator<URI> { minRefresh = minRefreshMillis; backgroundRefresh = backgroundRefreshMillis; lastRefreshed=0L; - if(locList==null) { + if (locList==null) { throw new LocatorException("No Location List given for PropertyLocator"); } String[] locarray = Split.split(',',locList); @@ -69,10 +69,10 @@ public class PropertyLocator implements Locator<URI> { random = new SecureRandom(); - for(int i=0;i<locarray.length;++i) { + for (int i=0;i<locarray.length;++i) { try { int range = locarray[i].indexOf(":["); - if(range<0) { + if (range<0) { uriList.add(new URI(locarray[i])); } else { String mach_colon = locarray[i].substring(0, range+1); @@ -81,7 +81,7 @@ public class PropertyLocator implements Locator<URI> { 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) { + for (int port=start;port<=end;++port) { uriList.add(new URI(mach_colon+port + (slash>=0?locarray[i].substring(slash):""))); } } @@ -106,7 +106,7 @@ public class PropertyLocator implements Locator<URI> { @Override public URI get(Item item) throws LocatorException { synchronized(orig) { - if(item==null) { + if (item==null) { return null; } else { return resolved[((PLItem)item).idx]; @@ -126,31 +126,31 @@ public class PropertyLocator implements Locator<URI> { @Override public Item next(Item item) throws LocatorException { - if(item==null) { + if (item==null) { return null; } else { int spot; - if((spot=(((PLItem)item).order+1))>=end)return null; + if ((spot=(((PLItem)item).order+1))>=end)return null; return current[spot]; } } @Override public synchronized void invalidate(Item item) throws LocatorException { - if(--end<0) { + if (--end<0) { refresh(); return; } - if(item==null) { + if (item==null) { return; } PLItem pli = (PLItem)item; int i,order; - for(i=0;i<end;++i) { - if(pli==current[i])break; + for (i=0;i<end;++i) { + if (pli==current[i])break; } order = current[i].order; - for(;i<end;++i) { + for (;i<end;++i) { current[i]=current[i+1]; current[i].order=order++; } @@ -159,7 +159,7 @@ public class PropertyLocator implements Locator<URI> { @Override public Item best() throws LocatorException { - if(current.length==0) { + if (current.length==0) { refresh(); } switch(current.length) { @@ -175,27 +175,27 @@ public class PropertyLocator implements Locator<URI> { @Override public synchronized boolean refresh() { - if(System.currentTimeMillis()>lastRefreshed) { + if (System.currentTimeMillis()>lastRefreshed) { // Build up list List<URI> resolve = new ArrayList<>(); String realname; - for(int i = 0; i < orig.length ; ++i) { + 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) { + 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 + if (port<0) { // default port = "https".equalsIgnoreCase(o.getScheme())?443:80; } socket.connect(new InetSocketAddress(realname,port),3000); try { - if(socket.isConnected()) { + if (socket.isConnected()) { n = new URI( o.getScheme(), o.getUserInfo(), @@ -212,7 +212,7 @@ public class PropertyLocator implements Locator<URI> { } } catch (IOException e) { } finally { - if(!socket.isClosed()) { + if (!socket.isClosed()) { try { socket.close(); } catch (IOException e) { @@ -227,14 +227,14 @@ public class PropertyLocator implements Locator<URI> { } end=resolve.size(); PLItem[] newCurrent; - if(current==null || current.length!=end) { + if (current==null || current.length!=end) { newCurrent = new PLItem[end]; } else { newCurrent = current; } - for(int i=0; i< end; ++i) { - if(newCurrent[i]==null){ + for (int i=0; i< end; ++i) { + if (newCurrent[i]==null){ newCurrent[i]=new PLItem(i); } else { newCurrent[i].idx=newCurrent[i].order=i; @@ -271,18 +271,18 @@ public class PropertyLocator implements Locator<URI> { public String toString() { StringBuilder sb = new StringBuilder(); boolean first = true; - for(URI uri : orig) { + for (URI uri : orig) { boolean isResolved=false; - if(uri!=null) { - if(first) { + if (uri!=null) { + if (first) { first = false; } else { sb.append(", "); } sb.append(uri.toString()); sb.append(" ["); - for(URI u2 : resolved) { - if(uri.equals(u2)) { + for (URI u2 : resolved) { + if (uri.equals(u2)) { isResolved = true; break; } 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 816dec82..3b79dba5 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 @@ -47,8 +47,8 @@ public class SingleEndpointLocator implements Locator<URI> { @Override public boolean hasItems() { - if(noRetryUntil!=null) { - if(new Date().after(noRetryUntil)) { + if (noRetryUntil!=null) { + if (new Date().after(noRetryUntil)) { noRetryUntil = null; } else { return false; 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 3bce5245..27eb507f 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 @@ -87,7 +87,7 @@ public class GreatCircle { switch(coords.length) { case 1: array = Split.split(',',coords[0]); - if(array.length!=4)return -1; + if (array.length!=4)return -1; return calc( Double.parseDouble(array[0]), Double.parseDouble(array[1]), @@ -97,7 +97,7 @@ public class GreatCircle { case 2: array = Split.split(',',coords[0]); String [] array2 = Split.split(',',coords[1]); - if(array.length!=2 || array2.length!=2)return -1; + if (array.length!=2 || array2.length!=2)return -1; return calc( Double.parseDouble(array[0]), Double.parseDouble(array[1]), 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 7b61e398..0eae1198 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 @@ -107,7 +107,7 @@ public class JU_PropertyLocator { private int countItems(PropertyLocator pl) throws LocatorException { int count = 0; - for(Item i = pl.first(); i != null; i = pl.next(i)) { + for (Item i = pl.first(); i != null; i = pl.next(i)) { ++count; } return count; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java b/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java index 142dde26..c4f3d504 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/AES.java @@ -100,7 +100,7 @@ public class AES implements Encryption { public CipherOutputStream outputStream(OutputStream os, boolean encrypt) { try { Cipher c = Cipher.getInstance(AES); - if(encrypt) { + if (encrypt) { c.init(Cipher.ENCRYPT_MODE,aeskeySpec); } else { c.init(Cipher.DECRYPT_MODE,aeskeySpec); @@ -116,7 +116,7 @@ public class AES implements Encryption { public CipherInputStream inputStream(InputStream is, boolean encrypt) { try { Cipher c = Cipher.getInstance(AES); - if(encrypt) { + if (encrypt) { c.init(Cipher.ENCRYPT_MODE,aeskeySpec); } else { c.init(Cipher.DECRYPT_MODE,aeskeySpec); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java b/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java index d9d4474d..e6d24dab 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/AbsUserCache.java @@ -76,10 +76,10 @@ public abstract class AbsUserCache<PERM extends Permission> { userMap = new ConcurrentHashMap<>(); - if(cleanInterval>0) { + if (cleanInterval>0) { cleanInterval = Math.max(MIN_INTERVAL, cleanInterval); synchronized(AbsUserCache.class) { // Lazy instantiate.. in case there is no cleanup needed - if(timer==null) { + if (timer==null) { timer = new Timer("CADI Cleanup Timer",true); } @@ -96,14 +96,14 @@ public abstract class AbsUserCache<PERM extends Permission> { missEncrypt = cache.missEncrypt; synchronized(AbsUserCache.class) { - if(cache.clean!=null && cache.clean.lur==null && this instanceof CachingLur) { + if (cache.clean!=null && cache.clean.lur==null && this instanceof CachingLur) { cache.clean.lur=(CachingLur<PERM>)this; } } } protected void setLur(CachingLur<PERM> lur) { - if(clean!=null)clean.lur = lur; + if (clean!=null)clean.lur = lur; } @@ -111,11 +111,11 @@ public abstract class AbsUserCache<PERM extends Permission> { Principal p = user.principal; String key; try { - if(p instanceof GetCred) { + if (p instanceof GetCred) { key = missKey(p.getName(), ((GetCred)p).getCred()); } else { byte[] cred; - if((cred=user.getCred())==null) { + if ((cred=user.getCred())==null) { key = user.name + NO_CRED; } else { key = missKey(user.name,cred); @@ -152,7 +152,7 @@ public abstract class AbsUserCache<PERM extends Permission> { return false; } Miss miss = missMap.get(mkey); - if(miss==null) { + if (miss==null) { missMap.put(mkey, new Miss(bs,clean==null?MIN_INTERVAL:clean.timeInterval,key)); return true; } @@ -165,7 +165,7 @@ public abstract class AbsUserCache<PERM extends Permission> { protected User<PERM> getUser(Principal principal) { String key; - if(principal instanceof GetCred) { + if (principal instanceof GetCred) { GetCred gc = (GetCred)principal; try { key = missKey(principal.getName(), gc.getCred()); @@ -177,7 +177,7 @@ public abstract class AbsUserCache<PERM extends Permission> { key = principal.getName()+NO_CRED; } User<PERM> u = userMap.get(key); - if(u!=null) { + if (u!=null) { u.incCount(); } return u; @@ -197,8 +197,8 @@ public abstract class AbsUserCache<PERM extends Permission> { return null; } u = userMap.get(key); - if(u!=null) { - if(u.permExpired()) { + if (u!=null) { + if (u.permExpired()) { userMap.remove(key); u=null; } else { @@ -223,7 +223,7 @@ public abstract class AbsUserCache<PERM extends Permission> { */ public void remove(String user) { Object o = userMap.remove(user); - if(o!=null) { + if (o!=null) { access.log(Level.INFO, user,"removed from Client Cache by Request"); } } @@ -237,7 +237,7 @@ public abstract class AbsUserCache<PERM extends Permission> { public final List<DumpInfo> dumpInfo() { List<DumpInfo> rv = new ArrayList<>(); - for(User<PERM> user : userMap.values()) { + for (User<PERM> user : userMap.values()) { rv.add(new DumpInfo(user)); } return rv; @@ -256,7 +256,7 @@ public abstract class AbsUserCache<PERM extends Permission> { * If overloading in Derived class, be sure to call "super.destroy()" */ public void destroy() { - if(timer!=null) { + if (timer!=null) { timer.purge(); timer.cancel(); } @@ -318,13 +318,13 @@ public abstract class AbsUserCache<PERM extends Permission> { ArrayList<User<PERM>> al = new ArrayList<>(userMap.values().size()); al.addAll(0, userMap.values()); long now = System.currentTimeMillis() + advance; - for(User<PERM> user : al) { + for (User<PERM> user : al) { ++total; - if(user.count>usageTriggerCount) { + if (user.count>usageTriggerCount) { boolean touched = false, removed=false; - if(user.principal instanceof CachedPrincipal) { + if (user.principal instanceof CachedPrincipal) { CachedPrincipal cp = (CachedPrincipal)user.principal; - if(cp.expires() < now) { + if (cp.expires() < now) { switch(cp.revalidate(null)) { case INACCESSIBLE: access.log(Level.AUDIT, "AAF Inaccessible. Keeping credentials"); @@ -343,20 +343,20 @@ public abstract class AbsUserCache<PERM extends Permission> { } } - if(!removed && lur!=null && user.permExpires<= now ) { - if(lur.reload(user).equals(Resp.REVALIDATED)) { + if (!removed && lur!=null && user.permExpires<= now ) { + if (lur.reload(user).equals(Resp.REVALIDATED)) { user.renewPerm(); access.log(Level.DEBUG, "Reloaded Perms for",user); touched = true; } } user.resetCount(); - if(touched) { + if (touched) { ++renewed; } } else { - if(user.permExpired()) { + if (user.permExpired()) { remove(user); ++count; } @@ -366,14 +366,14 @@ public abstract class AbsUserCache<PERM extends Permission> { // Clean out Misses int missTotal = missMap.keySet().size(); int miss = 0; - if(missTotal>0) { + if (missTotal>0) { ArrayList<String> keys = new ArrayList<>(missTotal); keys.addAll(missMap.keySet()); - for(String key : keys) { + for (String key : keys) { Miss m = missMap.get(key); - if(m!=null) { + if (m!=null) { long timeLeft = m.timestamp - System.currentTimeMillis(); - if(timeLeft<0) { + if (timeLeft<0) { synchronized(missMap) { missMap.remove(key); } @@ -386,14 +386,14 @@ public abstract class AbsUserCache<PERM extends Permission> { } } - if(count+renewed+miss>0) { + if (count+renewed+miss>0) { access.log(Level.INFO, (lur==null?"Cache":lur.getClass().getSimpleName()), "removed",count, "and renewed",renewed,"expired Permissions out of", total,"and removed", miss, "password misses out of",missTotal); } // If High (total) is reached during this period, increase the number of expired services removed for next time. // There's no point doing it again here, as there should have been cleaned items. - if(total>high) { + if (total>high) { // advance cleanup by 10%, without getting greater than timeInterval. advance = Math.min(timeInterval, advance+(timeInterval/10)); } else { @@ -432,10 +432,10 @@ public abstract class AbsUserCache<PERM extends Permission> { public synchronized boolean mayContinue() { long ts = System.currentTimeMillis(); - if(ts>timestamp) { + if (ts>timestamp) { tries = 0; timestamp = ts + timetolive; - } else if(MAX_TRIES <= ++tries) { + } else if (MAX_TRIES <= ++tries) { return false; } return true; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java index 76d9bb2a..a673ab4f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Access.java @@ -57,7 +57,7 @@ public interface Access { } public int toggle(int mask) { - if(inMask(mask)) { + if (inMask(mask)) { return delFromMask(mask); } else { return addToMask(mask); @@ -67,8 +67,8 @@ public interface Access { public int maskOf() { int mask=0; - for(Level l : values()) { - if(ordinal()<=l.ordinal() && l!=NONE) { + for (Level l : values()) { + if (ordinal()<=l.ordinal() && l!=NONE) { mask|=l.bit; } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java b/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java index 3f47351b..8202183d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/BufferedServletInputStream.java @@ -63,19 +63,19 @@ public class BufferedServletInputStream extends ServletInputStream { public int read() throws IOException { int value=-1; - if(capacitor==null) { + if (capacitor==null) { value=is.read(); } else { switch(state) { case STORE: value = is.read(); - if(value>=0) { + if (value>=0) { capacitor.put((byte)value); } break; case READ: value = capacitor.read(); - if(value<0) { + if (value<0) { capacitor.done(); capacitor=null; // all done with buffer value = is.read(); @@ -92,27 +92,27 @@ public class BufferedServletInputStream extends ServletInputStream { public int read(byte[] b, int off, int len) throws IOException { int count = -1; - if(capacitor==null) { + if (capacitor==null) { count = is.read(b,off,len); } else { switch(state) { case STORE: count = is.read(b, off, len); - if(count>0) { + if (count>0) { capacitor.put(b, off, count); } break; case READ: count = capacitor.read(b, off, len); - if(count<=0) { + if (count<=0) { capacitor.done(); capacitor=null; // all done with buffer } - if(count<len) { + if (count<len) { int temp = is.read(b, count, len-count); - if(temp>0) { // watch for -1 + if (temp>0) { // watch for -1 count+=temp; - } else if(count<=0) { + } else if (count<=0) { count = temp; // must account for Stream coming back -1 } } @@ -124,7 +124,7 @@ public class BufferedServletInputStream extends ServletInputStream { public long skip(long n) throws IOException { long skipped = capacitor.skip(n); - if(skipped<n) { + if (skipped<n) { skipped += is.skip(n-skipped); } return skipped; @@ -133,7 +133,7 @@ public class BufferedServletInputStream extends ServletInputStream { public int available() throws IOException { int count = is.available(); - if(capacitor!=null)count+=capacitor.available(); + if (capacitor!=null)count+=capacitor.available(); return count; } @@ -147,7 +147,7 @@ public class BufferedServletInputStream extends ServletInputStream { public void close() throws IOException { - if(capacitor!=null) { + if (capacitor!=null) { capacitor.done(); capacitor=null; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java index 647cd8a6..34d11623 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CadiWrap.java @@ -118,13 +118,13 @@ public class CadiWrap extends HttpServletRequestWrapper implements HttpServletRe } public static boolean checkPerm(Access access, String caller, Principal principal, PermConverter pconv, Lur lur, String perm) { - if(principal== null) { + if (principal== null) { access.log(Level.AUDIT,caller, "No Principal in Transaction"); return false; } else { final long start = System.nanoTime(); perm = pconv.convert(perm); - if(lur.fish(principal,lur.createPerm(perm))) { + if (lur.fish(principal,lur.createPerm(perm))) { access.printf(Level.DEBUG,"%s: %s has %s, %f ms", caller, principal.getName(), perm, Timing.millis(start)); return true; } else { @@ -158,7 +158,7 @@ public class CadiWrap extends HttpServletRequestWrapper implements HttpServletRe } public String getUser() { - if(user==null && principal!=null) { + if (user==null && principal!=null) { user = principal.getName(); } return user; @@ -183,9 +183,9 @@ public class CadiWrap extends HttpServletRequestWrapper implements HttpServletRe // Add a feature public void invalidate(String id) { - if(lur instanceof EpiLur) { + if (lur instanceof EpiLur) { ((EpiLur)lur).remove(id); - } else if(lur instanceof CachingLur) { + } else if (lur instanceof CachingLur) { ((CachingLur<?>)lur).remove(id); } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java index 5ca1ce30..f3a2a7fa 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Capacitor.java @@ -46,7 +46,7 @@ public class Capacitor { public void put(byte b) { - if(curr == null || curr.remaining()==0) { // ensure we have a "curr" buffer ready for data + if (curr == null || curr.remaining()==0) { // ensure we have a "curr" buffer ready for data curr = ringGet(); bbs.add(curr); } @@ -54,10 +54,10 @@ public class Capacitor { } public int read() { - if(curr!=null) { - if(curr.remaining()>0) { // have a buffer, use it! + if (curr!=null) { + if (curr.remaining()>0) { // have a buffer, use it! return curr.get(); - } else if(idx<bbs.size()){ // Buffer not enough, get next one from array + } else if (idx<bbs.size()){ // Buffer not enough, get next one from array curr=bbs.get(idx++); return curr.get(); } @@ -74,11 +74,11 @@ public class Capacitor { * @return */ public int read(byte[] array, int offset, int length) { - if(curr==null)return -1; + if (curr==null)return -1; int len; int count=0; - while(length>0) { // loop through while there's data needed - if((len=curr.remaining())>length) { // if enough data in curr buffer, use this code + while (length>0) { // loop through while there's data needed + if ((len=curr.remaining())>length) { // if enough data in curr buffer, use this code curr.get(array,offset,length); count+=length; length=0; @@ -87,7 +87,7 @@ public class Capacitor { count+=len; offset+=len; length-=len; - if(idx<bbs.size()) { + if (idx<bbs.size()) { curr=bbs.get(idx++); } else { length=0; // stop, and return the count of how many we were able to load @@ -105,14 +105,14 @@ public class Capacitor { * @param length */ public void put(byte[] array, int offset, int length) { - if(curr == null || curr.remaining()==0) { + if (curr == null || curr.remaining()==0) { curr = ringGet(); bbs.add(curr); } int len; - while(length>0) { - if((len=curr.remaining())>length) { + while (length>0) { + if ((len=curr.remaining())>length) { curr.put(array,offset,length); length=0; } else { @@ -130,10 +130,10 @@ public class Capacitor { * Move state from Storage mode into Read mode, changing all internal buffers to read mode, etc */ public void setForRead() { - for(ByteBuffer bb : bbs) { + for (ByteBuffer bb : bbs) { bb.flip(); } - if(bbs.isEmpty()) { + if (bbs.isEmpty()) { curr = null; idx = 0; } else { @@ -146,7 +146,7 @@ public class Capacitor { * reuse all the buffers */ public void done() { - for(ByteBuffer bb : bbs) { + for (ByteBuffer bb : bbs) { ringPut(bb); } bbs.clear(); @@ -160,7 +160,7 @@ public class Capacitor { */ public int available() { int count = 0; - for(ByteBuffer bb : bbs) { + for (ByteBuffer bb : bbs) { count+=bb.remaining(); } return count; @@ -174,11 +174,11 @@ public class Capacitor { public long skip(long n) { long skipped=0L; int skip; - if(curr==null) { + if (curr==null) { return 0; } - while(n>0) { - if(n<(skip=curr.remaining())) { + while (n>0) { + if (n<(skip=curr.remaining())) { curr.position(curr.position()+(int)n); skipped+=skip; n=0; @@ -186,7 +186,7 @@ public class Capacitor { curr.position(curr.limit()); skipped-=skip; - if(idx<bbs.size()) { + if (idx<bbs.size()) { curr=bbs.get(idx++); n-=skip; } else { @@ -201,10 +201,10 @@ public class Capacitor { * in a standalone mode. */ public void reset() { - for(ByteBuffer bb : bbs) { + for (ByteBuffer bb : bbs) { bb.position(0); } - if(bbs.isEmpty()) { + if (bbs.isEmpty()) { curr = null; idx = 0; } else { @@ -221,9 +221,9 @@ public class Capacitor { synchronized(ring) { bb=ring[start]; ring[start]=null; - if(bb!=null && ++start>15)start=0; + if (bb!=null && ++start>15)start=0; } - if(bb==null) { + if (bb==null) { bb=ByteBuffer.allocate(DEFAULT_CHUNK); } else { bb.clear();// refresh reused buffer @@ -234,7 +234,7 @@ public class Capacitor { private void ringPut(ByteBuffer bb) { synchronized(ring) { ring[end]=bb; // if null or not, BB will just be Garbage collected - if(++end>15)end=0; + if (++end>15)end=0; } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java b/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java index 7ca9fac2..68a8db05 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/CmdLine.java @@ -48,18 +48,18 @@ public class CmdLine { * @param args */ public static void main(String[] args) { - if(args.length>0) { - if("digest".equalsIgnoreCase(args[0]) && (args.length>2 || (args.length>1 && System.console()!=null))) { + if (args.length>0) { + if ("digest".equalsIgnoreCase(args[0]) && (args.length>2 || (args.length>1 && System.console()!=null))) { String keyfile; String password; - if(args.length>2) { + if (args.length>2) { password = args[1]; keyfile = args[2]; - if("-i".equals(password)) { + if ("-i".equals(password)) { int c; StringBuilder sb = new StringBuilder(); try { - while((c=System.in.read())>=0) { + while ((c=System.in.read())>=0) { sb.append((char)c); } } catch (IOException e) { @@ -86,7 +86,7 @@ public class CmdLine { return; /* testing code... don't want it exposed System.out.println(" ******** Testing *********"); - for(int i=0;i<100000;++i) { + for (int i=0;i<100000;++i) { System.out.println(args[1]); ByteArrayOutputStream baos = new ByteArrayOutputStream(); b64.enpass(args[1], baos); @@ -96,7 +96,7 @@ public class CmdLine { b64.depass(pass, reconstituted); String r = reconstituted.toString(); System.out.println(r); - if(!r.equals(args[1])) { + if (!r.equals(args[1])) { System.err.println("!!!!! STOP - ERROR !!!!!"); return; } @@ -113,7 +113,7 @@ public class CmdLine { // Jonathan. Oh, well, Deployment services need this behavior. I will put this code in, but leave it undocumented. // One still needs access to the keyfile to read. // July 2016 - thought of a tool "CMPass" to regurgitate from properties, but only if allowed. - } else if("regurgitate".equalsIgnoreCase(args[0]) && args.length>2) { + } else if ("regurgitate".equalsIgnoreCase(args[0]) && args.length>2) { try { Symm symm; FileInputStream fis = new FileInputStream(args[2]); @@ -123,10 +123,10 @@ public class CmdLine { fis.close(); } boolean isFile = false; - if("-i".equals(args[1]) || (isFile="-f".equals(args[1]))) { + if ("-i".equals(args[1]) || (isFile="-f".equals(args[1]))) { BufferedReader br; - if(isFile) { - if(args.length<4) { + if (isFile) { + if (args.length<4) { System.err.println("Filename in 4th position"); return; } @@ -139,10 +139,10 @@ public class CmdLine { boolean cont = false; StringBuffer sb = new StringBuffer(); JsonOutputStream jw = new JsonOutputStream(System.out); - while((line=br.readLine())!=null) { - if(cont) { + while ((line=br.readLine())!=null) { + if (cont) { int end; - if((end=line.indexOf('"'))>=0) { + if ((end=line.indexOf('"'))>=0) { sb.append(line,0,end); cont=false; } else { @@ -150,34 +150,34 @@ public class CmdLine { } } else { int idx; - if((idx = line.indexOf(' '))>=0 + if ((idx = line.indexOf(' '))>=0 && (idx = line.indexOf(' ',++idx))>0 && (idx = line.indexOf('=',++idx))>0 ) { System.out.println(line.substring(0, idx-5)); int start = idx+2; int end; - if((end=line.indexOf('"',start))<0) { + if ((end=line.indexOf('"',start))<0) { end = line.length(); cont = true; } sb.append(line,start,end); } } - if(sb.length()>0) { + if (sb.length()>0) { symm.depass(sb.toString(),jw); - if(!cont) { + if (!cont) { System.out.println(); } } System.out.flush(); sb.setLength(0); - if(!cont) { + if (!cont) { jw.resetIndent(); } } } finally { - if(isFile) { + if (isFile) { br.close(); } } @@ -191,7 +191,7 @@ public class CmdLine { System.err.println("Cannot regurgitate password"); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("encode64".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("encode64".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64.encode(args[1], System.out); System.out.println(); @@ -201,7 +201,7 @@ public class CmdLine { System.err.println("Cannot encode Base64 with " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("decode64".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("decode64".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64.decode(args[1], System.out); System.out.println(); @@ -211,7 +211,7 @@ public class CmdLine { System.err.println("Cannot decode Base64 text from " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("encode64url".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("encode64url".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64url.encode(args[1], System.out); System.out.println(); @@ -221,7 +221,7 @@ public class CmdLine { System.err.println("Cannot encode Base64url with " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("decode64url".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("decode64url".equalsIgnoreCase(args[0]) && args.length>1) { try { Symm.base64url.decode(args[1], System.out); System.out.println(); @@ -231,7 +231,7 @@ public class CmdLine { System.err.println("Cannot decode Base64url text from " + args[1]); System.err.println(" \""+ e.getMessage() + '"'); } - } else if("md5".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("md5".equalsIgnoreCase(args[0]) && args.length>1) { try { System.out.println(Hash.hashMD5asStringHex(args[1])); System.out.flush(); @@ -240,11 +240,11 @@ public class CmdLine { System.err.println(" \""+ e.getMessage() + '"'); } return; - } else if("sha256".equalsIgnoreCase(args[0]) && args.length>1) { + } else if ("sha256".equalsIgnoreCase(args[0]) && args.length>1) { try { - if(args.length>2) { + if (args.length>2) { int max = args.length>7?7:args.length; - for(int i=2;i<max;++i) { + for (int i=2;i<max;++i) { int salt = Integer.parseInt(args[i]); System.out.println(Hash.hashSHA256asStringHex(args[1],salt)); } @@ -257,9 +257,9 @@ public class CmdLine { } System.out.flush(); return; - } else if("keygen".equalsIgnoreCase(args[0])) { + } else if ("keygen".equalsIgnoreCase(args[0])) { try { - if(args.length>1) { + if (args.length>1) { File f = new File(args[1]); FileOutputStream fos = new FileOutputStream(f); try { @@ -280,13 +280,13 @@ public class CmdLine { System.err.println(" \""+ e.getMessage() + '"'); } - } else if("passgen".equalsIgnoreCase(args[0])) { + } else if ("passgen".equalsIgnoreCase(args[0])) { int numDigits; - if(args.length <= 1) { + if (args.length <= 1) { numDigits = 24; } else { numDigits = Integer.parseInt(args[1]); - if(numDigits<8)numDigits = 8; + if (numDigits<8)numDigits = 8; } String pass; boolean noLower,noUpper,noDigits,noSpecial,repeatingChars,missingChars; @@ -295,33 +295,33 @@ public class CmdLine { missingChars=noLower=noUpper=noDigits=noSpecial=true; repeatingChars=false; int c=-1,last; - for(int i=0;i<numDigits;++i) { + for (int i=0;i<numDigits;++i) { last = c; c = pass.charAt(i); - if(c==last) { + if (c==last) { repeatingChars=true; break; } - if(noLower) { + if (noLower) { noLower=!(c>=0x61 && c<=0x7A); } - if(noUpper) { + if (noUpper) { noUpper=!(c>=0x41 && c<=0x5A); } - if(noDigits) { + if (noDigits) { noDigits=!(c>=0x30 && c<=0x39); } - if(noSpecial) { + if (noSpecial) { noSpecial = "+!@#$%^&*(){}[]?:;,.".indexOf(c)<0; } missingChars = (noLower || noUpper || noDigits || noSpecial); } - } while(missingChars || repeatingChars); + } while (missingChars || repeatingChars); System.out.println(pass.substring(0,numDigits)); - } else if("urlgen".equalsIgnoreCase(args[0])) { + } else if ("urlgen".equalsIgnoreCase(args[0])) { int numDigits; - if(args.length <= 1) { + if (args.length <= 1) { numDigits = 24; } else { numDigits = Integer.parseInt(args[1]); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java index acd45019..3027fd74 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Hash.java @@ -132,9 +132,9 @@ public class Hash { * @return */ public static boolean isEqual(byte ba1[], byte ba2[]) { - if(ba1.length!=ba2.length)return false; - for(int i = 0;i<ba1.length; ++i) { - if(ba1[i]!=ba2[i])return false; + if (ba1.length!=ba2.length)return false; + for (int i = 0;i<ba1.length; ++i) { + if (ba1[i]!=ba2[i])return false; } return true; } @@ -142,10 +142,10 @@ public class Hash { public static int compareTo(byte[] a, byte[] b) { int end = Math.min(a.length, b.length); int compare = 0; - for(int i=0;compare == 0 && i<end;++i) { + for (int i=0;compare == 0 && i<end;++i) { compare = a[i]-b[i]; } - if(compare==0)compare=a.length-b.length; + if (compare==0)compare=a.length-b.length; return compare; } @@ -178,7 +178,7 @@ public class Hash { public static byte[] fromHex(String s) throws CadiException{ - if(!s.startsWith("0x")) { + if (!s.startsWith("0x")) { throw new CadiException("HexString must start with \"0x\""); } boolean high = true; @@ -186,19 +186,19 @@ public class Hash { byte b; byte[] ba = new byte[(s.length()-2)/2]; int idx; - for(int i=2;i<s.length();++i) { + for (int i=2;i<s.length();++i) { c = s.charAt(i); - if(c>=0x30 && c<=0x39) { + if (c>=0x30 && c<=0x39) { b=(byte)(c-0x30); - } else if(c>=0x61 && c<=0x66) { + } else if (c>=0x61 && c<=0x66) { b=(byte)(c-0x57); // account for "A" - } else if(c>=0x41 && c<=0x46) { + } else if (c>=0x41 && c<=0x46) { b=(byte)(c-0x37); } else { throw new CadiException("Invalid char '" + c + "' in HexString"); } idx = (i-2)/2; - if(high) { + if (high) { ba[idx]=(byte)(b<<4); high = false; } else { @@ -222,7 +222,7 @@ public class Hash { byte[] ba; boolean high; int start; - if(s.length()%2==0) { + if (s.length()%2==0) { ba = new byte[s.length()/2]; high=true; start=0; @@ -232,19 +232,19 @@ public class Hash { start=1; } int idx; - for(int i=start;i<s.length();++i) { + for (int i=start;i<s.length();++i) { c = s.charAt((i-start)); - if(c>=0x30 && c<=0x39) { + if (c>=0x30 && c<=0x39) { b=(byte)(c-0x30); - } else if(c>=0x61 && c<=0x66) { + } else if (c>=0x61 && c<=0x66) { b=(byte)(c-0x57); // account for "A" - } else if(c>=0x41 && c<=0x46) { + } else if (c>=0x41 && c<=0x46) { b=(byte)(c-0x37); } else { return null; } idx = i/2; - if(high) { + if (high) { ba[idx]=(byte)(b<<4); high = false; } else { diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java b/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java index a35777f8..8467c7c6 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/PropAccess.java @@ -89,8 +89,8 @@ public class PropAccess implements Access { this.logIt = logIt; Properties nprops=new Properties(); int eq; - for(String arg : args) { - if((eq=arg.indexOf('='))>0) { + for (String arg : args) { + if ((eq=arg.indexOf('='))>0) { nprops.setProperty(arg.substring(0, eq),arg.substring(eq+1)); } } @@ -104,16 +104,16 @@ public class PropAccess implements Access { props = new Properties(); // First, load related System Properties - for(Entry<Object,Object> es : System.getProperties().entrySet()) { + for (Entry<Object,Object> es : System.getProperties().entrySet()) { String key = es.getKey().toString(); - for(String start : new String[] {"cadi_","aaf_","cm_"}) { - if(key.startsWith(start)) { + for (String start : new String[] {"cadi_","aaf_","cm_"}) { + if (key.startsWith(start)) { props.put(key, es.getValue()); } } } // Second, overlay or fill in with Passed in Props - if(p!=null) { + if (p!=null) { props.putAll(p); } @@ -121,11 +121,11 @@ public class PropAccess implements Access { load(props.getProperty(Config.CADI_PROP_FILES)); String sLevel = props.getProperty(Config.CADI_LOGLEVEL); - if(sLevel!=null) { + if (sLevel!=null) { level=Level.valueOf(sLevel).maskOf(); } // Setup local Symmetrical key encryption - if(symm==null) { + if (symm==null) { try { symm = Symm.obtain(this); } catch (CadiException e) { @@ -142,18 +142,18 @@ public class PropAccess implements Access { private void specialConversions() { // Critical - if no Security Protocols set, then set it. We'll just get messed up if not - if(props.get(Config.CADI_PROTOCOLS)==null) { + if (props.get(Config.CADI_PROTOCOLS)==null) { props.setProperty(Config.CADI_PROTOCOLS, SecurityInfo.HTTPS_PROTOCOLS_DEFAULT); } Object temp; temp=props.get(Config.CADI_PROTOCOLS); - if(props.get(Config.HTTPS_PROTOCOLS)==null && temp!=null) { + if (props.get(Config.HTTPS_PROTOCOLS)==null && temp!=null) { props.put(Config.HTTPS_PROTOCOLS, temp); } - if(temp!=null) { - if("1.7".equals(System.getProperty("java.specification.version")) + if (temp!=null) { + if ("1.7".equals(System.getProperty("java.specification.version")) && (temp==null || (temp instanceof String && ((String)temp).contains("TLSv1.2")))) { System.setProperty(Config.HTTPS_CIPHER_SUITES, Config.HTTPS_CIPHER_SUITES_DEFAULT); } @@ -161,20 +161,20 @@ public class PropAccess implements Access { } private void load(String cadi_prop_files) { - if(cadi_prop_files==null) { + if (cadi_prop_files==null) { return; } String prevKeyFile = props.getProperty(Config.CADI_KEYFILE); int prev = 0, end = cadi_prop_files.length(); int idx; String filename; - while(prev<end) { + while (prev<end) { idx = cadi_prop_files.indexOf(File.pathSeparatorChar,prev); - if(idx<0) { + if (idx<0) { idx = end; } File file = new File(filename=cadi_prop_files.substring(prev,idx)); - if(file.exists()) { + if (file.exists()) { printf(Level.INIT,"Loading CADI Properties from %s",file.getAbsolutePath()); try { FileInputStream fis = new FileInputStream(file); @@ -182,12 +182,12 @@ public class PropAccess implements Access { props.load(fis); // Recursively Load String chainProp = props.getProperty(Config.CADI_PROP_FILES); - if(chainProp!=null) { - if(recursionProtection==null) { + if (chainProp!=null) { + if (recursionProtection==null) { recursionProtection = new ArrayList<>(); recursionProtection.add(cadi_prop_files); } - if(!recursionProtection.contains(chainProp)) { + if (!recursionProtection.contains(chainProp)) { recursionProtection.add(chainProp); load(chainProp); // recurse } @@ -205,23 +205,23 @@ public class PropAccess implements Access { } // Trim - for(Entry<Object, Object> es : props.entrySet()) { + for (Entry<Object, Object> es : props.entrySet()) { Object value = es.getValue(); - if(value instanceof String) { + if (value instanceof String) { String trim = ((String)value).trim(); // Remove Beginning/End Quotes, which might be there if mixed with Bash Props int s = 0, e=trim.length()-1; - if(s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') { + if (s<e && trim.charAt(s)=='"' && trim.charAt(e)=='"') { trim=trim.substring(s+1,e); } - if(trim!=value) { // Yes, I want OBJECT equals + if (trim!=value) { // Yes, I want OBJECT equals props.setProperty((String)es.getKey(), trim); } } } // Reset Symm if Keyfile Changes: String newKeyFile = props.getProperty(Config.CADI_KEYFILE); - if((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) { + if ((prevKeyFile!=null && newKeyFile!=null) || (newKeyFile!=null && !newKeyFile.equals(prevKeyFile))) { try { symm = Symm.obtain(this); } catch (CadiException e) { @@ -234,7 +234,7 @@ public class PropAccess implements Access { } String loglevel = props.getProperty(Config.CADI_LOGLEVEL); - if(loglevel!=null) { + if (loglevel!=null) { try { level=Level.valueOf(loglevel).maskOf(); } catch (IllegalArgumentException e) { @@ -253,7 +253,7 @@ public class PropAccess implements Access { @Override public void log(Level level, Object ... elements) { - if(willLog(level)) { + if (willLog(level)) { logIt.push(level,elements); } } @@ -270,11 +270,11 @@ public class PropAccess implements Access { sb.append(name); int end = elements.length; - if(end<=0) { + if (end<=0) { sb.append("] "); } else { int idx = 0; - if(elements[idx] instanceof Integer) { + if (elements[idx] instanceof Integer) { sb.append('-'); sb.append(elements[idx]); ++idx; @@ -282,14 +282,14 @@ public class PropAccess implements Access { sb.append("] "); String s; boolean first = true; - for(Object o : elements) { - if(o!=null) { + for (Object o : elements) { + if (o!=null) { s=o.toString(); - if(first) { + if (first) { first = false; } else { int l = s.length(); - if(l>0) { + if (l>0) { switch(s.charAt(l-1)) { case ' ': break; @@ -313,7 +313,7 @@ public class PropAccess implements Access { @Override public void printf(Level level, String fmt, Object... elements) { - if(willLog(level)) { + if (willLog(level)) { log(level,String.format(fmt, elements)); } } @@ -362,9 +362,9 @@ public class PropAccess implements Access { } public void setProperty(String tag, String value) { - if(value!=null) { + if (value!=null) { props.put(tag, value); - if(Config.CADI_KEYFILE.equals(tag)) { + if (Config.CADI_KEYFILE.equals(tag)) { // reset decryption too try { symm = Symm.obtain(this); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java b/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java index 518ea6dd..998b87c9 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/ServletContextAccess.java @@ -34,7 +34,7 @@ public class ServletContextAccess extends PropAccess { super(filterConfig); // protected constructor... does not have "init" called. context = filterConfig.getServletContext(); - for(Enumeration<?> en = filterConfig.getInitParameterNames();en.hasMoreElements();) { + for (Enumeration<?> en = filterConfig.getInitParameterNames();en.hasMoreElements();) { String name = (String)en.nextElement(); setProperty(name, filterConfig.getInitParameter(name)); } @@ -46,7 +46,7 @@ public class ServletContextAccess extends PropAccess { */ @Override public void log(Level level, Object... elements) { - if(willLog(level)) { + if (willLog(level)) { StringBuilder sb = buildMsg(level, elements); context.log(sb.toString()); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java b/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java index fd60b0c1..28af03cd 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/Symm.java @@ -139,12 +139,12 @@ public class Symm { // data (i.e. abcde...). Therefore, we'll quickly analyze the keyset. If it proves to have // too much entropy, the "Unordered" algorithm, which is faster in such cases is used. ArrayList<int[]> la = new ArrayList<>(); - for(int i=0;i<codeset.length;++i) { + for (int i=0;i<codeset.length;++i) { curr = codeset[i]; - if(prev+1==curr) { // is next character in set + if (prev+1==curr) { // is next character in set prev = curr; } else { - if(offset!=Integer.SIZE) { // add previous range + if (offset!=Integer.SIZE) { // add previous range la.add(new int[]{first,prev,offset}); } first = prev = curr; @@ -152,7 +152,7 @@ public class Symm { } } la.add(new int[]{first,curr,offset}); - if(la.size()>codeset.length/3) { + if (la.size()>codeset.length/3) { convert = new Unordered(codeset); } else { // too random to get speed enhancement from range algorithm int[][] range = new int[la.size()][]; @@ -210,10 +210,10 @@ public class Symm { public <T> T exec(SyncExec<T> exec) throws Exception { synchronized(LOCK) { - if(keyBytes == null) { + if (keyBytes == null) { keyBytes = new byte[AES.AES_KEY_SIZE/8]; int offset = (Math.abs(codeset[0])+47)%(codeset.length-keyBytes.length); - for(int i=0;i<keyBytes.length;++i) { + for (int i=0;i<keyBytes.length;++i) { keyBytes[i] = (byte)codeset[i+offset]; } } @@ -231,7 +231,7 @@ public class Symm { } public byte[] encode(byte[] toEncrypt) throws IOException { - if(toEncrypt==null) { + if (toEncrypt==null) { return EMPTY; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream((int)(toEncrypt.length*1.25)); @@ -344,8 +344,8 @@ public class Symm { boolean go; do { read = is.read(); - if(go = read>=0) { - if(line>=splitLinesAt) { + if (go = read>=0) { + if (line>=splitLinesAt) { os.write('\n'); line = 0; } @@ -362,7 +362,7 @@ public class Symm { // Char 1 is last 4 bits of prev plus the first 2 bits of read // Char 2 is the last 6 bits of read os.write(codeset[(((prev & 0xF)<<2) | (read>>6))]); - if(line==splitLinesAt) { // deal with line splitting for two characters + if (line==splitLinesAt) { // deal with line splitting for two characters os.write('\n'); line=0; } @@ -376,21 +376,21 @@ public class Symm { switch(idx) { case 1: // just the last 2 bits of prev os.write(codeset[(prev & 0x03)<<4]); - if(endEquals)os.write(DOUBLE_EQ); + if (endEquals)os.write(DOUBLE_EQ); break; case 2: // just the last 4 bits of prev os.write(codeset[(prev & 0xF)<<2]); - if(endEquals)os.write('='); + if (endEquals)os.write('='); break; } idx = 0; } - } while(go); + } while (go); } public void decode(InputStream is, OutputStream os, int skip) throws IOException { - if(is.skip(skip)!=skip) { + if (is.skip(skip)!=skip) { throw new IOException("Error skipping on IOStream in Symm"); } decode(is,os); @@ -405,9 +405,9 @@ public class Symm { public void decode(InputStream is, OutputStream os) throws IOException { int read, idx=0; int prev=0, index; - while((read = is.read())>=0) { + while ((read = is.read())>=0) { index = convert.convert(read); - if(index>=0) { + if (index>=0) { switch(++idx) { // 1 based cases, slightly faster ++ case 1: // index goes into first 6 bits of prev prev = index<<2; @@ -459,8 +459,8 @@ public class Symm { case '\r': return -1; } - for(int i=0;i<range.length;++i) { - if(read >= range[i][0] && read<=range[i][1]) { + for (int i=0;i<range.length;++i) { + if (read >= range[i][0] && read<=range[i][1]) { return read-range[i][2]; } } @@ -487,8 +487,8 @@ public class Symm { case '\r': return -1; } - for(int i=0;i<codec.length;++i) { - if(codec[i]==read)return i; + for (int i=0;i<codec.length;++i) { + if (codec[i]==read)return i; } // don't give clue in Encryption mode throw new IOException("Unacceptable Character in Stream"); @@ -519,7 +519,7 @@ public class Symm { private Obtain(Symm b64, byte[] key) { skip = Math.abs(key[key.length-13]%key.length); - if((key.length&0x1) == (skip&0x1)) { // if both are odd or both are even + if ((key.length&0x1) == (skip&0x1)) { // if both are odd or both are even ++skip; } length = b64.codeset.length; @@ -542,7 +542,7 @@ public class Symm { */ public static Symm obtain(Access access) throws CadiException { String keyfile = access.getProperty(Config.CADI_KEYFILE,null); - if(keyfile!=null) { + if (keyfile!=null) { Symm symm = Symm.baseCrypt(); File file = new File(keyfile); @@ -551,7 +551,7 @@ public class Symm { } catch (IOException e1) { access.log(Level.INIT, Config.CADI_KEYFILE,"points to",file.getAbsolutePath()); } - if(file.exists()) { + if (file.exists()) { try { FileInputStream fis = new FileInputStream(file); try { @@ -619,7 +619,7 @@ public class Symm { throw new IOException("Invalid Key"); } byte[] bkey = baos.toByteArray(); - if(bkey.length<0x88) { // 2048 bit key + if (bkey.length<0x88) { // 2048 bit key throw new IOException("Invalid key"); } return baseCrypt().obtain(bkey); @@ -663,37 +663,37 @@ public class Symm { * @throws IOException */ public void enpass(final String password, final OutputStream os) throws IOException { - if(password==null) { + if (password==null) { throw new IOException("Invalid password passed"); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); byte[] bytes = password.getBytes(); - if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization + if (this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization dos.write(bytes); } else { Random r = new SecureRandom(); int start = 0; byte b; - for(int i=0;i<3;++i) { + for (int i=0;i<3;++i) { dos.writeByte(b=(byte)r.nextInt()); start+=Math.abs(b); } start%=0x7; - for(int i=0;i<start;++i) { + for (int i=0;i<start;++i) { dos.writeByte(r.nextInt()); } dos.writeInt((int)System.currentTimeMillis()); int minlength = Math.min(0x9,bytes.length); dos.writeByte(minlength); // expect truncation - if(bytes.length<0x9) { - for(int i=0;i<bytes.length;++i) { + if (bytes.length<0x9) { + for (int i=0;i<bytes.length;++i) { dos.writeByte(r.nextInt()); dos.writeByte(bytes[i]); } // make sure it's long enough - for(int i=bytes.length;i<0x9;++i) { + for (int i=bytes.length;i<0x9;++i) { dos.writeByte(r.nextInt()); } } else { @@ -733,7 +733,7 @@ public class Symm { * @throws IOException */ public String depass(String password) throws IOException { - if(password==null)return null; + if (password==null)return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); depass(password,baos); return new String(baos.toByteArray()); @@ -772,23 +772,23 @@ public class Symm { byte[] bytes = baos.toByteArray(); DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes)); long time; - if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization + if (this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization os.write(bytes); time = 0L; } else { int start=0; - for(int i=0;i<3;++i) { + for (int i=0;i<3;++i) { start+=Math.abs(dis.readByte()); } start%=0x7; - for(int i=0;i<start;++i) { + for (int i=0;i<start;++i) { dis.readByte(); } time = (dis.readInt() & 0xFFFF)|(System.currentTimeMillis()&0xFFFF0000); int minlength = dis.readByte(); - if(minlength<0x9){ + if (minlength<0x9){ DataOutputStream dos = new DataOutputStream(os); - for(int i=0;i<minlength;++i) { + for (int i=0;i<minlength;++i) { dis.readByte(); dos.writeByte(dis.readByte()); } @@ -807,7 +807,7 @@ public class Symm { public static String randomGen(char[] chars ,int numBytes) { int rint; StringBuilder sb = new StringBuilder(numBytes); - for(int i=0;i<numBytes;++i) { + for (int i=0;i<numBytes;++i) { rint = random.nextInt(chars.length); sb.append(chars[rint]); } @@ -829,14 +829,14 @@ public class Symm { int index; Obtain o = new Obtain(this,key); - while(filled>=0) { + while (filled>=0) { index = o.next(); - if(index<0 || index>=codeset.length) { + if (index<0 || index>=codeset.length) { System.out.println("uh, oh"); } - if(right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something) - for(int j=index;j<end;++j) { - if(seq[j]==0) { + if (right) { // alternate going left or right to find the next open slot (keeps it from taking too long to hit something) + for (int j=index;j<end;++j) { + if (seq[j]==0) { seq[j]=codeset[filled]; --filled; break; @@ -844,8 +844,8 @@ public class Symm { } right = false; } else { - for(int j=index;j>=0;--j) { - if(seq[j]==0) { + for (int j=index;j>=0;--j) { + if (seq[j]==0) { seq[j]=codeset[filled]; --filled; break; @@ -859,7 +859,7 @@ public class Symm { try { newSymm.keyBytes = new byte[AES.AES_KEY_SIZE/8]; int offset = (Math.abs(key[(47%key.length)])+137)%(key.length-newSymm.keyBytes.length); - for(int i=0;i<newSymm.keyBytes.length;++i) { + for (int i=0;i<newSymm.keyBytes.length;++i) { newSymm.keyBytes[i] = key[i+offset]; } } catch (Exception e) { @@ -876,7 +876,7 @@ public class Symm { * @throws IOException */ public static synchronized Symm internalOnly() throws IOException { - if(internalOnly==null) { + if (internalOnly==null) { ByteArrayInputStream baos = new ByteArrayInputStream(keygen()); try { internalOnly = Symm.obtain(baos); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/User.java b/cadi/core/src/main/java/org/onap/aaf/cadi/User.java index 512f2e6a..4848e504 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/User.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/User.java @@ -125,7 +125,7 @@ public final class User<PERM extends Permission> { } public void add(LocalPermission permission) { - if(perms==NULL_MAP) { + if (perms==NULL_MAP) { perms=newMap(); } perms.put(permission.getKey(),permission); @@ -157,8 +157,8 @@ public final class User<PERM extends Permission> { sb.append('|'); boolean first = true; synchronized(perms) { - for(Permission gp : perms.values()) { - if(first) { + for (Permission gp : perms.values()) { + if (first) { first = false; sb.append(':'); } else { diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java index 4784d1ee..088227ed 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Config.java @@ -233,9 +233,9 @@ public class Config { ///////////////////////////////////////////////////// Class<?> aafConClass = loadClass(access,CADI_AAF_CON_DEF); Object aafcon = null; - if(con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) { + if (con!=null && aafConClass!=null && aafConClass.isAssignableFrom(con.getClass())) { aafcon = con; - } else if(lur != null) { + } else if (lur != null) { Field f; try { f = lur.getClass().getField("aaf"); @@ -248,14 +248,14 @@ public class Config { boolean hasDirectAAF = hasDirect("DirectAAFLur",additionalTafLurs); // IMPORTANT! Don't attempt to load AAF Connector if there is no AAF URL String aafURL = access.getProperty(AAF_URL,null); - if(!hasDirectAAF && aafcon==null && aafURL!=null) { + if (!hasDirectAAF && aafcon==null && aafURL!=null) { aafcon = loadAAFConnector(si, aafURL); } HttpTaf taf; // Setup Host, in case Network reports an unusable Hostname (i.e. VTiers, VPNs, etc) String hostname = logProp(access, HOSTNAME,null); - if(hostname==null) { + if (hostname==null) { try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e1) { @@ -279,10 +279,10 @@ public class Config { ///////////////////////////////////////////////////// X509Taf x509TAF = null; String truststore = logProp(access, CADI_TRUSTSTORE,null); - if(truststore!=null) { + if (truststore!=null) { String truststorePwd = access.getProperty(CADI_TRUSTSTORE_PASSWORD,null); - if(truststorePwd!=null) { - if(truststorePwd.startsWith(Symm.ENC)) { + if (truststorePwd!=null) { + if (truststorePwd.startsWith(Symm.ENC)) { try { access.decrypt(truststorePwd,false); } catch (IOException e) { @@ -314,17 +314,17 @@ public class Config { long userExp = Long.parseLong(aafCleanup); boolean basicWarn = "TRUE".equals(access.getProperty(BASIC_WARN,"FALSE")); - if(!hasDirectAAF) { + if (!hasDirectAAF) { HttpTaf aaftaf=null; - if(!hasOAuthDirectTAF) { - if(basicRealm!=null) { + if (!hasOAuthDirectTAF) { + if (basicRealm!=null) { @SuppressWarnings("unchecked") Class<HttpTaf> obasicCls = (Class<HttpTaf>)loadClass(access,CADI_OBASIC_HTTP_TAF_DEF); - if(obasicCls!=null) { + if (obasicCls!=null) { try { String tokenurl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL, null); String introspecturl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL, null); - if(tokenurl==null || introspecturl==null) { + if (tokenurl==null || introspecturl==null) { access.log(Level.INIT,"Both tokenurl and introspecturl are required. Oauth Authorization is disabled."); } Constructor<HttpTaf> obasicConst = obasicCls.getConstructor(PropAccess.class,String.class, String.class, String.class); @@ -333,20 +333,20 @@ public class Config { } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { access.log(Level.INIT, e); } - } else if(up!=null) { + } else if (up!=null) { access.log(Level.INIT,"Basic Authorization is enabled using realm",basicRealm); // Allow warning about insecure channel to be turned off - if(!basicWarn) { + if (!basicWarn) { access.log(Level.INIT, "WARNING! The basicWarn property has been set to false.", " There will be no additional warning if Basic Auth is used on an insecure channel"); } BasicHttpTaf bht = new BasicHttpTaf(access, up, basicRealm, userExp, basicWarn); - for(Object o : additionalTafLurs) { - if(o instanceof CredValDomain) { + for (Object o : additionalTafLurs) { + if (o instanceof CredValDomain) { bht.add((CredValDomain)o); } } - if(x509TAF!=null) { + if (x509TAF!=null) { x509TAF.add(bht); } htlist.add(bht); @@ -359,28 +359,28 @@ public class Config { ///////////////////////////////////////////////////// // Configure AAF Driven Basic Auth ///////////////////////////////////////////////////// - if(aafcon==null) { + if (aafcon==null) { access.log(Level.INIT,"AAF Connection (AAFcon) is null. Cannot create an AAF TAF"); - } else if(aafURL==null) { + } else if (aafURL==null) { access.log(Level.INIT,"No AAF URL in properties, Cannot create an AAF TAF"); } else {// There's an AAF_URL... try to configure an AAF String aafTafClassName = logProp(access, AAF_TAF_CLASS,AAF_TAF_CLASS_DEF); // Only 2.0 available at this time - if(AAF_TAF_CLASS_DEF.equals(aafTafClassName)) { + if (AAF_TAF_CLASS_DEF.equals(aafTafClassName)) { try { Class<?> aafTafClass = loadClass(access,aafTafClassName); - if(aafTafClass!=null) { + if (aafTafClass!=null) { Constructor<?> cstr = aafTafClass.getConstructor(Connector.class,boolean.class,AbsUserCache.class); - if(cstr!=null) { - if(lur instanceof AbsUserCache) { + if (cstr!=null) { + if (lur instanceof AbsUserCache) { aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn,lur); } else { cstr = aafTafClass.getConstructor(Connector.class,boolean.class); - if(cstr!=null) { + if (cstr!=null) { aaftaf = (HttpTaf)cstr.newInstance(aafcon,basicWarn); } } - if(aaftaf==null) { + if (aaftaf==null) { access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured"); } else { access.log(Level.INIT,"AAF TAF Configured to ",aafURL); @@ -390,7 +390,7 @@ public class Config { } else { access.log(Level.INIT, "There is no AAF TAF class available: %s. AAF TAF not configured.",aafTafClassName); } - } catch(Exception e) { + } catch (Exception e) { access.log(Level.INIT,"ERROR! AAF TAF Failed construction. NOT Configured",e); } } @@ -400,7 +400,7 @@ public class Config { ///////////////////////////////////////////////////// // Configure OAuth TAF ///////////////////////////////////////////////////// - if(!hasOAuthDirectTAF) { + if (!hasOAuthDirectTAF) { String oauthTokenUrl = logProp(access,Config.AAF_OAUTH2_TOKEN_URL,null); Class<?> oadtClss; try { @@ -409,21 +409,21 @@ public class Config { oadtClss = null; access.log(Level.INIT, e1); } - if(additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) { + if (additionalTafLurs!=null && additionalTafLurs.length>0 && (oadtClss!=null && additionalTafLurs[0].getClass().isAssignableFrom(oadtClss))) { htlist.add((HttpTaf)additionalTafLurs[0]); String[] array= new String[additionalTafLurs.length-1]; - if(array.length>0) { + if (array.length>0) { System.arraycopy(htlist, 1, array, 0, array.length); } additionalTafLurs = array; access.log(Level.INIT,"OAuth2 Direct is enabled"); - } else if(oauthTokenUrl!=null) { + } else if (oauthTokenUrl!=null) { String oauthIntrospectUrl = logProp(access,Config.AAF_OAUTH2_INTROSPECT_URL,null); @SuppressWarnings("unchecked") Class<HttpTaf> oaTCls = (Class<HttpTaf>)loadClass(access,OAUTH_HTTP_TAF); - if(oaTCls!=null) { + if (oaTCls!=null) { Class<?> oaTTmgrCls = loadClass(access, OAUTH_TOKEN_MGR); - if(oaTTmgrCls!=null) { + if (oaTTmgrCls!=null) { try { Method oaTTmgrGI = oaTTmgrCls.getMethod("getInstance",PropAccess.class,String.class,String.class); Object oaTTmgr = oaTTmgrGI.invoke(null /*this is static method*/,access,oauthTokenUrl,oauthIntrospectUrl); @@ -444,7 +444,7 @@ public class Config { // Adding BasicAuth (AAF) last, after other primary Cookie Based // Needs to be before Cert... see below ///////////////////////////////////////////////////// - if(aaftaf!=null) { + if (aaftaf!=null) { htlist.add(aaftaf); } } @@ -452,22 +452,22 @@ public class Config { ///////////////////////////////////////////////////// // Any Additional Lurs passed in Constructor ///////////////////////////////////////////////////// - if(additionalTafLurs!=null) { - for(Object additional : additionalTafLurs) { - if(additional instanceof BasicHttpTaf) { + if (additionalTafLurs!=null) { + for (Object additional : additionalTafLurs) { + if (additional instanceof BasicHttpTaf) { BasicHttpTaf ht = (BasicHttpTaf)additional; - for(Object cv : additionalTafLurs) { - if(cv instanceof CredValDomain) { + for (Object cv : additionalTafLurs) { + if (cv instanceof CredValDomain) { ht.add((CredValDomain)cv); access.printf(Level.INIT,"%s Authentication is enabled",cv); } } htlist.add(ht); - } else if(additional instanceof HttpTaf) { + } else if (additional instanceof HttpTaf) { HttpTaf ht = (HttpTaf)additional; htlist.add(ht); access.printf(Level.INIT,"%s Authentication is enabled",additional.getClass().getSimpleName()); - } else if(hasOAuthDirectTAF) { + } else if (hasOAuthDirectTAF) { Class<?> daupCls; try { daupCls = Class.forName("org.onap.aaf.auth.direct.DirectAAFUserPass"); @@ -475,7 +475,7 @@ public class Config { daupCls = null; access.log(Level.INIT, e); } - if(daupCls != null && additional.getClass().isAssignableFrom(daupCls)) { + if (daupCls != null && additional.getClass().isAssignableFrom(daupCls)) { htlist.add(new BasicHttpTaf(access, (CredVal)additional , basicRealm, userExp, basicWarn)); access.printf(Level.INIT,"Direct BasicAuth Authentication is enabled",additional.getClass().getSimpleName()); } @@ -484,9 +484,9 @@ public class Config { } // Add BasicAuth, if any, to x509Taf - if(x509TAF!=null) { - for( HttpTaf ht : htlist) { - if(ht instanceof BasicHttpTaf) { + if (x509TAF!=null) { + for ( HttpTaf ht : htlist) { + if (ht instanceof BasicHttpTaf) { x509TAF.add((BasicHttpTaf)ht); } } @@ -494,7 +494,7 @@ public class Config { ///////////////////////////////////////////////////// // Create EpiTaf from configured TAFs ///////////////////////////////////////////////////// - if(htlist.size()==1) { + if (htlist.size()==1) { // just return the one taf = htlist.get(0); } else { @@ -504,7 +504,7 @@ public class Config { taf = new HttpEpiTaf(access,locator, tc, htarray); // ok to pass locator == null String level = logProp(access, CADI_LOGLEVEL, null); - if(level!=null) { + if (level!=null) { access.setLogLevel(Level.valueOf(level)); } } @@ -514,7 +514,7 @@ public class Config { public static String logProp(Access access,String tag, String def) { String rv = access.getProperty(tag, def); - if(rv == null) { + if (rv == null) { access.log(Level.INIT,tag,"is not explicitly set"); } else { access.log(Level.INIT,tag,"is set to",rv); @@ -533,14 +533,14 @@ public class Config { String users = access.getProperty(USERS,null); String groups = access.getProperty(GROUPS,null); - if(groups!=null || users!=null) { + if (groups!=null || users!=null) { LocalLur ll = new LocalLur(access, users, groups); // note b64==null is ok.. just means no encryption. lurs.add(ll); String writeto = access.getProperty(WRITE_TO,null); - if(writeto!=null) { + if (writeto!=null) { String msg = UsersDump.updateUsers(writeto, ll); - if(msg!=null) { + if (msg!=null) { access.log(Level.INIT,"ERROR! Error Updating ",writeto,"with roles and users:",msg); } } @@ -554,10 +554,10 @@ public class Config { ///////////////////////////////////////////////////// String tokenUrl = logProp(access,AAF_OAUTH2_TOKEN_URL, null); String introspectUrl = logProp(access,AAF_OAUTH2_INTROSPECT_URL, null); - if(tokenUrl!=null && introspectUrl !=null) { + if (tokenUrl!=null && introspectUrl !=null) { try { Class<?> olurCls = loadClass(access, CADI_OLUR_CLASS_DEF); - if(olurCls!=null) { + if (olurCls!=null) { Constructor<?> olurCnst = olurCls.getConstructor(PropAccess.class,String.class,String.class); Lur olur = (Lur)olurCnst.newInstance(access,tokenUrl,introspectUrl); lurs.add(olur); @@ -567,7 +567,7 @@ public class Config { } } catch (NoSuchMethodException| SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { String msg = e.getMessage(); - if(msg==null && e.getCause()!=null) { + if (msg==null && e.getCause()!=null) { msg = e.getCause().getMessage(); } access.log(Level.INIT,"AAF/OAuth LUR is not instantiated.",msg,e); @@ -576,7 +576,7 @@ public class Config { access.log(Level.INIT, "OAuth2 Lur disabled"); } - if(con!=null) { // try to reutilize connector + if (con!=null) { // try to reutilize connector lurs.add(con.newLur()); } else { ///////////////////////////////////////////////////// @@ -584,12 +584,12 @@ public class Config { ///////////////////////////////////////////////////// String aafURL = logProp(access,AAF_URL,null); // Trigger Property String aafEnv = access.getProperty(AAF_ENV,null); - if(aafEnv == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL + if (aafEnv == null && aafURL!=null && access instanceof PropAccess) { // set AAF_ENV from AAF_URL int ec = aafURL.indexOf("envContext="); - if(ec>0) { + if (ec>0) { ec += 11; // length of envContext= int slash = aafURL.indexOf('/', ec); - if(slash>0) { + if (slash>0) { aafEnv = aafURL.substring(ec, slash); ((PropAccess)access).setProperty(AAF_ENV, aafEnv); access.printf(Level.INIT, "Setting aafEnv to %s from aaf_url value",aafEnv); @@ -598,30 +598,30 @@ public class Config { } // Don't configure AAF if it is using DirectAccess - if(!hasDirect("DirectAAFLur",additionalTafLurs)) { - if(aafURL==null) { + if (!hasDirect("DirectAAFLur",additionalTafLurs)) { + if (aafURL==null) { access.log(Level.INIT,"No AAF LUR properties, AAF will not be loaded"); } else {// There's an AAF_URL... try to configure an AAF String aafLurClassStr = logProp(access,AAF_LUR_CLASS,AAF_V2_0_AAF_LUR_PERM); ////////////AAF Lur 2.0 ///////////// - if(aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { + if (aafLurClassStr!=null && aafLurClassStr.startsWith(AAF_V2_0)) { try { Object aafcon = loadAAFConnector(si, aafURL); - if(aafcon==null) { + if (aafcon==null) { access.log(Level.INIT,"AAF LUR class,",aafLurClassStr,"cannot be constructed without valid AAFCon object."); } else { Class<?> aafAbsAAFCon = loadClass(access, AAF_V2_0_AAFCON); - if(aafAbsAAFCon!=null) { + if (aafAbsAAFCon!=null) { Method mNewLur = aafAbsAAFCon.getMethod("newLur"); Object aaflur = mNewLur.invoke(aafcon); - if(aaflur==null) { + if (aaflur==null) { access.log(Level.INIT,"ERROR! AAF LUR Failed construction. NOT Configured"); } else { access.log(Level.INIT,"AAF LUR Configured to ",aafURL); lurs.add((Lur)aaflur); String debugIDs = logProp(access,Config.AAF_DEBUG_IDS, null); - if(debugIDs !=null && aaflur instanceof CachingLur) { + if (debugIDs !=null && aaflur instanceof CachingLur) { ((CachingLur<?>)aaflur).setDebug(debugIDs); } } @@ -638,9 +638,9 @@ public class Config { ///////////////////////////////////////////////////// // Any Additional passed in Constructor ///////////////////////////////////////////////////// - if(additionalTafLurs!=null) { - for(Object additional : additionalTafLurs) { - if(additional instanceof Lur) { + if (additionalTafLurs!=null) { + for (Object additional : additionalTafLurs) { + if (additional instanceof Lur) { lurs.add((Lur)additional); access.log(Level.INIT, additional); } @@ -666,9 +666,9 @@ public class Config { } private static boolean hasDirect(String simpleClassName, Object[] additionalTafLurs) { - if(additionalTafLurs!=null) { - for(Object tf : additionalTafLurs) { - if(tf.getClass().getSimpleName().equals(simpleClassName)) { + if (additionalTafLurs!=null) { + for (Object tf : additionalTafLurs) { + if (tf.getClass().getSimpleName().equals(simpleClassName)) { return true; } } @@ -746,15 +746,15 @@ public class Config { public static Locator<URI> loadLocator(SecurityInfoC<HttpURLConnection> si, final String _url) throws LocatorException { Access access = si.access; Locator<URI> locator = null; - if(_url==null) { + if (_url==null) { access.log(Level.INIT,"No URL passed to 'loadLocator'. Disabled"); } else { String url = _url; String replacement; int idxAAFLocateUrl; - if((idxAAFLocateUrl=_url.indexOf(AAF_LOCATE_URL_TAG))>0 && ((replacement=access.getProperty(AAF_LOCATE_URL, null))!=null)) { + if ((idxAAFLocateUrl=_url.indexOf(AAF_LOCATE_URL_TAG))>0 && ((replacement=access.getProperty(AAF_LOCATE_URL, null))!=null)) { StringBuilder sb = new StringBuilder(replacement); - if(!replacement.endsWith("/locate")) { + if (!replacement.endsWith("/locate")) { sb.append("/locate"); } sb.append(_url,idxAAFLocateUrl+AAF_LOCATE_URL_TAG.length(),_url.length()); @@ -763,7 +763,7 @@ public class Config { try { Class<?> lcls = loadClass(access,AAF_LOCATOR_CLASS_DEF); - if(lcls==null) { + if (lcls==null) { throw new CadiException("Need to include aaf-cadi-aaf jar for AAFLocator"); } // First check for preloaded @@ -773,7 +773,7 @@ public class Config { } catch (Exception e) { access.log(Level.INIT, e); } - if(locator==null) { + if (locator==null) { URI locatorURI = new URI(url); Constructor<?> cnst = lcls.getConstructor(SecurityInfoC.class,URI.class); locator = (Locator<URI>)cnst.newInstance(new Object[] {si,locatorURI}); @@ -785,7 +785,7 @@ public class Config { access.log(Level.INFO, "AAFLocator enabled using preloaded " + locator.getClass().getSimpleName()); } } catch (InvocationTargetException e) { - if(e.getTargetException() instanceof LocatorException) { + if (e.getTargetException() instanceof LocatorException) { throw (LocatorException)e.getTargetException(); } access.log(Level.INIT,e.getTargetException().getMessage(),"AAFLocator for",url,"could not be created.",e); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java index 56ac4dd5..b48dd74d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/Get.java @@ -59,7 +59,7 @@ public interface Get { } // Take def if nothing else - if(str==null) { + if (str==null) { str = def; // don't log defaults } else { @@ -83,8 +83,8 @@ public interface Get { } public String get(String name, String def, boolean print) { String gotten = access.getProperty(name, def); - if(print) { - if(gotten == null) { + if (print) { + if (gotten == null) { access.log(Level.INIT,name, "is not set"); } else { access.log(Level.INIT,name, "is set to", gotten); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java index 4655dfa1..30adcc97 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/GetAccess.java @@ -38,7 +38,7 @@ public class GetAccess extends PropAccess { public String getProperty(String tag, String def) { String rv; rv = super.getProperty(tag, null); - if(rv==null && getter!=null) { + if (rv==null && getter!=null) { rv = getter.get(tag, null, true); } return rv==null?def:rv; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java index a73df14e..c5e5a50e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/MultiGet.java @@ -31,9 +31,9 @@ public class MultiGet implements Get { @Override public String get(String name, String def, boolean print) { String str; - for(Get getter : getters) { + for (Get getter : getters) { str = getter.get(name, null, print); - if(str!=null) + if (str!=null) return str; } return def; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java index 45e1dd1c..4e365fba 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfoC.java @@ -44,7 +44,7 @@ public class SecurityInfoC<CLIENT> extends SecurityInfo { @SuppressWarnings("unchecked") public static synchronized <CLIENT> SecurityInfoC<CLIENT> instance(Access access, Class<CLIENT> cls) throws CadiException { SecurityInfoInit<CLIENT> sii; - if(cls.isAssignableFrom(HttpURLConnection.class)) { + if (cls.isAssignableFrom(HttpURLConnection.class)) { try { @SuppressWarnings("rawtypes") Class<SecurityInfoInit> initCls = (Class<SecurityInfoInit>)Class.forName("org.onap.aaf.cadi.http.HSecurityInfoInit"); @@ -62,7 +62,7 @@ public class SecurityInfoC<CLIENT> extends SecurityInfo { } SecurityInfoC<CLIENT> sic = (SecurityInfoC<CLIENT>) sicMap.get(cls); - if(sic==null) { + if (sic==null) { sic = new SecurityInfoC<CLIENT>(access); sic.set(sii.bestDefault(sic)); sicMap.put(cls, sic); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java index de25cb7f..98ab4706 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/UsersDump.java @@ -41,7 +41,7 @@ public class UsersDump { */ public static boolean write(OutputStream os, AbsUserCache<?> lur) { PrintStream ps; - if(os instanceof PrintStream) { + if (os instanceof PrintStream) { ps = (PrintStream)os; } else { ps = new PrintStream(os); @@ -59,14 +59,14 @@ public class UsersDump { // Obtain all unique role names HashSet<String> groups = new HashSet<>(); - for(AbsUserCache<?>.DumpInfo di : lur.dumpInfo()) { + for (AbsUserCache<?>.DumpInfo di : lur.dumpInfo()) { sb.append("\n <user username=\""); sb.append(di.user); sb.append("\" roles=\""); boolean first = true; - for(String role : di.perms) { + for (String role : di.perms) { groups.add(role); - if(first)first = false; + if (first)first = false; else sb.append(','); sb.append(role); } @@ -75,7 +75,7 @@ public class UsersDump { } // Print roles - for(String group : groups) { + for (String group : groups) { ps.print(" <role rolename=\""); ps.print(group); ps.println("\"/>"); @@ -104,15 +104,15 @@ public class UsersDump { */ public static String updateUsers(String writeto, LocalLur up) { // Dump a Tomcat-user.xml lookalike (anywhere) - if(writeto!=null) { + if (writeto!=null) { // First read content ByteArrayOutputStream baos = new ByteArrayOutputStream(); - if(UsersDump.write(baos, up)) { + if (UsersDump.write(baos, up)) { byte[] postulate = baos.toByteArray(); // now get contents of file File file = new File(writeto); boolean writeIt; - if(file.exists()) { + if (file.exists()) { try { FileInputStream fis = new FileInputStream(file); byte[] orig = new byte[(int)file.length()]; @@ -122,17 +122,17 @@ public class UsersDump { } finally { fis.close(); } - if(read<=0) { + if (read<=0) { writeIt = false; } else { // Starting at third "<" (<tomcat-users> line) int startA=0, startB=0; - for(int i=0;startA<orig.length && i<3;++startA) if(orig[startA]=='<')++i; - for(int i=0;startB<orig.length && i<3;++startB) if(postulate[startB]=='<')++i; + for (int i=0;startA<orig.length && i<3;++startA) if (orig[startA]=='<')++i; + for (int i=0;startB<orig.length && i<3;++startB) if (postulate[startB]=='<')++i; writeIt=orig.length-startA!=postulate.length-startB; // first, check if remaining length is the same - while(!writeIt && startA<orig.length && startB<postulate.length) { - if(orig[startA++]!=postulate[startB++])writeIt = true; + while (!writeIt && startA<orig.length && startB<postulate.length) { + if (orig[startA++]!=postulate[startB++])writeIt = true; } } } catch (Exception e) { @@ -142,7 +142,7 @@ public class UsersDump { writeIt = true; } - if(writeIt) { + if (writeIt) { try { FileOutputStream fos = new FileOutputStream(file); try { diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java index affb8f96..cd48556b 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiFilter.java @@ -113,7 +113,7 @@ public class CadiFilter implements Filter { public CadiFilter(boolean init, PropAccess access, Object ... moreTafLurs) throws ServletException { this.access = access; additionalTafLurs = moreTafLurs; - if(init) { + if (init) { init(new AccessGetter(access)); } } @@ -129,7 +129,7 @@ public class CadiFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { // need the Context for Logging, instantiating ClassLoader, etc ServletContextAccess sca=new ServletContextAccess(filterConfig); - if(access==null) { + if (access==null) { access = sca; } @@ -144,9 +144,9 @@ public class CadiFilter implements Filter { TrustChecker tc = TrustChecker.NOTRUST; // default position try { Class<TrustChecker> ctc = (Class<TrustChecker>) Class.forName("org.onap.aaf.cadi.aaf.v2_0.AAFTrustChecker"); - if(ctc!=null) { + if (ctc!=null) { Constructor<TrustChecker> contc = ctc.getConstructor(Access.class); - if(contc!=null) { + if (contc!=null) { tc = contc.newInstance(access); } } @@ -184,8 +184,8 @@ public class CadiFilter implements Filter { // In this case, the epiTaf will be changed to a non-NullTaf, and thus not instantiate twice. synchronized(CadiHTTPManip.noAdditional /*will always remain same Object*/) { ++count; - if(httpChecker == null) { - if(access==null) { + if (httpChecker == null) { + if (access==null) { access = new PropAccess(); } try { @@ -193,16 +193,16 @@ public class CadiFilter implements Filter { } catch (CadiException | LocatorException e1) { throw new ServletException(e1); } - } else if(access==null) { + } else if (access==null) { access= httpChecker.getAccess(); } /* * Setup Authn Path Exceptions */ - if(pathExceptions==null) { + if (pathExceptions==null) { String str = getter.get(Config.CADI_NOAUTHN, null, true); - if(str!=null) { + if (str!=null) { pathExceptions = str.split("\\s*:\\s*"); } } @@ -210,22 +210,22 @@ public class CadiFilter implements Filter { /* * SETUP Permission Converters... those that can take Strings from a Vendor Product, and convert to appropriate AAF Permissions */ - if(mapPairs==null) { + if (mapPairs==null) { String str = getter.get(Config.AAF_PERM_MAP, null, true); - if(str!=null) { + if (str!=null) { String mstr = getter.get(Config.AAF_PERM_MAP, null, true); - if(mstr!=null) { + if (mstr!=null) { String map[] = mstr.split("\\s*:\\s*"); - if(map.length>0) { + if (map.length>0) { MapPermConverter mpc=null; int idx; mapPairs = new ArrayList<>(); - for(String entry : map) { - if((idx=entry.indexOf('='))<0) { // it's a Path, so create a new converter + for (String entry : map) { + if ((idx=entry.indexOf('='))<0) { // it's a Path, so create a new converter access.log(Level.INIT,"Loading Perm Conversions for:",entry); mapPairs.add(new Pair(entry,mpc=new MapPermConverter())); } else { - if(mpc!=null) { + if (mpc!=null) { mpc.map().put(entry.substring(0,idx),entry.substring(idx+1)); } else { access.log(Level.ERROR,"cadi_perm_map is malformed; ",entry, "is skipped"); @@ -248,7 +248,7 @@ public class CadiFilter implements Filter { public void destroy() { // Synchronize, in case multiCadiFilters are used. synchronized(CadiHTTPManip.noAdditional) { - if(--count<=0 && httpChecker!=null) { + if (--count<=0 && httpChecker!=null) { httpChecker.destroy(); httpChecker=null; access=null; @@ -272,7 +272,7 @@ public class CadiFilter implements Filter { String tag = ""; try { HttpServletRequest hreq = (HttpServletRequest)request; - if(noAuthn(hreq)) { + if (noAuthn(hreq)) { startCode=System.nanoTime(); chain.doFilter(request, response); code = Timing.millis(startCode); @@ -281,11 +281,11 @@ public class CadiFilter implements Filter { startValidate=System.nanoTime(); TafResp tresp = httpChecker.validate(hreq, hresp, hreq); validate = Timing.millis(startValidate); - if(tresp.isAuthenticated()==RESP.IS_AUTHENTICATED) { + if (tresp.isAuthenticated()==RESP.IS_AUTHENTICATED) { user = tresp.getPrincipal().personalName(); tag = tresp.getPrincipal().tag(); CadiWrap cw = new CadiWrap(hreq, tresp, httpChecker.getLur(),getConverter(hreq)); - if(httpChecker.notCadi(cw, hresp)) { + if (httpChecker.notCadi(cw, hresp)) { startCode=System.nanoTime(); oauthFilter.doFilter(cw,response,chain); code = Timing.millis(startCode); @@ -308,11 +308,11 @@ public class CadiFilter implements Filter { * @return */ private boolean noAuthn(HttpServletRequest hreq) { - if(pathExceptions!=null) { + if (pathExceptions!=null) { String pi = hreq.getPathInfo(); - if(pi==null) return false; // JBoss sometimes leaves null - for(String pe : pathExceptions) { - if(pi.startsWith(pe))return true; + if (pi==null) return false; // JBoss sometimes leaves null + for (String pe : pathExceptions) { + if (pi.startsWith(pe))return true; } } return false; @@ -322,11 +322,11 @@ public class CadiFilter implements Filter { * Get Converter by Path */ private PermConverter getConverter(HttpServletRequest hreq) { - if(mapPairs!=null) { + if (mapPairs!=null) { String pi = hreq.getPathInfo(); - if(pi !=null) { - for(Pair p: mapPairs) { - if(pi.startsWith(p.name))return p.pc; + if (pi !=null) { + for (Pair p: mapPairs) { + if (pi.startsWith(p.name))return p.pc; } } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java index 3c0f139b..bab758ec 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiHTTPManip.java @@ -78,18 +78,18 @@ public class CadiHTTPManip { Config.setDefaultRealm(access); aaf_id = access.getProperty(Config.CADI_ALIAS,access.getProperty(Config.AAF_APPID, null)); - if(aaf_id==null) { + if (aaf_id==null) { access.printf(Level.INIT, "%s is not set. %s can be used instead",Config.AAF_APPID,Config.CADI_ALIAS); } else { access.printf(Level.INIT, "%s is set to %s",Config.AAF_APPID,aaf_id); } String ns = aaf_id==null?null:UserChainManip.idToNS(aaf_id); - if(ns!=null) { + if (ns!=null) { thisPerm = ns+ACCESS_CADI_CONTROL; int dot = ns.indexOf('.'); - if(dot>=0) { + if (dot>=0) { int dot2=ns.indexOf('.',dot+1); - if(dot2<0) { + if (dot2<0) { dot2=dot; } companyPerm = ns.substring(0, dot2)+ACCESS_CADI_CONTROL; @@ -105,9 +105,9 @@ public class CadiHTTPManip { lur = Config.configLur(si, con, additionalTafLurs); tc.setLur(lur); - if(lur instanceof EpiLur) { + if (lur instanceof EpiLur) { up = ((EpiLur)lur).getUserPassImpl(); - } else if(lur instanceof CredVal) { + } else if (lur instanceof CredVal) { up = (CredVal)lur; } else { up = null; @@ -160,20 +160,20 @@ public class CadiHTTPManip { public boolean notCadi(CadiWrap req, HttpServletResponse resp) { String pathInfo = req.getPathInfo(); - if(METH.equalsIgnoreCase(req.getMethod()) && pathInfo!=null && pathInfo.contains(CADI)) { - if(req.getUser().equals(aaf_id) || req.isUserInRole(thisPerm) || req.isUserInRole(companyPerm)) { + if (METH.equalsIgnoreCase(req.getMethod()) && pathInfo!=null && pathInfo.contains(CADI)) { + if (req.getUser().equals(aaf_id) || req.isUserInRole(thisPerm) || req.isUserInRole(companyPerm)) { try { - if(pathInfo.contains(CADI_CACHE_PRINT)) { + if (pathInfo.contains(CADI_CACHE_PRINT)) { resp.getOutputStream().println(lur.toString()); resp.setStatus(200); return false; - } else if(pathInfo.contains(CADI_CACHE_CLEAR)) { + } else if (pathInfo.contains(CADI_CACHE_CLEAR)) { StringBuilder report = new StringBuilder(); lur.clear(req.getUserPrincipal(), report); resp.getOutputStream().println(report.toString()); resp.setStatus(200); return false; - } else if(pathInfo.contains(CADI_LOG_SET)) { + } else if (pathInfo.contains(CADI_LOG_SET)) { Level l; int slash = pathInfo.lastIndexOf('/'); String level = pathInfo.substring(slash+1); @@ -200,7 +200,7 @@ public class CadiHTTPManip { public void destroy() { access.log(Level.INFO,"CadiHttpChecker destroyed."); - if(lur!=null) { + if (lur!=null) { lur.destroy(); lur=null; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java index f56cbf27..cf7c922d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/FCGet.java @@ -49,25 +49,25 @@ class FCGet implements Get { public String get(String name, String def, boolean print) { String str = null; // Try Server Context First - if(context!=null) { + if (context!=null) { str = context.getInitParameter(name); } // Try Filter Context next - if(str==null && filterConfig != null) { + if (str==null && filterConfig != null) { str = filterConfig.getInitParameter(name); } - if(str==null) { + if (str==null) { str = access.getProperty(name, def); } // Take def if nothing else - if(str==null) { + if (str==null) { str = def; // don't log defaults } else { str = str.trim(); // this is vital in Property File based values, as spaces can hide easily - if(print) { + if (print) { access.log(Level.INFO,"Setting", name, "to", str); } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java index c1b477b1..a41c5eb7 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/ConfigPrincipal.java @@ -57,10 +57,10 @@ public class ConfigPrincipal implements Principal, GetCred { } public String getAsBasicAuthHeader() throws IOException { - if(content ==null) { + if (content ==null) { String s = name + ':' + new String(cred); content = "Basic " + Symm.base64.encode(s); - } else if(!content.startsWith("Basic ")) { // content is the saved password from construction + } else if (!content.startsWith("Basic ")) { // content is the saved password from construction String s = name + ':' + content; content = "Basic " + Symm.base64.encode(s); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java index 2c5e1957..5443dec2 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/EpiLur.java @@ -57,30 +57,30 @@ public final class EpiLur implements Lur { */ public EpiLur(Lur ... lurs) throws CadiException{ this.lurs = lurs; - if(lurs.length==0) throw new CadiException("Need at least one Lur implementation in constructor"); + if (lurs.length==0) throw new CadiException("Need at least one Lur implementation in constructor"); } public boolean fish(Principal bait, Permission ... pond) { - if(pond==null) { + if (pond==null) { return false; } boolean rv = false; Lur lur; - for(int i=0;!rv && i<lurs.length;++i) { + for (int i=0;!rv && i<lurs.length;++i) { rv = (lur = lurs[i]).fish(bait, pond); - if(!rv && lur.handlesExclusively(pond)) break; + if (!rv && lur.handlesExclusively(pond)) break; } return rv; } public void fishAll(Principal bait, List<Permission> permissions) { - for(Lur lur : lurs) { + for (Lur lur : lurs) { lur.fishAll(bait, permissions); } } public void destroy() { - for(Lur lur : lurs) { + for (Lur lur : lurs) { lur.destroy(); } } @@ -90,8 +90,8 @@ public final class EpiLur implements Lur { * @return */ public CredVal getUserPassImpl() { - for(Lur lur : lurs) { - if(lur instanceof CredVal) { + for (Lur lur : lurs) { + if (lur instanceof CredVal) { return (CredVal)lur; } } @@ -109,15 +109,15 @@ public final class EpiLur implements Lur { * @return */ public Lur get(int idx) { - if(idx>=0 && idx<lurs.length) { + if (idx>=0 && idx<lurs.length) { return lurs[idx]; } return null; } public boolean handles(Principal p) { - for(Lur l : lurs) { - if(l.handles(p)) { + for (Lur l : lurs) { + if (l.handles(p)) { return true; } } @@ -125,16 +125,16 @@ public final class EpiLur implements Lur { } public void remove(String id) { - for(Lur l : lurs) { - if(l instanceof CachingLur) { + for (Lur l : lurs) { + if (l instanceof CachingLur) { ((CachingLur<?>)l).remove(id); } } } public Lur subLur(Class<? extends Lur> cls ) { - for(Lur l : lurs) { - if(l.getClass().isAssignableFrom(cls)) { + for (Lur l : lurs) { + if (l.getClass().isAssignableFrom(cls)) { return l; } } @@ -151,14 +151,14 @@ public final class EpiLur implements Lur { */ @Override public void clear(Principal p, StringBuilder report) { - for(Lur lur : lurs) { + for (Lur lur : lurs) { lur.clear(p, report); } } public String toString() { StringBuilder sb = new StringBuilder(); - for(Lur lur : lurs) { + for (Lur lur : lurs) { sb.append(lur.getClass().getSimpleName()); sb.append(": Report\n"); sb.append(lur.toString()); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java index d2b6f1aa..f8fa02e5 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/lur/LocalLur.java @@ -98,7 +98,7 @@ public final class LocalLur extends AbsUserCache<LocalPermission> implements Lur if (pond == null) { return false; } - for(Permission p : pond) { + for (Permission p : pond) { if (handles(bait) && p instanceof LocalPermission) { // local Users only have LocalPermissions User<LocalPermission> user = getUser(bait); if (user != null) { @@ -134,7 +134,7 @@ public final class LocalLur extends AbsUserCache<LocalPermission> implements Lur public boolean handlesExclusively(Permission ... pond) { boolean rv = false; for (Permission p : pond) { - if(rv=supportingGroups.contains(p.getKey())) { + if (rv=supportingGroups.contains(p.getKey())) { break; } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java index d3c1e236..746e67d8 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/BasicPrincipal.java @@ -45,8 +45,8 @@ public class BasicPrincipal extends BearerPrincipal implements GetCred { created = System.currentTimeMillis(); ByteArrayInputStream bis = new ByteArrayInputStream(content.getBytes()); // Read past "Basic ", ensuring it starts with it. - for(int i=0;i<basic.length;++i) { - if(bis.read()!=basic[i]) { + for (int i=0;i<basic.length;++i) { + if (bis.read()!=basic[i]) { name=content; cred = null; return; @@ -54,10 +54,10 @@ public class BasicPrincipal extends BearerPrincipal implements GetCred { } BasicOS bos = new BasicOS(content.length()); Symm.base64.decode(bis,bos); // note: writes directly to name until ':' - if(name==null) throw new IOException("Invalid Coding"); + if (name==null) throw new IOException("Invalid Coding"); else cred = bos.toCred(); int at; - if((at=name.indexOf('@'))>0) { + if ((at=name.indexOf('@'))>0) { domain=name.substring(at+1); shortName=name.substring(0, at); } else { @@ -83,7 +83,7 @@ public class BasicPrincipal extends BearerPrincipal implements GetCred { @Override public void write(int b) throws IOException { - if(b==':' && first) { + if (b==':' && first) { first = false; name = new String(baos.toByteArray()); baos.reset(); // diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java index f81e160d..4a6e4cda 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/CachedBasicPrincipal.java @@ -54,7 +54,7 @@ public class CachedBasicPrincipal extends BasicPrincipal implements CachedPrinci public CachedPrincipal.Resp revalidate(Object state) { Resp resp = creator.revalidate(this, state); - if(resp.equals(Resp.REVALIDATED))expires = System.currentTimeMillis()+timeToLive; + if (resp.equals(Resp.REVALIDATED))expires = System.currentTimeMillis()+timeToLive; return resp; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java index 8c75701f..20f22846 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/Kind.java @@ -33,19 +33,19 @@ public class Kind { public static char getKind(final Principal principal) { Principal check; - if(principal instanceof TrustPrincipal) { + if (principal instanceof TrustPrincipal) { check = ((TrustPrincipal)principal).original(); } else { check = principal; } - if(check instanceof X509Principal) { + if (check instanceof X509Principal) { return X509; } - if(check instanceof OAuth2FormPrincipal) { + if (check instanceof OAuth2FormPrincipal) { // Note: if AAF, will turn into 'A' return OAUTH; } - if(check instanceof BasicPrincipal) { + if (check instanceof BasicPrincipal) { return BASIC_AUTH; } return UNKNOWN; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java index 4d13de87..01326054 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/OAuth2FormPrincipal.java @@ -49,7 +49,7 @@ public class OAuth2FormPrincipal extends TaggedPrincipal { @Override public String personalName() { - if(username!=null && username!=client_id) { + if (username!=null && username!=client_id) { StringBuilder sb = new StringBuilder(); sb.append(username); sb.append('|'); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java index 9dddcd63..7bb4ff52 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TaggedPrincipal.java @@ -47,7 +47,7 @@ public abstract class TaggedPrincipal implements Principal { } public String personalName() { - if(tagLookup == null) { + if (tagLookup == null) { return getName(); } try { diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java index 5d4a0586..7e92aaca 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/TrustPrincipal.java @@ -33,10 +33,10 @@ public class TrustPrincipal extends BearerPrincipal implements UserChain { public TrustPrincipal(final Principal actual, final String asName) { this.original = actual; name = asName.trim(); - if(actual instanceof UserChain) { + if (actual instanceof UserChain) { UserChain uc = (UserChain)actual; userChain = uc.userChain(); - } else if(actual instanceof TaggedPrincipal) { + } else if (actual instanceof TaggedPrincipal) { userChain=((TaggedPrincipal)actual).tag(); } else { userChain = actual.getClass().getSimpleName(); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java index 1cd114a0..0348cd1f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/principal/X509Principal.java @@ -55,17 +55,17 @@ public class X509Principal extends BearerPrincipal implements GetCred { String _name = null; String subj = cert.getSubjectDN().getName(); int cn = subj.indexOf("OU="); - if(cn>=0) { + if (cn>=0) { cn+=3; int space = subj.indexOf(',',cn); - if(space>=0) { + if (space>=0) { String id = subj.substring(cn, space); - if(pattern.matcher(id).matches()) { + if (pattern.matcher(id).matches()) { _name = id; } } } - if(_name==null) { + if (_name==null) { throw new IOException("X509 does not have Identity as CN"); } name = _name; @@ -74,7 +74,7 @@ public class X509Principal extends BearerPrincipal implements GetCred { public String getAsHeader() throws IOException { try { - if(content==null) { + if (content==null) { content=cert.getEncoded(); } } catch (CertificateEncodingException e) { diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java index b248e553..d2cbf3fa 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/EpiTaf.java @@ -47,7 +47,7 @@ public class EpiTaf implements Taf { */ public EpiTaf(Taf ... tafs) throws CadiException{ this.tafs = tafs; - if(tafs.length==0) throw new CadiException("Need at least one Taf implementation in constructor"); + if (tafs.length==0) throw new CadiException("Need at least one Taf implementation in constructor"); } /** @@ -63,13 +63,13 @@ public class EpiTaf implements Taf { */ public TafResp validate(LifeForm reading, String... info) { TafResp tresp,firstTryAuth=null; - for(Taf taf : tafs) { + for (Taf taf : tafs) { tresp = taf.validate(reading, info); switch(tresp.isAuthenticated()) { case TRY_ANOTHER_TAF: break; case TRY_AUTHENTICATING: - if(firstTryAuth==null)firstTryAuth=tresp; + if (firstTryAuth==null)firstTryAuth=tresp; break; default: return tresp; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java index b0f56603..6334164e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/HttpEpiTaf.java @@ -94,7 +94,7 @@ public class HttpEpiTaf implements HttpTaf { TafResp firstTry = null; List<Redirectable> redirectables = null; List<TafResp> log; - if(access.willLog(Level.DEBUG)) { + if (access.willLog(Level.DEBUG)) { log = new ArrayList<>(); } else { log = null; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java index 21830b01..d5f6b032 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/basic/BasicHttpTaf.java @@ -85,23 +85,23 @@ public class BasicHttpTaf implements HttpTaf { */ public TafResp validate(Taf.LifeForm reading, HttpServletRequest req, HttpServletResponse resp) { // See if Request implements BasicCred (aka CadiWrap or other), and if User/Pass has already been set separately - if(req instanceof BasicCred) { + if (req instanceof BasicCred) { BasicCred bc = (BasicCred)req; - if(bc.getUser()!=null) { // CadiWrap, if set, makes sure User & Password are both valid, or both null - if(DenialOfServiceTaf.isDeniedID(bc.getUser())!=null) { + if (bc.getUser()!=null) { // CadiWrap, if set, makes sure User & Password are both valid, or both null + if (DenialOfServiceTaf.isDeniedID(bc.getUser())!=null) { return DenialOfServiceTaf.respDenyID(access,bc.getUser()); } CachedBasicPrincipal bp = new CachedBasicPrincipal(this,bc,realm,timeToLive); // Be able to do Organizational specific lookups by Domain CredVal cv = rbacs.get(bp.getDomain()); - if(cv==null) { + if (cv==null) { cv = rbac; } // ONLY FOR Last Ditch DEBUGGING... // access.log(Level.WARN,bp.getName() + ":" + new String(bp.getCred())); - if(cv.validate(bp.getName(),Type.PASSWORD,bp.getCred(),req)) { + if (cv.validate(bp.getName(),Type.PASSWORD,bp.getCred(),req)) { return new BasicHttpTafResp(access,bp,bp.getName()+" authenticated by password",RESP.IS_AUTHENTICATED,resp,realm,false); } else { //TODO may need timed retries in a given time period @@ -112,25 +112,25 @@ public class BasicHttpTaf implements HttpTaf { } // Get User/Password from Authorization Header value String authz = req.getHeader("Authorization"); - if(authz != null && authz.startsWith("Basic ")) { - if(warn&&!req.isSecure()) { + if (authz != null && authz.startsWith("Basic ")) { + if (warn&&!req.isSecure()) { access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); } try { CachedBasicPrincipal ba = new CachedBasicPrincipal(this,authz,realm,timeToLive); - if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { + if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { return DenialOfServiceTaf.respDenyID(access,ba.getName()); } final int at = ba.getName().indexOf('@'); CredVal cv = rbacs.get(ba.getName().substring(at+1)); - if(cv==null) { + if (cv==null) { cv = rbac; // default } // ONLY FOR Last Ditch DEBUGGING... // access.log(Level.WARN,ba.getName() + ":" + new String(ba.getCred())); - if(cv.validate(ba.getName(), Type.PASSWORD, ba.getCred(), req)) { + if (cv.validate(ba.getName(), Type.PASSWORD, ba.getCred(), req)) { return new BasicHttpTafResp(access,ba, ba.getName()+" authenticated by BasicAuth password",RESP.IS_AUTHENTICATED,resp,realm,false); } else { //TODO may need timed retries in a given time period @@ -148,7 +148,7 @@ public class BasicHttpTaf implements HttpTaf { protected String buildMsg(Principal pr, HttpServletRequest req, Object ... msg) { StringBuilder sb = new StringBuilder(); - if(pr!=null) { + if (pr!=null) { sb.append("user="); sb.append(pr.getName()); sb.append(','); @@ -157,9 +157,9 @@ public class BasicHttpTaf implements HttpTaf { sb.append(req.getRemoteAddr()); sb.append(",port="); sb.append(req.getRemotePort()); - if(msg.length>0) { + if (msg.length>0) { sb.append(",msg=\""); - for(Object s : msg) { + for (Object s : msg) { sb.append(s.toString()); } sb.append('"'); @@ -173,7 +173,7 @@ public class BasicHttpTaf implements HttpTaf { public CredVal getCredVal(String key) { CredVal cv = rbacs.get(key); - if(cv==null) { + if (cv==null) { cv = rbac; } return cv; @@ -181,9 +181,9 @@ public class BasicHttpTaf implements HttpTaf { @Override public Resp revalidate(CachedPrincipal prin, Object state) { - if(prin instanceof BasicPrincipal) { + if (prin instanceof BasicPrincipal) { BasicPrincipal ba = (BasicPrincipal)prin; - if(DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { + if (DenialOfServiceTaf.isDeniedID(ba.getName())!=null) { return Resp.UNVALIDATED; } return rbac.validate(ba.getName(), Type.PASSWORD, ba.getCred(), state)?Resp.REVALIDATED:Resp.UNVALIDATED; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java index d0034c76..0f252e39 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/cert/X509Taf.java @@ -81,18 +81,18 @@ public class X509Taf implements HttpTaf { public X509Taf(Access access, Lur lur, CertIdentity ... cis) throws CertificateException, NoSuchAlgorithmException, CadiException { this.access = access; env = access.getProperty(Config.AAF_ENV,null); - if(env==null) { + if (env==null) { throw new CadiException("X509Taf requires Environment ("+Config.AAF_ENV+") to be set."); } // this.lur = lur; this.cadiIssuers = new ArrayList<>(); - for(String ci : access.getProperty(Config.CADI_X509_ISSUERS, "").split(":")) { + for (String ci : access.getProperty(Config.CADI_X509_ISSUERS, "").split(":")) { access.printf(Level.INIT, "Trusting Identity for Certificates signed by \"%s\"",ci); cadiIssuers.add(ci); } try { Class<?> dci = access.classLoader().loadClass("org.onap.aaf.auth.direct.DirectCertIdentity"); - if(dci==null) { + if (dci==null) { certIdents = cis; } else { CertIdentity temp[] = new CertIdentity[cis.length+1]; @@ -129,28 +129,28 @@ public class X509Taf implements HttpTaf { // Check for Mutual SSL try { X509Certificate[] certarr = (X509Certificate[])req.getAttribute("javax.servlet.request.X509Certificate"); - if(certarr!=null && certarr.length>0) { + if (certarr!=null && certarr.length>0) { si.checkClientTrusted(certarr); // Note: If the Issuer is not in the TrustStore, it's not added to the Cert list String issuer = certarr[0].getIssuerDN().toString(); - if(cadiIssuers.contains(issuer)) { + if (cadiIssuers.contains(issuer)) { String subject = certarr[0].getSubjectDN().getName(); // avoiding extra object creation, since this is validated EVERY transaction with a Cert int at = subject.indexOf('@'); - if(at>=0) { + if (at>=0) { int start = subject.lastIndexOf(',', at); - if(start<0) { + if (start<0) { start = 0; } int end = subject.indexOf(',', at); - if(end<0) { + if (end<0) { end=subject.length(); } int temp; - if(((temp=subject.indexOf("OU=",start))>=0 && temp<end) || + if (((temp=subject.indexOf("OU=",start))>=0 && temp<end) || ((temp=subject.indexOf("CN=",start))>=0 && temp<end)) { String[] sa = Split.splitTrim(':', subject, temp+3,end); - if(sa.length==1 || (sa.length>1 && env!=null && env.equals(sa[1]))) { // Check Environment + if (sa.length==1 || (sa.length>1 && env!=null && env.equals(sa[1]))) { // Check Environment return new X509HttpTafResp(access, new X509Principal(sa[0], certarr[0],(byte[])null,bht), "X509Taf validated " + sa[0] + (sa.length<2?"":" for aaf_env " + env ), RESP.IS_AUTHENTICATED); @@ -168,10 +168,10 @@ public class X509Taf implements HttpTaf { String responseText=null; String authHeader = req.getHeader("Authorization"); - if(certarr!=null) { // If cert !=null, Cert is Tested by Mutual Protocol. - if(authHeader!=null) { // This is only intended to be a Secure Connection, not an Identity - for(String auth : Split.split(',',authHeader)) { - if(auth.startsWith("Bearer ")) { // Bearer = OAuth... Don't use as Authenication + if (certarr!=null) { // If cert !=null, Cert is Tested by Mutual Protocol. + if (authHeader!=null) { // This is only intended to be a Secure Connection, not an Identity + for (String auth : Split.split(',',authHeader)) { + if (auth.startsWith("Bearer ")) { // Bearer = OAuth... Don't use as Authenication return new X509HttpTafResp(access, null, "Certificate verified, but Bearer Token is presented", RESP.TRY_ANOTHER_TAF); } } @@ -179,9 +179,9 @@ public class X509Taf implements HttpTaf { cert = certarr[0]; responseText = ", validated by Mutual SSL Protocol"; } else { // If cert == null, Get Declared Cert (in header), but validate by having them sign something - if(authHeader != null) { - for(String auth : Split.splitTrim(',',authHeader)) { - if(auth.startsWith("x509 ")) { + if (authHeader != null) { + for (String auth : Split.splitTrim(',',authHeader)) { + if (auth.startsWith("x509 ")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(auth.length()); try { array = auth.getBytes(); @@ -197,10 +197,10 @@ public class X509Taf implements HttpTaf { // cert.checkValidity(); // cert.--- GET FINGERPRINT? String stuff = req.getHeader("Signature"); - if(stuff==null) + if (stuff==null) return new X509HttpTafResp(access, null, "Header entry 'Signature' required to validate One way X509 Certificate", RESP.TRY_ANOTHER_TAF); String data = req.getHeader("Data"); - // if(data==null) + // if (data==null) // return new X509HttpTafResp(access, null, "No signed Data to validate with X509 Certificate", RESP.TRY_ANOTHER_TAF); // Note: Data Pos shows is "<signatureType> <data>" @@ -215,7 +215,7 @@ public class X509Taf implements HttpTaf { Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert.getPublicKey()); sig.update(data.getBytes()); - if(!sig.verify(array)) { + if (!sig.verify(array)) { access.log(Level.ERROR, "Signature doesn't Match"); return new X509HttpTafResp(access, null, CERTIFICATE_NOT_VALID_FOR_AUTHENTICATION, RESP.TRY_ANOTHER_TAF); } @@ -227,21 +227,21 @@ public class X509Taf implements HttpTaf { } } } - if(cert==null) { + if (cert==null) { return new X509HttpTafResp(access, null, "No Certificate Info on Transaction", RESP.TRY_ANOTHER_TAF); } // A cert has been found, match Identify TaggedPrincipal prin=null; - for(int i=0;prin==null && i<certIdents.length;++i) { - if((prin=certIdents[i].identity(req, cert, certBytes))!=null) { + for (int i=0;prin==null && i<certIdents.length;++i) { + if ((prin=certIdents[i].identity(req, cert, certBytes))!=null) { responseText = prin.getName() + " matches Certificate " + cert.getSubjectX500Principal().getName() + responseText; } } // if Principal is found, check for "AS_USER" and whether this entity is trusted to declare - if(prin!=null) { + if (prin!=null) { return new X509HttpTafResp( access, prin, @@ -249,7 +249,7 @@ public class X509Taf implements HttpTaf { RESP.IS_AUTHENTICATED); } } - } catch(Exception e) { + } catch (Exception e) { return new X509HttpTafResp(access, null, e.getMessage(), RESP.TRY_ANOTHER_TAF); } @@ -266,7 +266,7 @@ public class X509Taf implements HttpTaf { } public CredVal getCredVal(final String key) { - if(bht==null) { + if (bht==null) { return null; } else { return bht.getCredVal(key); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTaf.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTaf.java index 4154e50e..f083e5aa 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTaf.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/dos/DenialOfServiceTaf.java @@ -62,9 +62,9 @@ public class DenialOfServiceTaf implements HttpTaf { public DenialOfServiceTaf(Access access) throws CadiException { puntNotDenied = new PuntTafResp("DenialOfServiceTaf", "This Transaction is not denied"); this.access = access; - if(dosIP==null || dosID == null) { + if (dosIP==null || dosID == null) { String dirStr; - if((dirStr = access.getProperty(Config.AAF_DATA_DIR, null))!=null) { + if ((dirStr = access.getProperty(Config.AAF_DATA_DIR, null))!=null) { dosIP = new File(dirStr+"/dosIP"); readIP(); dosID = new File(dirStr+"/dosID"); @@ -76,10 +76,10 @@ public class DenialOfServiceTaf implements HttpTaf { @Override public TafResp validate(LifeForm reading, HttpServletRequest req, final HttpServletResponse resp) { // Performance, when not needed - if(deniedIP != null) { + if (deniedIP != null) { String ip; Counter c = deniedIP.get(ip=req.getRemoteAddr()); - if(c!=null) { + if (c!=null) { c.inc(); return respDenyIP(access,ip); } @@ -100,7 +100,7 @@ public class DenialOfServiceTaf implements HttpTaf { * for use in Other TAFs, before they attempt backend validation of */ public static Counter isDeniedID(String identity) { - if(deniedID!=null) { + if (deniedID!=null) { return deniedID.get(identity); } return null; @@ -110,7 +110,7 @@ public class DenialOfServiceTaf implements HttpTaf { * */ public static Counter isDeniedIP(String ipvX) { - if(deniedIP!=null) { + if (deniedIP!=null) { return deniedIP.get(ipvX); } return null; @@ -125,24 +125,24 @@ public class DenialOfServiceTaf implements HttpTaf { */ public static synchronized boolean denyIP(String ip) { boolean rv = false; - if(deniedIP==null) { + if (deniedIP==null) { deniedIP = new HashMap<>(); deniedIP.put(ip, new Counter(ip)); // Noted duplicated for minimum time spent rv= true; - } else if(deniedIP.get(ip)==null) { + } else if (deniedIP.get(ip)==null) { deniedIP.put(ip, new Counter(ip)); rv = true; } - if(rv) { + if (rv) { writeIP(); } return rv; } private static void writeIP() { - if(dosIP!=null && deniedIP!=null) { - if(deniedIP.isEmpty()) { - if(dosIP.exists()) { + if (dosIP!=null && deniedIP!=null) { + if (deniedIP.isEmpty()) { + if (dosIP.exists()) { dosIP.delete(); } } else { @@ -150,7 +150,7 @@ public class DenialOfServiceTaf implements HttpTaf { try { fos = new PrintStream(new FileOutputStream(dosIP,false)); try { - for(String ip: deniedIP.keySet()) { + for (String ip: deniedIP.keySet()) { fos.println(ip); } } finally { @@ -164,17 +164,17 @@ public class DenialOfServiceTaf implements HttpTaf { } private static void readIP() { - if(dosIP!=null && dosIP.exists()) { + if (dosIP!=null && dosIP.exists()) { BufferedReader br; try { br = new BufferedReader(new FileReader(dosIP)); try { - if(deniedIP==null) { + if (deniedIP==null) { deniedIP=new HashMap<>(); } String line; - while((line=br.readLine())!=null) { + while ((line=br.readLine())!=null) { deniedIP.put(line, new Counter(line)); } } finally { @@ -195,9 +195,9 @@ public class DenialOfServiceTaf implements HttpTaf { * @return */ public static synchronized boolean removeDenyIP(String ip) { - if(deniedIP!=null && deniedIP.remove(ip)!=null) { + if (deniedIP!=null && deniedIP.remove(ip)!=null) { writeIP(); - if(deniedIP.isEmpty()) { + if (deniedIP.isEmpty()) { deniedIP=null; } return true; @@ -214,15 +214,15 @@ public class DenialOfServiceTaf implements HttpTaf { */ public static synchronized boolean denyID(String id) { boolean rv = false; - if(deniedID==null) { + if (deniedID==null) { deniedID = new HashMap<>(); deniedID.put(id, new Counter(id)); // Noted duplicated for minimum time spent rv = true; - } else if(deniedID.get(id)==null) { + } else if (deniedID.get(id)==null) { deniedID.put(id, new Counter(id)); rv = true; } - if(rv) { + if (rv) { writeID(); } return rv; @@ -230,9 +230,9 @@ public class DenialOfServiceTaf implements HttpTaf { } private static void writeID() { - if(dosID!=null && deniedID!=null) { - if(deniedID.isEmpty()) { - if(dosID.exists()) { + if (dosID!=null && deniedID!=null) { + if (deniedID.isEmpty()) { + if (dosID.exists()) { dosID.delete(); } } else { @@ -240,7 +240,7 @@ public class DenialOfServiceTaf implements HttpTaf { try { fos = new PrintStream(new FileOutputStream(dosID,false)); try { - for(String ip: deniedID.keySet()) { + for (String ip: deniedID.keySet()) { fos.println(ip); } } finally { @@ -254,17 +254,17 @@ public class DenialOfServiceTaf implements HttpTaf { } private static void readID() { - if(dosID!=null && dosID.exists()) { + if (dosID!=null && dosID.exists()) { BufferedReader br; try { br = new BufferedReader(new FileReader(dosID)); try { - if(deniedID==null) { + if (deniedID==null) { deniedID=new HashMap<>(); } String line; - while((line=br.readLine())!=null) { + while ((line=br.readLine())!=null) { deniedID.put(line, new Counter(line)); } } finally { @@ -284,9 +284,9 @@ public class DenialOfServiceTaf implements HttpTaf { * @return */ public static synchronized boolean removeDenyID(String id) { - if(deniedID!=null && deniedID.remove(id)!=null) { + if (deniedID!=null && deniedID.remove(id)!=null) { writeID(); - if(deniedID.isEmpty()) { + if (deniedID.isEmpty()) { deniedID=null; } @@ -297,16 +297,16 @@ public class DenialOfServiceTaf implements HttpTaf { public List<String> report() { int initSize = 0; - if(deniedIP!=null)initSize+=deniedIP.size(); - if(deniedID!=null)initSize+=deniedID.size(); + if (deniedIP!=null)initSize+=deniedIP.size(); + if (deniedID!=null)initSize+=deniedID.size(); ArrayList<String> al = new ArrayList<>(initSize); - if(deniedID!=null) { - for(Counter c : deniedID.values()) { + if (deniedID!=null) { + for (Counter c : deniedID.values()) { al.add(c.toString()); } } - if(deniedIP!=null) { - for(Counter c : deniedIP.values()) { + if (deniedIP!=null) { + for (Counter c : deniedIP.values()) { al.add(c.toString()); } } @@ -344,13 +344,13 @@ public class DenialOfServiceTaf implements HttpTaf { private synchronized void inc() { ++count; last = System.currentTimeMillis(); - if(first==null) { + if (first==null) { first = new Date(last); } } public String toString() { - if(count==0) + if (count==0) return name + " is on the denied list, but has not attempted Access"; else return diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java index f0b8d38d..07389aad 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/FQI.java @@ -31,14 +31,14 @@ public class FQI { StringBuilder sb = null; String[] split = Split.split('.',fqi); int at; - for(int i=split.length-1;i>=0;--i) { - if(sb == null) { + for (int i=split.length-1;i>=0;--i) { + if (sb == null) { sb = new StringBuilder(); } else { sb.append('.'); } - if((at = split[i].indexOf('@'))>0) { + if ((at = split[i].indexOf('@'))>0) { sb.append(split[i].subSequence(at+1, split[i].length())); } else { sb.append(split[i]); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java index 7c3ac30d..e790766b 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/JsonOutputStream.java @@ -39,11 +39,11 @@ public class JsonOutputStream extends OutputStream { @Override public void write(int b) throws IOException { - if(ret=='\n') { + if (ret=='\n') { ret = 0; - if(prev!=',' || (b!='{' && b!='[')) { + if (prev!=',' || (b!='{' && b!='[')) { os.write('\n'); - for(int i=0;i<indent;++i) { + for (int i=0;i<indent;++i) { os.write(TWO_SPACE); } } @@ -58,7 +58,7 @@ public class JsonOutputStream extends OutputStream { case ']': --indent; os.write('\n'); - for(int i=0;i<indent;++i) { + for (int i=0;i<indent;++i) { os.write(TWO_SPACE); } break; @@ -81,7 +81,7 @@ public class JsonOutputStream extends OutputStream { @Override public void close() throws IOException { - if(closeable) { + if (closeable) { os.close(); } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/NetMask.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/NetMask.java index 2a3d75ff..19fd1e2d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/NetMask.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/NetMask.java @@ -56,7 +56,7 @@ public class NetMask { public static long derive(byte[] inBytes) { long addr = 0L; int offset = inBytes.length*8; - for(int i=0;i<inBytes.length;++i) { + for (int i=0;i<inBytes.length;++i) { addr&=(inBytes[i]<<offset); offset-=8; } @@ -68,22 +68,22 @@ public class NetMask { int idx=str.indexOf(':'); int slash = str.indexOf('/'); - if(idx<0) { // Not IPV6, so it's IPV4... Is there a mask of 123/254? + if (idx<0) { // Not IPV6, so it's IPV4... Is there a mask of 123/254? idx=str.indexOf('.'); int offset = 24; int end = slash>=0?slash:str.length(); int bits = slash>=0?Integer.parseInt(str.substring(slash+1)):32; - if(check && bits>32) { + if (check && bits>32) { throw new MaskFormatException("Invalid Mask Offset in IPV4 Address"); } int prev = 0; long lbyte; - while(prev<end) { - if(idx<0) { + while (prev<end) { + if (idx<0) { idx = end; } lbyte = Long.parseLong(str.substring(prev, idx)); - if(check && (lbyte>255 || lbyte<0)) { + if (check && (lbyte>255 || lbyte<0)) { throw new MaskFormatException("Invalid Byte in IPV4 Address"); } rv|=lbyte<<offset; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java index a2c76967..4bb1d3b8 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Split.java @@ -36,20 +36,20 @@ public class Split { } public static String[] split(char c, String value, int start, int end) { - if(value==null) { + if (value==null) { return new String[0]; } // Count items to preallocate Array (memory alloc is more expensive than counting twice) int count,idx; - for(count=1,idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,++idx),++count); + for (count=1,idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,++idx),++count); String[] rv = new String[count]; - if(count==1) { + if (count==1) { rv[0]=value.substring(start,end); } else { int last=0; count=-1; - for(idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,idx)) { + for (idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,idx)) { rv[++count]=value.substring(last,idx); last = ++idx; } @@ -59,20 +59,20 @@ public class Split { } public static String[] splitTrim(char c, String value, int start, int end) { - if(value==null) { + if (value==null) { return new String[0]; } // Count items to preallocate Array (memory alloc is more expensive than counting twice) int count,idx; - for(count=1,idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,++idx),++count); + for (count=1,idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,++idx),++count); String[] rv = new String[count]; - if(count==1) { + if (count==1) { rv[0]=value.substring(start,end).trim(); } else { int last=0; count=-1; - for(idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,idx)) { + for (idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,idx)) { rv[++count]=value.substring(last,idx).trim(); last = ++idx; } @@ -86,23 +86,23 @@ public class Split { } public static String[] splitTrim(char c, String value, int size) { - if(value==null) { + if (value==null) { return new String[0]; } int idx; String[] rv = new String[size]; - if(size==1) { + if (size==1) { rv[0]=value.trim(); } else { int last=0; int count=-1; size-=2; - for(idx=value.indexOf(c);idx>=0 && count<size;idx=value.indexOf(c,idx)) { + for (idx=value.indexOf(c);idx>=0 && count<size;idx=value.indexOf(c,idx)) { rv[++count]=value.substring(last,idx).trim(); last = ++idx; } - if(idx>0) { + if (idx>0) { rv[++count]=value.substring(last,idx).trim(); } else { rv[++count]=value.substring(last).trim(); diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java index 5cab15f6..a85020ff 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/SubStandardConsole.java @@ -40,7 +40,7 @@ public class SubStandardConsole implements MyConsole { try { System.out.printf(fmt,args); rv = br.readLine(); - if(args.length==1 && rv.length()==0) { + if (args.length==1 && rv.length()==0) { rv = args[0].toString(); } } catch (IOException e) { diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java index 9ddd0626..da99d06d 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/TheConsole.java @@ -25,7 +25,7 @@ public class TheConsole implements MyConsole { @Override public String readLine(String fmt, Object... args) { String rv = System.console().readLine(fmt, args); - if(args.length>0 && args[0]!=null && rv.length()==0) { + if (args.length>0 && args[0]!=null && rv.length()==0) { rv = args[0].toString(); } return rv; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java index ff74f39c..d42aaf55 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/UserChainManip.java @@ -31,7 +31,7 @@ public class UserChainManip { */ public static StringBuilder build(StringBuilder sb, String app, String id, UserChain.Protocol proto, boolean as) { boolean mayAs; - if(!(mayAs=sb.length()==0)) { + if (!(mayAs=sb.length()==0)) { sb.append(','); } sb.append(app); @@ -39,34 +39,34 @@ public class UserChainManip { sb.append(id); sb.append(':'); sb.append(proto.name()); - if(as && mayAs) { + if (as && mayAs) { sb.append(":AS"); } return sb; } public static String idToNS(String id) { - if(id==null) { + if (id==null) { return ""; } else { StringBuilder sb = new StringBuilder(); char c; int end; boolean first = true; - for(int idx = end = id.length()-1;idx>=0;--idx) { - if((c = id.charAt(idx))=='@' || c=='.') { - if(idx<end) { - if(first) { + for (int idx = end = id.length()-1;idx>=0;--idx) { + if ((c = id.charAt(idx))=='@' || c=='.') { + if (idx<end) { + if (first) { first = false; } else { sb.append('.'); } - for(int i=idx+1;i<=end;++i) { + for (int i=idx+1;i<=end;++i) { sb.append(id.charAt(i)); } } end=idx-1; - if(c=='@') { + if (c=='@') { break; } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Vars.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Vars.java index b8468129..9751969e 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/Vars.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/Vars.java @@ -48,28 +48,28 @@ public class Vars { StringBuilder sb = null; int idx,index=0,prev = 0; - if(text.contains("%s")) { + if (text.contains("%s")) { sb = new StringBuilder(); } StringBuilder[] sbs = new StringBuilder[] {sb,holder}; boolean replace, clearIndex = false; int c; - while((idx=text.indexOf('%',prev))>=0) { + while ((idx=text.indexOf('%',prev))>=0) { replace = false; - if(clearIndex) { + if (clearIndex) { index=0; } - if(sb!=null) { + if (sb!=null) { sb.append(text,prev,idx); } - if(holder!=null) { + if (holder!=null) { holder.append(text,prev,idx); } boolean go = true; - while(go) { - if(text.length()>++idx) { + while (go) { + if (text.length()>++idx) { switch(c=text.charAt(idx)) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': @@ -87,19 +87,19 @@ public class Vars { } prev = idx; go=false; - if(replace) { - if(sb!=null) { + if (replace) { + if (sb!=null) { sb.append('%'); sb.append(index); } - if(index<=vars.length) { - if(holder!=null) { + if (index<=vars.length) { + if (holder!=null) { holder.append(vars[index-1]); } } } else { - for(StringBuilder s : sbs) { - if(s!=null) { + for (StringBuilder s : sbs) { + if (s!=null) { s.append("%"); } } @@ -107,10 +107,10 @@ public class Vars { } } - if(sb!=null) { + if (sb!=null) { sb.append(text,prev,text.length()); } - if(holder!=null) { + if (holder!=null) { holder.append(text,prev,text.length()); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java index 38322307..d0a7da47 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/Match.java @@ -57,42 +57,42 @@ public class Match<OUTPUT> { this.qname = new QName(ns,name); this.next = next; stopAfter = exclusive = false; - for(Match<OUTPUT> m : next) { // add the possible tags to look for - if(!m.stopAfter)m.prev = this; + for (Match<OUTPUT> m : next) { // add the possible tags to look for + if (!m.stopAfter)m.prev = this; } } public Match<OUTPUT> onMatch(OUTPUT output, XReader reader) throws XMLStreamException { - while(reader.hasNext()) { + while (reader.hasNext()) { XEvent event = reader.nextEvent(); switch(event.getEventType()) { case XMLEvent.START_ELEMENT: QName e_qname = event.asStartElement().getName(); //System.out.println("Start - " + e_qname); boolean match = false; - for(Match<OUTPUT> m : next) { - if(e_qname.equals(m.qname)) { + for (Match<OUTPUT> m : next) { + if (e_qname.equals(m.qname)) { match=true; - if(m.onMatch(output, reader)==null) { + if (m.onMatch(output, reader)==null) { return null; // short circuit Parsing } break; } } - if(exclusive && !match) // When Tag MUST be present, i.e. the Root Tag, versus info we're not interested in + if (exclusive && !match) // When Tag MUST be present, i.e. the Root Tag, versus info we're not interested in return null; break; case XMLEvent.CHARACTERS: //System.out.println("Data - " +event.asCharacters().getData()); - if(action!=null) { - if(!action.content(output,event.asCharacters().getData())) { + if (action!=null) { + if (!action.content(output,event.asCharacters().getData())) { return null; } } break; case XMLEvent.END_ELEMENT: //System.out.println("End - " + event.asEndElement().getName()); - if(event.asEndElement().getName().equals(qname)) { + if (event.asEndElement().getName().equals(qname)) { return prev; } break; diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java index b7cc40ad..aa46bec5 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/wsse/XReader.java @@ -66,7 +66,7 @@ public class XReader { } public boolean hasNext() throws XMLStreamException { - if(curr==null) { + if (curr==null) { curr = parse(); } return curr!=null; @@ -106,7 +106,7 @@ public class XReader { Map<String,String> nss = nsses.isEmpty()?null:nsses.peek(); XEvent rv; - if((rv=another)!=null) { // "another" is a tag that may have needed to be created, but not + if ((rv=another)!=null) { // "another" is a tag that may have needed to be created, but not // immediately returned. Save for next parse. If necessary, this could be turned into // a FIFO storage, but a single reference is enough for now. another = null; // "rv" is now set for the Event, and will be returned. Set to Null. @@ -115,15 +115,15 @@ public class XReader { int c=0; try { - while(go && (c=is.read())>=0) { + while (go && (c=is.read())>=0) { ++count; switch(c) { case '<': // Tag is opening state|=~BEGIN_DOC; // remove BEGIN_DOC flag, this is possibly an XML Doc XEvent cxe = null; - if(baos.size()>0) { // If there are any characters between tags, we send as Character Event + if (baos.size()>0) { // If there are any characters between tags, we send as Character Event String chars = baos.toString().trim(); // Trim out WhiteSpace before and after - if(chars.length()>0) { // don't send if Characters were only whitespace + if (chars.length()>0) { // don't send if Characters were only whitespace cxe = new XEvent.Characters(chars); baos.reset(); go = false; @@ -145,7 +145,7 @@ public class XReader { default: ns = ""; } - if(ns==null) + if (ns==null) throw new XMLStreamException("Invalid Namespace Prefix at " + count); go = false; switch(t.state) { // based on @@ -165,9 +165,9 @@ public class XReader { break; case START_TAG|END_TAG: // This tag is both start/end aka <myTag/> rv = new XEvent.StartElement(ns,t.name); - if(last=='/')another = new XEvent.EndElement(ns,t.name); + if (last=='/')another = new XEvent.EndElement(ns,t.name); } - if(cxe!=null) { // if there is a Character Event, it actually should go first. ow. + if (cxe!=null) { // if there is a Character Event, it actually should go first. ow. another = rv; // Make current Event the "another" or next event, and rv = cxe; // send Character Event now } @@ -175,12 +175,12 @@ public class XReader { case ' ': case '\t': case '\n': - if((state&BEGIN_DOC)==BEGIN_DOC) { // if Whitespace before doc, just ignore + if ((state&BEGIN_DOC)==BEGIN_DOC) { // if Whitespace before doc, just ignore break; } // fallthrough on purpose default: - if((state&BEGIN_DOC)==BEGIN_DOC) { // if there is any data at the start other than XML Tag, it's not XML + if ((state&BEGIN_DOC)==BEGIN_DOC) { // if there is any data at the start other than XML Tag, it's not XML throw new XMLStreamException("Parse Error: This is not an XML Doc"); } baos.write(c); // save off Characters @@ -190,7 +190,7 @@ public class XReader { } catch (IOException e) { throw new XMLStreamException(e); // all errors parsing will be treated as XMLStreamErrors (like StAX) } - if(c==-1 && (state&BEGIN_DOC)==BEGIN_DOC) { // Normally, end of stream is ok, however, we need to know if the + if (c==-1 && (state&BEGIN_DOC)==BEGIN_DOC) { // Normally, end of stream is ok, however, we need to know if the throw new XMLStreamException("Premature End of File"); // document isn't an XML document, so we throw exception if it } // hasn't yet been determined to be an XML Doc } @@ -214,15 +214,15 @@ public class XReader { String prefix=null,name=null,value=null; baos.reset(); - while(go && (c=is.read())>=0) { + while (go && (c=is.read())>=0) { ++count; - if(quote!=0) { // If we're in a quote, we only end if we hit another quote of the same time, not preceded by \ - if(c==quote && last!='\\') { + if (quote!=0) { // If we're in a quote, we only end if we hit another quote of the same time, not preceded by \ + if (c==quote && last!='\\') { quote=0; } else { baos.write(c); } - } else if((state&COMMENT)==COMMENT) { // similar to Quote is being in a comment + } else if ((state&COMMENT)==COMMENT) { // similar to Quote is being in a comment switch(c) { case '-': switch(state) { // XML has a complicated Quote set... <!-- --> ... we keep track if each has been met with flags. @@ -244,7 +244,7 @@ public class XReader { } break; case '>': // Tag indicator has been found, do we have all the comment characters in line? - if((state&COMPLETE_COMMENT)==COMPLETE_COMMENT) { + if ((state&COMPLETE_COMMENT)==COMPLETE_COMMENT) { byte ba[] = baos.toByteArray(); tag = new Tag(null,null, new String(ba,0,ba.length-2)); baos.reset(); @@ -254,7 +254,7 @@ public class XReader { // fall through on purpose default: state&=~(COMMENT_D3|COMMENT_D4); - if((state&IN_COMMENT)!=IN_COMMENT) state&=~IN_COMMENT; // false alarm, it's not actually a comment + if ((state&IN_COMMENT)!=IN_COMMENT) state&=~IN_COMMENT; // false alarm, it's not actually a comment baos.write(c); } } else { // Normal Tag Processing loop @@ -273,7 +273,7 @@ public class XReader { } break; case '!': - if(last=='<') { + if (last=='<') { state|=COMMENT|COMMENT_E; // likely a comment, continue processing in Comment Loop } baos.write(c); @@ -296,15 +296,15 @@ public class XReader { case ' ': case '\t': case '\n': // white space indicates change in internal tag state, ex between name and between attributes - if((state&VALUE)==VALUE) { + if ((state&VALUE)==VALUE) { value = baos.toString(); // we're in VALUE state, add characters to Value - } else if(name==null) { + } else if (name==null) { name = baos.toString(); // we're in Name state (default) add characters to Name } baos.reset(); // we've assigned chars, reset buffer - if(name!=null) { // Name is not null, there's a tag in the offing here... + if (name!=null) { // Name is not null, there's a tag in the offing here... Tag t = new Tag(prefix,name,value); - if(tag==null) { // Set as the tag to return, if not exists + if (tag==null) { // Set as the tag to return, if not exists tag = t; } else { // if we already have a Tag, then we'll treat this one as an attribute tag.add(t); @@ -314,7 +314,7 @@ public class XReader { break; case '\'': // is the character one of two kinds of quote? case '"': - if(last!='\\') { + if (last!='\\') { quote=c; break; } @@ -327,10 +327,10 @@ public class XReader { last = c; } int type = state&(DOC_TYPE|COMMENT|END_TAG|START_TAG); // get just the Tag states and turn into Type for Tag - if(type==0) { + if (type==0) { type=START_TAG; } - if(tag!=null) { + if (tag!=null) { tag.state|=type; // add the appropriate Tag States } return tag; @@ -350,20 +350,20 @@ public class XReader { */ private Map<String, String> getNss(Map<String, String> nss, Tag t) { Map<String,String> newnss = null; - if(t.attribs!=null) { - for(Tag tag : t.attribs) { - if("xmlns".equals(tag.prefix)) { - if(newnss==null) { + if (t.attribs!=null) { + for (Tag tag : t.attribs) { + if ("xmlns".equals(tag.prefix)) { + if (newnss==null) { newnss = new HashMap<>(); - if(nss!=null)newnss.putAll(nss); + if (nss!=null)newnss.putAll(nss); } newnss.put(tag.name, tag.value); } } } //return newnss==null?(nss==null?new HashMap<String,String>():nss):newnss; - if(newnss==null) { - if(nss==null) { + if (newnss==null) { + if (nss==null) { newnss = new HashMap<>(); } else { newnss = nss; @@ -399,7 +399,7 @@ public class XReader { * @param tag */ public void add(Tag attrib) { - if(attribs == null) { + if (attribs == null) { attribs = new ArrayList<>(); } attribs.add(attrib); @@ -407,14 +407,14 @@ public class XReader { public String toString() { StringBuffer sb = new StringBuffer(); - if(prefix!=null) { + if (prefix!=null) { sb.append(prefix); sb.append(':'); } sb.append(name==null?"!!ERROR!!":name); char quote = ((state&DOC_TYPE)==DOC_TYPE)?'\'':'"'; - if(value!=null) { + if (value!=null) { sb.append('='); sb.append(quote); sb.append(value); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java index f57bb93e..22ce8abf 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/filter/test/JU_AUTHZServlet.java @@ -99,7 +99,7 @@ public class JU_AUTHZServlet { field.setAccessible(true); field.set(target, value); field.setAccessible(false); - } catch(Exception e) { + } catch (Exception e) { System.err.println("Could not set field [" + fieldName + "] to " + value); } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java index a8839f2c..ea45c128 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/principal/test/JU_X509Principal.java @@ -93,7 +93,7 @@ public class JU_X509Principal { try { x509 = new X509Principal(cert, cred, null); fail("Should have thrown an Exception"); - } catch(IOException e) { + } catch (IOException e) { assertThat(e.getMessage(), is("X509 does not have Identity as CN")); } @@ -102,7 +102,7 @@ public class JU_X509Principal { try { x509 = new X509Principal(cert, cred, null); fail("Should have thrown an Exception"); - } catch(IOException e) { + } catch (IOException e) { assertThat(e.getMessage(), is("X509 does not have Identity as CN")); } @@ -111,7 +111,7 @@ public class JU_X509Principal { try { x509 = new X509Principal(cert, cred, null); fail("Should have thrown an Exception"); - } catch(IOException e) { + } catch (IOException e) { assertThat(e.getMessage(), is("X509 does not have Identity as CN")); } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java index d67acf3c..47d8f8d1 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/taf/dos/test/JU_DenialOfServiceTaf.java @@ -353,7 +353,7 @@ public class JU_DenialOfServiceTaf { field.setAccessible(true); field.set(null, value); field.setAccessible(false); - } catch(Exception e) { + } catch (Exception e) { System.err.println("Could not set field [" + fieldName + "] to " + value); } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java index affaccc5..a3e0db0d 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_AES.java @@ -60,7 +60,7 @@ public class JU_AES { byte[] keyBytes = new byte[AES.AES_KEY_SIZE/8]; char[] codeset = Symm.base64.codeset; int offset = (Math.abs(codeset[0]) + 47) % (codeset.length - keyBytes.length); - for(int i = 0; i < keyBytes.length; ++i) { + for (int i = 0; i < keyBytes.length; ++i) { keyBytes[i] = (byte)codeset[i+offset]; } aes = new AES(keyBytes, 0, keyBytes.length); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java index 78a6fa21..60999b69 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_BufferedServletInputStream.java @@ -151,7 +151,7 @@ public class JU_BufferedServletInputStream { @Test public void ByteArrayReadStateIsReadTest() throws Exception { byte output[] = new byte[200]; - for(int i = 0; i < 2; ++i) { + for (int i = 0; i < 2; ++i) { bsis.mark(0); bsis.read(output, 0, 100); Assert.assertEquals(new String(output, 0, expected.length()), expected); @@ -160,7 +160,7 @@ public class JU_BufferedServletInputStream { bsis.read(output, 0, output.length); Assert.assertEquals(new String(output, 0, expected.length()), expected); bsis = new BufferedServletInputStream(new ByteArrayInputStream(output)); - if(i == 0) { + if (i == 0) { output = new byte[200]; } } @@ -286,7 +286,7 @@ public class JU_BufferedServletInputStream { byte aa[] = new byte[testString.length()]; // 65 count... important for our test (divisible by 5); int read; - for(int i=0;i<aa.length;i+=5) { + for (int i=0;i<aa.length;i+=5) { read = bsis.read(aa, i, 5); assertEquals(5,read); } @@ -296,7 +296,7 @@ public class JU_BufferedServletInputStream { byte bb[] = new byte[aa.length]; read = 0; - for(int i=0;read>=0;i+=read) { + for (int i=0;read>=0;i+=read) { read = bsis.read(bb,i,5); switch(i) { case 65: diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java index 1bdbc571..4c842915 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_Capacitor.java @@ -58,13 +58,13 @@ public class JU_Capacitor { assertNull(curr_field.get(cap)); assertEquals(idx_field.get(cap), 0); - for(int iter = 0; iter < 20; ++iter) { - for(int i = 0; i < 20; ++i) { + for (int iter = 0; iter < 20; ++iter) { + for (int i = 0; i < 20; ++i) { cap.put((byte)('a' + i)); } cap.setForRead(); byte[] array = new byte[20]; - for(int i = 0; i < 20; ++i) { + for (int i = 0; i < 20; ++i) { array[i]=(byte)cap.read(); } assertEquals("abcdefghijklmnopqrst", new String(array)); @@ -73,12 +73,12 @@ public class JU_Capacitor { cap.done(); } - for(int i = 0; i < 500; i++) { + for (int i = 0; i < 500; i++) { cap.put((byte)'a'); } cap.setForRead(); byte[] array = new byte[500]; - for(int i = 0; i < 500; ++i) { + for (int i = 0; i < 500; ++i) { array[i]=(byte)cap.read(); } assertEquals((new String(array)).length(), 500); @@ -88,7 +88,7 @@ public class JU_Capacitor { @Test public void availableTest() { assertEquals(cap.available(), 0); - for(int i = 0; i < 100; ++i) { + for (int i = 0; i < 100; ++i) { cap.put((byte)'a'); } // The Capacitor can hold 256 bytes. After reading 100 bytes, @@ -114,12 +114,12 @@ public class JU_Capacitor { byte[] a = b.getBytes(); byte[] c = new byte[b.length()]; // we want to use this to test reading offsets, etc - for(int i = 0; i < a.length; i += 11) { + for (int i = 0; i < a.length; i += 11) { cap.put(a, i, Math.min(11, a.length-i)); } cap.reset(); int read; - for(int i = 0; i < c.length; i += read) { + for (int i = 0; i < c.length; i += read) { read = cap.read(c, i, Math.min(3, c.length-i)); } assertEquals(b, new String(c)); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java index cba4c46a..967bf221 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_CmdLine.java @@ -163,7 +163,7 @@ public class JU_CmdLine { String filePath = "test/output_key"; File testDir = new File("test"); - if(!testDir.exists()) { + if (!testDir.exists()) { testDir.mkdirs(); } CmdLine.main(new String[]{"keygen", filePath}); diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java index 6f6f49e1..45f221c4 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_PropAccess.java @@ -115,7 +115,7 @@ public class JU_PropAccess { }); try { pa.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { + } catch (Exception e) { fail("Should have thrown an exception"); } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java index 15464bf1..7c67f8c9 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/test/JU_ServletContextAccess.java @@ -89,7 +89,7 @@ public class JU_ServletContextAccess { try { sca.log(new Exception("This exception was thrown intentionally, please ignore it")); - } catch(Exception e) { + } catch (Exception e) { fail("Should have thrown an exception"); } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java index 5a1014bc..5f880403 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/wsse/test/JU_WSSEParser.java @@ -130,12 +130,12 @@ public class JU_WSSEParser { // is = new BufferedServletInputStream(fis); // is.mark(0); // try { -// while(is.read()>=0); +// while (is.read()>=0); // } finally { // fis.close(); // } // -// for(int i=0;i<iter;++i) { +// for (int i=0;i<iter;++i) { // start = System.nanoTime(); // is.reset(); // try { diff --git a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java index 7c633640..f98c76fb 100644 --- a/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java +++ b/cadi/oauth-enduser/src/main/java/org/onap/aaf/cadi/enduser/SimpleRESTClient.java @@ -61,11 +61,11 @@ public class SimpleRESTClient { callTimeout = Integer.parseInt(tcf.access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); tokenClient = tcf.newClient(tokenURL); Result<TimedToken> rtt = tokenClient.getToken(scope); - if(rtt.isOK()) { + if (rtt.isOK()) { restClient = tcf.newTzClient(endpoint); - if((client_id = tcf.access.getProperty(Config.AAF_APPID, null))==null) { - if((client_id = tcf.access.getProperty(Config.CADI_ALIAS, null))==null) { + if ((client_id = tcf.access.getProperty(Config.AAF_APPID, null))==null) { + if ((client_id = tcf.access.getProperty(Config.CADI_ALIAS, null))==null) { throw new CadiException(Config.AAF_APPID + " or " + Config.CADI_ALIAS + " needs to be defined"); } } @@ -86,10 +86,10 @@ public class SimpleRESTClient { //Format:<ID>:<APP>:<protocol>[:AS][,<ID>:<APP>:<protocol>]* public SimpleRESTClient endUser(Principal principal) { - if(principal==null) { + if (principal==null) { chain = null; } else { - if(principal instanceof TaggedPrincipal) { + if (principal instanceof TaggedPrincipal) { TaggedPrincipal tp = (TaggedPrincipal)principal; chain = tp.getName() + ':' + (app==null?"":app) + ':' + tp.tag() + ":AS"; } else { @@ -128,7 +128,7 @@ public class SimpleRESTClient { } public StringBuilder builder() { - if(sb==null) { + if (sb==null) { sb = new StringBuilder(); content = null; } @@ -140,16 +140,16 @@ public class SimpleRESTClient { */ public void clear() { content = null; - if(sb!=null) { + if (sb!=null) { sb.setLength(0); } } @Override public String toString() { - if(content!=null) { + if (content!=null) { return content; - } else if(sb!=null) { + } else if (sb!=null) { return sb.toString(); } else { return ""; @@ -158,8 +158,8 @@ public class SimpleRESTClient { public byte[] getBytes() { byte[] rv; - if(content==null) { - if(sb==null) { + if (content==null) { + if (sb==null) { rv = EMPTY_STREAM_BYTES; } else { rv = sb.toString().getBytes(); @@ -192,7 +192,7 @@ public class SimpleRESTClient { return client.create(path, contentType, new ETransfer(input)); } }); - if(!future.get(callTimeout)) { + if (!future.get(callTimeout)) { throw new RESTException(future); } } @@ -217,7 +217,7 @@ public class SimpleRESTClient { return client.read(path,accepts, headers()); } }); - if(future.get(callTimeout)) { + if (future.get(callTimeout)) { return future.value; } else { throw new RESTException(future); @@ -245,7 +245,7 @@ public class SimpleRESTClient { return client.update(path, contentType, new ETransfer(input)); } }); - if(future.get(callTimeout)) { + if (future.get(callTimeout)) { return future.value; } else { throw new RESTException(future); @@ -268,7 +268,7 @@ public class SimpleRESTClient { return client.delete(path, contentType); } }); - if(!future.get(callTimeout)) { + if (!future.get(callTimeout)) { throw new RESTException(future); } } @@ -292,14 +292,14 @@ public class SimpleRESTClient { } public String[] headers() { - if(chain==null) { + if (chain==null) { return headers.headers(); } else { String[] strs = headers.headers(); String[] rv = new String[strs.length+2]; rv[0]=Config.CADI_USER_CHAIN; rv[1]=chain; - for(int i = 0;i<strs.length;++i) { + for (int i = 0;i<strs.length;++i) { rv[i+2]=strs[i]; } return rv; diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java index 154ba1b7..cd9c2313 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OAuthExample.java @@ -94,7 +94,7 @@ public class OAuthExample { // If AAF Token server, then its just the same as your other AAF MechID creds // If it is the Alternate OAUTH, you'll need THOSE credentials. See that tool's Onboarding procedures. String client_id = access.getProperty(Config.AAF_APPID); - if(client_id==null) { + if (client_id==null) { // For AAF, client_id CAN be Certificate. This is not necessarily true elsewhere client_id = access.getProperty(Config.CADI_ALIAS); } @@ -126,7 +126,7 @@ public class OAuthExample { // tc.clearToken("org.onap.aaf","org.onap.test"); // Result Object can be queried for success - if(rtt.isOK()) { + if (rtt.isOK()) { TimedToken token = rtt.value; print(token); // Take a look at what's in a Token @@ -147,7 +147,7 @@ public class OAuthExample { // The "future" calling method allows you to do other processing, such as call more than one backend // client before picking up the result // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then - if(future.get(CALL_TIMEOUT)) { + if (future.get(CALL_TIMEOUT)) { // Client Returned expected value return future.value; } else { @@ -165,7 +165,7 @@ public class OAuthExample { // As a Service, read Introspection information as proof of Authenticated Authorization ////////////////////////////////////////////////////////////////////// // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( - // i.e. if(isUserInRole("ns.perm|instance|action")) {... + // i.e. if (isUserInRole("ns.perm|instance|action")) {... // // Here, however, is a way to introspect via Java // @@ -174,7 +174,7 @@ public class OAuthExample { TokenClient tci = tcf.newClient(tokenIntrospectURL); tci.client_creds(client_id, client_secret); Result<Introspect> is = tci.introspect(token.getAccessToken()); - if(is.isOK()) { + if (is.isOK()) { // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure print(is.value); // do something with Introspect Object } else { @@ -206,7 +206,7 @@ public class OAuthExample { } private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { + if (ti==null || ti.getClientId()==null) { System.out.println("Empty Introspect"); return; } diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java index 657a9b78..f4fe017f 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/OnapClientExample.java @@ -97,7 +97,7 @@ public class OnapClientExample { // tc.clearToken("org.onap.aaf","org.onap.test"); // Result Object can be queried for success - if(rtt.isOK()) { + if (rtt.isOK()) { TimedToken token = rtt.value; print(token); // Take a look at what's in a Token @@ -122,7 +122,7 @@ public class OnapClientExample { // The "future" calling method allows you to do other processing, such as call more than one backend // client before picking up the result // If "get" matches the HTTP Code for the method (i.e. read HTTP Return value is 200), then - if(future.get(CALL_TIMEOUT)) { + if (future.get(CALL_TIMEOUT)) { // Client Returned expected value return future.value; } else { @@ -140,7 +140,7 @@ public class OnapClientExample { // As a Service, read Introspection information as proof of Authenticated Authorization ////////////////////////////////////////////////////////////////////// // CADI Framework (i.e. CadiFilter) works with the Introspection to drive the J2EE interfaces ( - // i.e. if(isUserInRole("ns.perm|instance|action")) {... + // i.e. if (isUserInRole("ns.perm|instance|action")) {... // // Here, however, is a way to introspect via Java // @@ -148,7 +148,7 @@ public class OnapClientExample { // We need a Different Introspect TokenClient, because different Endpoint (and usually different Services) TokenClient tci = tcf.newClient(Config.AAF_OAUTH2_INTROSPECT_URL); Result<Introspect> is = tci.introspect(token.getAccessToken()); - if(is.isOK()) { + if (is.isOK()) { // Note that AAF will add JSON set of Permissions as part of "Content:", legitimate extension of OAuth Structure print(is.value); // do something with Introspect Object } else { @@ -180,7 +180,7 @@ public class OnapClientExample { } private static void print(Introspect ti) { - if(ti==null || ti.getClientId()==null) { + if (ti==null || ti.getClientId()==null) { System.out.println("Empty Introspect"); return; } diff --git a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java index 27f9198a..dc1824fc 100644 --- a/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java +++ b/cadi/oauth-enduser/src/test/java/org/onap/aaf/cadi/enduser/test/SimpleRestClientExample.java @@ -42,7 +42,7 @@ public class SimpleRestClientExample { String urlString = cf.getAccess().getProperty("myurl", null); - if(urlString==null) { + if (urlString==null) { System.out.println("Note: In your startup, add \"myurl=https://<aaf hello machine>:8130\" to command line\n\t" + "OR\n\t" + " add -Dmyurl=https://<aaf hello machine>:8130 to VM Args\n\t" @@ -64,8 +64,8 @@ public class SimpleRestClientExample { PrintWriter pw = input.writer(); pw.print("{\"something\": ["); - for(int i=0;i<4;++i) { - if(i>0) { + for (int i=0;i<4;++i) { + if (i>0) { pw.print(','); } pw.print("{\"myint\":"); @@ -136,14 +136,14 @@ public class SimpleRestClientExample { System.out.println("-------- START Expecting Exception starting here --------"); expectException = true; restClient.get("notAnAPI"); - } catch(RESTException e) { + } catch (RESTException e) { System.out.println(e.getCode()); System.out.println(e.getMsg()); System.out.println(e.getMessage()); System.out.println(e.getLocalizedMessage()); System.out.println(e); } finally { - if(expectException) { + if (expectException) { System.out.println("-------- END Expecting Exception starting here --------"); } System.out.println("-------- END REST READ/GET --------"); diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java index f11d8f89..e3342914 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/MyServlet.java @@ -60,15 +60,15 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; request.getUserPrincipal()); String perm = request.getParameter("PERM"); - if(perm!=null) { - if(request.isUserInRole(perm)) { - if(perm.indexOf('|')<0) { + if (perm!=null) { + if (request.isUserInRole(perm)) { + if (perm.indexOf('|')<0) { res.getOutputStream().println("\nCongrats!, You are in Role " + perm); } else { res.getOutputStream().println("\nCongrats!, You have Permission " + perm); } } else { - if(perm.indexOf('|')<0) { + if (perm.indexOf('|')<0) { res.getOutputStream().println("\nSorry, you are NOT in Role " + perm); } else { res.getOutputStream().println("\nSorry, you do NOT have Permission " + perm); @@ -78,12 +78,12 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; // You can get the working AAFCon from Trans AAFCon<?> aafcon = AAFCon.obtain(req); - if(aafcon!=null) { + if (aafcon!=null) { try { res.getOutputStream().println("----- Perms JSON from direct call -----"); final Principal up = request.getUserPrincipal(); TaggedPrincipal tp; - if(up instanceof TaggedPrincipal) { + if (up instanceof TaggedPrincipal) { tp = (TaggedPrincipal)up; } else { tp = new TaggedPrincipal() { @@ -101,7 +101,7 @@ import org.onap.aaf.cadi.principal.TaggedPrincipal; // This call will be "as the user calling", but only if permission is set to trust. // Future<String> future = aafcon.clientAs("2.0",tp).read("/authz/perms/user/"+request.getUserPrincipal().getName(),"application/Perms+json"); Future<String> future = aafcon.client("2.0").read("/authz/perms/user/"+request.getUserPrincipal().getName(),"application/Perms+json"); - if(future.get(4000 /* timeout */)) { + if (future.get(4000 /* timeout */)) { res.getOutputStream().print(future.value); } else { System.err.println(future.code() + ", " + future.body()); diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java index cec8a539..165acffb 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/JettyServletServer.java @@ -51,7 +51,7 @@ public abstract class JettyServletServer implements Servlet { int maxPoolSize = 10; int keepAliveTime = 3000; String hostname = access.getProperty(Config.HOSTNAME, null); - if(hostname==null) { + if (hostname==null) { hostname = Inet4Address.getLocalHost().getHostName(); } @@ -62,7 +62,7 @@ public abstract class JettyServletServer implements Servlet { Server server = new Server(pool); String protocol; - if(access.getProperty(Config.CADI_KEYSTORE_PASSWORD,null)==null) { + if (access.getProperty(Config.CADI_KEYSTORE_PASSWORD,null)==null) { ServerConnector conn = new ServerConnector(server); conn.setHost(hostname); conn.setPort(port); diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java index 29462cfb..4d170f3f 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/jetty/MiniJASPIWrap.java @@ -55,9 +55,9 @@ public class MiniJASPIWrap extends ServletHolder { this.rolesAllowed = servlet.getAnnotation(RolesAllowed.class); StringBuilder sb = new StringBuilder(); boolean first = true; - if(rolesAllowed!=null) { - for(String str : rolesAllowed.value()) { - if(first)first=false; + if (rolesAllowed!=null) { + for (String str : rolesAllowed.value()) { + if (first)first=false; else sb.append(','); sb.append(str); } @@ -73,26 +73,26 @@ public class MiniJASPIWrap extends ServletHolder { */ @Override public void handle(Request baseRequest, ServletRequest request, ServletResponse response) throws ServletException, UnavailableException, IOException { - if(rolesAllowed==null) { + if (rolesAllowed==null) { super.handle(baseRequest, request, response); } else { // Validate try { HttpServletRequest hreq = (HttpServletRequest)request; boolean proceed = false; - for(String role : rolesAllowed.value()) { - if(hreq.isUserInRole(role)) { + for (String role : rolesAllowed.value()) { + if (hreq.isUserInRole(role)) { proceed = true; break; } } - if(proceed) { + if (proceed) { super.handle(baseRequest, request, response); } else { //baseRequest.getServletContext().log(hreq.getUserPrincipal().getName()+" Refused " + roles); ((HttpServletResponse)response).sendError(403); // forbidden } - } catch(ClassCastException e) { + } catch (ClassCastException e) { throw new ServletException("JASPIWrap only supports HTTPServletRequest/HttpServletResponse"); } } diff --git a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java index 1597dbd5..e82dddd2 100644 --- a/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java +++ b/cadi/servlet-sample/src/test/java/org/onap/aaf/sample/cadi/tomcate/TomcatEmbedded.java @@ -76,10 +76,10 @@ public class TomcatEmbedded { private static void setAttr(Connector connector, Access access, String ctag, String atag) throws IOException { String value = access.getProperty(atag, null); - if(value==null) { + if (value==null) { access.log(Level.ERROR, atag, "is null"); } else { - if(value.startsWith("enc:")) { + if (value.startsWith("enc:")) { access.log(Level.INIT,atag,"=enc:************"); value = access.decrypt(value, false); } else { diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java b/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java index d72222e8..a8f0951e 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/BaseDataFactory.java @@ -71,13 +71,13 @@ public class BaseDataFactory { env.staticSlot(EnvFactory.SCHEMA_DIR),
EnvFactory.DEFAULT_SCHEMA_DIR);
File dir = new File(schemaDir);
- if(!dir.exists())throw new APIException("Schema Directory " + schemaDir + " does not exist. You can set this with " + EnvFactory.SCHEMA_DIR + " property");
+ if (!dir.exists())throw new APIException("Schema Directory " + schemaDir + " does not exist. You can set this with " + EnvFactory.SCHEMA_DIR + " property");
FileInputStream[] fis = new FileInputStream[filenames.length];
Source[] sources = new Source[filenames.length];
File f;
- for(int i=0; i<filenames.length; ++i) {
- if(!(f=new File(schemaDir + File.separatorChar + filenames[i])).exists()) {
- if(!f.exists()) throw new APIException("Cannot find " + f.getName() + " for schema validation");
+ for (int i=0; i<filenames.length; ++i) {
+ if (!(f=new File(schemaDir + File.separatorChar + filenames[i])).exists()) {
+ if (!f.exists()) throw new APIException("Cannot find " + f.getName() + " for schema validation");
}
try {
fis[i]=new FileInputStream(f);
@@ -95,7 +95,7 @@ public class BaseDataFactory { } catch (SAXException e) {
throw new APIException(e);
} finally {
- for(FileInputStream d : fis) {
+ for (FileInputStream d : fis) {
try {
d.close();
} catch (IOException e) {
@@ -109,10 +109,10 @@ public class BaseDataFactory { public static QName getQName(Class<?> clss) throws APIException {
// Obtain the Necessary info for QName from Requirement
XmlRootElement xre = clss.getAnnotation(XmlRootElement.class);
- if(xre==null)throw new APIException(clss.getName() + " does not have an XmlRootElement annotation");
+ if (xre==null)throw new APIException(clss.getName() + " does not have an XmlRootElement annotation");
Package pkg = clss.getPackage();
XmlSchema xs = pkg.getAnnotation(XmlSchema.class);
- if(xs==null) throw new APIException(clss.getName() + " package-info does not have an XmlSchema annotation");
+ if (xs==null) throw new APIException(clss.getName() + " package-info does not have an XmlSchema annotation");
return new QName(xs.namespace(),xre.name());
}
@@ -367,7 +367,7 @@ public class BaseDataFactory { // */
// public Character objectify(Env env, String input) throws APIException {
// int length = input.length();
-// if(length<1 || length>1) {
+// if (length<1 || length>1) {
// throw new APIException("String [" + input + "] does not represent a single Character");
// }
// return input.charAt(0);
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java b/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java index aa74edc9..f2b539a3 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/LogTarget.java @@ -68,8 +68,8 @@ public interface LogTarget { PrintStream out = System.out;
out.print(org.onap.aaf.misc.env.util.Chrono.dateFmt.format(new Date()));
out.print(": ");
- for(Object str : msgs) {
- if(str!=null) {
+ for (Object str : msgs) {
+ if (str!=null) {
out.print(str.toString());
out.print(' ');
} else {
@@ -83,7 +83,7 @@ public interface LogTarget { PrintStream out = System.out;
out.print(Chrono.dateFmt.format(new Date()));
out.print(": ");
- for(Object str : msgs) {
+ for (Object str : msgs) {
out.print(str.toString());
out.print(' ');
}
@@ -108,7 +108,7 @@ public interface LogTarget { PrintStream out = System.err;
out.print(Chrono.dateFmt.format(new Date()));
out.print(": ");
- for(Object str : msgs) {
+ for (Object str : msgs) {
out.print(str.toString());
out.print(' ');
}
@@ -120,7 +120,7 @@ public interface LogTarget { PrintStream out = System.err;
out.print(Chrono.dateFmt.format(new Date()));
out.print(": ");
- for(Object str : msgs) {
+ for (Object str : msgs) {
out.print(str.toString());
out.print(' ');
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java b/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java index b8a8e03a..6848be09 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/StoreImpl.java @@ -81,15 +81,15 @@ public class StoreImpl implements Store { staticMap = new HashMap<>();
localMap = new HashMap<>();
- if(tag!=null) {
+ if (tag!=null) {
String tequals = tag + '=';
- for(String arg : args) {
- if(arg.startsWith(tequals) && !arg.equals(tequals)) { // needs to have something after =
+ for (String arg : args) {
+ if (arg.startsWith(tequals) && !arg.equals(tequals)) { // needs to have something after =
Properties props = new Properties();
- for(String f : Split.split(File.pathSeparatorChar,arg.substring(tequals.length()))) {
+ for (String f : Split.split(File.pathSeparatorChar,arg.substring(tequals.length()))) {
moreProps(new File(f),props);
}
- for(Entry<Object, Object> es : props.entrySet()) {
+ for (Entry<Object, Object> es : props.entrySet()) {
put(staticSlot(es.getKey().toString()),es.getValue());
}
}
@@ -105,29 +105,29 @@ public class StoreImpl implements Store { staticMap = new HashMap<>();
localMap = new HashMap<>();
- if(tag!=null) {
+ if (tag!=null) {
String fname = props.getProperty(tag);
- if(fname!=null) {
- for(String f : Split.split(File.pathSeparatorChar,fname)) {
- if(!moreProps(new File(f),props)) {
+ if (fname!=null) {
+ for (String f : Split.split(File.pathSeparatorChar,fname)) {
+ if (!moreProps(new File(f),props)) {
System.err.println("Unable to load Properties from " + f);
}
}
}
}
- for(Entry<Object, Object> es : props.entrySet()) {
+ for (Entry<Object, Object> es : props.entrySet()) {
put(staticSlot(es.getKey().toString()),es.getValue());
}
}
public void propsFromArgs(String tag, String[] args) {
- if(tag!=null) {
- for(String arg : args) {
+ if (tag!=null) {
+ for (String arg : args) {
String sarg[] = Split.split('=',arg);
- if(sarg.length==2) {
- if(tag.equals(sarg[0])) {
- for(String fname : Split.split(File.pathSeparatorChar,sarg[1])) {
+ if (sarg.length==2) {
+ if (tag.equals(sarg[0])) {
+ for (String fname : Split.split(File.pathSeparatorChar,sarg[1])) {
moreProps(new File(fname),null /* no target */);
}
}
@@ -138,22 +138,22 @@ public class StoreImpl implements Store { }
private boolean moreProps(File f, Properties target) {
- if(f.exists()) {
+ if (f.exists()) {
Properties props = new Properties();
try {
FileInputStream fis = new FileInputStream(f);
try {
props.load(fis);
- if(target!=null) {
+ if (target!=null) {
target.load(fis);
}
} finally {
fis.close();
}
- } catch(IOException e) {
+ } catch (IOException e) {
System.err.println(e);
}
- for(Entry<Object, Object> es : props.entrySet()) {
+ for (Entry<Object, Object> es : props.entrySet()) {
put(staticSlot(es.getKey().toString()),es.getValue());
}
return true;
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java index b86b4fbb..c0e7bde7 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/AbsTrans.java @@ -124,7 +124,7 @@ public abstract class AbsTrans<ENV extends Env> implements TransStore { Metric metric = new Metric();
int last = (metric.entries = trail.size()) -1;
metric.buckets = flags.length==0?EMPTYF:new float[flags.length];
- if(last>=0) {
+ if (last>=0) {
TimeTaken first = trail.get(0);
// If first entry is sub, then it's actually the last "end" as well
// otherwise, check end
@@ -133,48 +133,48 @@ public abstract class AbsTrans<ENV extends Env> implements TransStore { metric.total = (end - first.start) / 1000000f;
}
- if(sb==null) {
- for(TimeTaken tt : trail) {
+ if (sb==null) {
+ for (TimeTaken tt : trail) {
float ms = tt.millis();
- for(int i=0;i<flags.length;++i) {
- if(tt.flag == flags[i]) metric.buckets[i]+=ms;
+ for (int i=0;i<flags.length;++i) {
+ if (tt.flag == flags[i]) metric.buckets[i]+=ms;
}
}
- } else if(!lt.isLoggable()) {
+ } else if (!lt.isLoggable()) {
boolean first = true;
- for(TimeTaken tt : trail) {
+ for (TimeTaken tt : trail) {
float ms = tt.millis();
- for(int i=0;i<flags.length;++i) {
- if(tt.flag == flags[i]) metric.buckets[i]+=ms;
+ for (int i=0;i<flags.length;++i) {
+ if (tt.flag == flags[i]) metric.buckets[i]+=ms;
}
- if((tt.flag&ALWAYS)==ALWAYS) {
- if(first) first = false;
+ if ((tt.flag&ALWAYS)==ALWAYS) {
+ if (first) first = false;
else sb.append('/');
sb.append(tt.name);
}
}
} else {
Stack<Long> stack = new Stack<Long>();
- for(TimeTaken tt : trail) {
+ for (TimeTaken tt : trail) {
// Create Indentation based on SUB
- while(!stack.isEmpty() && tt.end()>stack.peek()) {
+ while (!stack.isEmpty() && tt.end()>stack.peek()) {
--indent;
stack.pop();
}
- for(int i=0;i<indent;++i) {
+ for (int i=0;i<indent;++i) {
sb.append(" ");
}
tt.output(sb);
sb.append('\n');
- if((tt.flag&SUB)==SUB) {
+ if ((tt.flag&SUB)==SUB) {
stack.push(tt.end());
++indent;
}
// Add time values to Metric
float ms = tt.millis();
- for(int i=0;i<flags.length;++i) {
- if(tt.flag == flags[i]) metric.buckets[i]+=ms;
+ for (int i=0;i<flags.length;++i) {
+ if (tt.flag == flags[i]) metric.buckets[i]+=ms;
}
}
}
@@ -200,7 +200,7 @@ public abstract class AbsTrans<ENV extends Env> implements TransStore { Object o;
try {
o = slot.get(state);
- } catch(ArrayIndexOutOfBoundsException e) {
+ } catch (ArrayIndexOutOfBoundsException e) {
// Env State Size has changed because of dynamic Object creation... Rare event, but needs to be covered
Object[] temp = ((StoreImpl) delegate).newTransState();
System.arraycopy(state, 0, temp, 0, state.length);
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java index 94f7d47b..6fbfacdb 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/BasicEnv.java @@ -86,9 +86,9 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX super(null, tags);
// props = new HashMap<>();
// String value;
-// for(int i=0;i<tags.length;++i) {
+// for (int i=0;i<tags.length;++i) {
// value = applet.getParameter(tags[i]);
-// if(value!=null) {
+// if (value!=null) {
// props.put(tags[i], value);
// }
// }
@@ -164,11 +164,11 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX case Env.REMOTE: sb.append("REMOTE "); break;
}
sb.append(name);
- if(flag != Env.CHECKPOINT) {
+ if (flag != Env.CHECKPOINT) {
sb.append(' ');
sb.append((end-start)/1000000f);
sb.append("ms");
- if(size>=0) {
+ if (size>=0) {
sb.append(" size: ");
sb.append(Long.toString(size));
}
@@ -185,11 +185,11 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX public Properties getProperties(String ... filter) {
Properties props = new Properties();
boolean yes;
- for(String key : existingStaticSlotNames()) {
- if(filter.length>0) {
+ for (String key : existingStaticSlotNames()) {
+ if (filter.length>0) {
yes = false;
- for(String f : filter) {
- if(key.startsWith(f)) {
+ for (String f : filter) {
+ if (key.startsWith(f)) {
yes = true;
break;
}
@@ -197,9 +197,9 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX } else {
yes = true;
}
- if(yes) {
+ if (yes) {
String value = getProperty(key);
- if(value!=null) {
+ if (value!=null) {
props.put(key, value);
}
}
@@ -242,7 +242,7 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX // @SuppressWarnings("unchecked")
// @Override
public <T> DataFactory<T> newDataFactory(Class<?>... classes) throws APIException {
-// if(String.class.isAssignableFrom(classes[0]))
+// if (String.class.isAssignableFrom(classes[0]))
// return (DataFactory<T>) new StringDF(this);
return new JAXBDF<T>(this,classes);
}
@@ -250,7 +250,7 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX // @SuppressWarnings("unchecked")
// @Override
public <T> DataFactory<T> newDataFactory(Schema schema, Class<?>... classes) throws APIException {
-// if(String.class.isAssignableFrom(classes[0]))
+// if (String.class.isAssignableFrom(classes[0]))
// return (DataFactory<T>) new StringDF(this);
return new JAXBDF<T>(this, schema, classes);
}
@@ -258,7 +258,7 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX // @SuppressWarnings("unchecked")
// @Override
public<T> DataFactory<T> newDataFactory(QName qName, Class<?> ... classes) throws APIException {
-// if(String.class.isAssignableFrom(classes[0]))
+// if (String.class.isAssignableFrom(classes[0]))
// return (DataFactory<T>) new StringDF(this);
return new JAXBDF<T>(this, qName, classes);
}
@@ -274,9 +274,9 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX }
public void loadFromSystemPropsStartsWith(String ... str) {
- for(String name : System.getProperties().stringPropertyNames()) {
- for(String s : str) {
- if(name.startsWith(s)) {
+ for (String name : System.getProperties().stringPropertyNames()) {
+ for (String s : str) {
+ if (name.startsWith(s)) {
setProperty(name, System.getProperty(name));
}
}
@@ -289,10 +289,10 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX */
public void loadToSystemPropsStartsWith(String ... str) {
String value;
- for(String name : existingStaticSlotNames()) {
- for(String s : str) {
- if(name.startsWith(s)) {
- if((value = getProperty(name))!=null)
+ for (String name : existingStaticSlotNames()) {
+ for (String s : str) {
+ if (name.startsWith(s)) {
+ if ((value = getProperty(name))!=null)
System.setProperty(name,value);
}
}
@@ -301,24 +301,24 @@ public class BasicEnv extends StoreImpl implements EnvJAXB, TransCreate<TransJAX public void loadPropFiles(String tag, ClassLoader classloader) throws IOException {
String propfiles = getProperty(tag);
- if(propfiles!=null) {
- for(String pf : Split.splitTrim(File.pathSeparatorChar, propfiles)) {
+ if (propfiles!=null) {
+ for (String pf : Split.splitTrim(File.pathSeparatorChar, propfiles)) {
InputStream is = classloader==null?null:classloader.getResourceAsStream(pf);
- if(is==null) {
+ if (is==null) {
File f = new File(pf);
- if(f.exists()) {
+ if (f.exists()) {
is = new FileInputStream(f);
}
}
- if(is!=null) {
+ if (is!=null) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String line;
- while((line=br.readLine())!=null) {
+ while ((line=br.readLine())!=null) {
line = line.trim();
- if(!line.startsWith("#")) {
+ if (!line.startsWith("#")) {
String[] tv = Split.splitTrim('=', line);
- if(tv.length==2) {
+ if (tv.length==2) {
setProperty(tv[0],tv[1]);
}
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java index c8adfc78..3fcbcf9e 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/JavaUtilLogTarget.java @@ -49,16 +49,16 @@ public class JavaUtilLogTarget implements LogTarget { }
public void log(Object ... msgs) {
- if(log.isLoggable(level)) {
+ if (log.isLoggable(level)) {
StringBuilder sb = new StringBuilder();
String msg;
- for(int i=0;i<msgs.length;++i) {
+ for (int i=0;i<msgs.length;++i) {
msg = msgs[i].toString();
- if(msg!=null && msg.length()>0) {
+ if (msg!=null && msg.length()>0) {
int sbl = sb.length();
- if(sbl>0) {
+ if (sbl>0) {
char last = sb.charAt(sbl-1);
- if(" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' ');
+ if (" (.".indexOf(last)<0 && "().".indexOf(msg.charAt(0))<0)sb.append(' ');
}
sb.append(msg);
}
@@ -69,10 +69,10 @@ public class JavaUtilLogTarget implements LogTarget { public void log(Throwable e, Object ... msgs) {
String str = e.getLocalizedMessage();
- if(str==null) {
+ if (str==null) {
str = e.getMessage();
}
- if(str==null) {
+ if (str==null) {
str = e.getClass().getName();
}
log.log(level,str,msgs);
@@ -83,7 +83,7 @@ public class JavaUtilLogTarget implements LogTarget { */
@Override
public void printf(String fmt, Object ... vars) {
- if(log.isLoggable(level)) {
+ if (log.isLoggable(level)) {
log.log(level,String.format(fmt,vars));
}
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java index 81d9c1b2..b144852a 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/impl/Log4JLogTarget.java @@ -61,7 +61,7 @@ public class Log4JLogTarget implements LogTarget { // @Override
public void log(Throwable e, Object... msgs) {
- if (log.isEnabledFor(level)) {
+ if (log.isEnabledFor (level)) {
StringBuilder sb = new StringBuilder();
String msg;
@@ -69,7 +69,7 @@ public class Log4JLogTarget implements LogTarget { e.printStackTrace(new PrintWriter(new StringBuilderWriter(sb)));
}
for (int i = 0; i < msgs.length; ++i) {
- if(msgs[i]!=null) {
+ if (msgs[i]!=null) {
msg = msgs[i].toString();
if (msg != null && msg.length() > 0) {
int sbl = sb.length();
@@ -92,7 +92,7 @@ public class Log4JLogTarget implements LogTarget { */
@Override
public void printf(String fmt, Object ... vars) {
- if(log.isEnabledFor(level)) {
+ if (log.isEnabledFor (level)) {
log.log(level,String.format(fmt,vars));
}
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java index dc7ee192..d140a6b8 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBDF.java @@ -152,7 +152,7 @@ public class JAXBDF<T> extends BaseDataFactory implements OldDataFactory<T>,IOOb try {
T t = jumar.unmarshal(env.debug(), input);
return new JAXBData<T>(primaryEnv, this, new JAXBStringifier<T>(jmar), new JAXBObjectifier<T>(jumar),t);
- } catch(JAXBException e) {
+ } catch (JAXBException e) {
throw new APIException(e);
}
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java index 38977a35..6d83aca4 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBData.java @@ -114,7 +114,7 @@ public final class JAXBData<T> implements Data<T>{ * @throws APIException
*/
public String asString(EnvJAXB env) throws APIException {
- if(dataAsString!=null) {
+ if (dataAsString!=null) {
return dataAsString;
} else {
return dataAsString = stringifier.stringify(env, dataAsObject);
@@ -131,7 +131,7 @@ public final class JAXBData<T> implements Data<T>{ */
// @Override
public String asString() throws APIException {
- if(dataAsString!=null) {
+ if (dataAsString!=null) {
return dataAsString;
} else {
return dataAsString = stringifier.stringify(creatingEnv, dataAsObject,options);
@@ -139,7 +139,7 @@ public final class JAXBData<T> implements Data<T>{ }
public Data<T> to(OutputStream os) throws APIException, IOException {
- if(dataAsString!=null) {
+ if (dataAsString!=null) {
os.write(dataAsString.getBytes());
} else if (stringifier instanceof IOStringifier){
((IOStringifier<T>)stringifier).stringify(creatingEnv, dataAsObject, os, options);
@@ -153,7 +153,7 @@ public final class JAXBData<T> implements Data<T>{ // @Override
public JAXBData<T> to(Writer writer) throws APIException, IOException {
- if(dataAsString!=null) {
+ if (dataAsString!=null) {
writer.write(dataAsString);
} else if (stringifier instanceof IOStringifier){
((IOStringifier<T>)stringifier).stringify(creatingEnv, dataAsObject, writer, options);
@@ -166,7 +166,7 @@ public final class JAXBData<T> implements Data<T>{ public InputStream getInputStream() throws APIException {
- if(dataAsString==null) {
+ if (dataAsString==null) {
dataAsString = stringifier.stringify(creatingEnv,dataAsObject,options);
}
return new ByteArrayInputStream(dataAsString.getBytes());
@@ -184,7 +184,7 @@ public final class JAXBData<T> implements Data<T>{ */
public T asObject(EnvJAXB env) throws APIException {
- if(dataAsObject !=null) {
+ if (dataAsObject !=null) {
return dataAsObject;
} else {
// Some Java compilers need two statements here
@@ -204,7 +204,7 @@ public final class JAXBData<T> implements Data<T>{ */
// @Override
public T asObject() throws APIException {
- if(dataAsObject !=null) {
+ if (dataAsObject !=null) {
return dataAsObject;
} else {
// Some Java compilers need two statements here
@@ -239,7 +239,7 @@ public final class JAXBData<T> implements Data<T>{ */
// @Override
public String toString() {
- if(dataAsString!=null) {
+ if (dataAsString!=null) {
return dataAsString;
} else {
try {
@@ -292,8 +292,8 @@ public final class JAXBData<T> implements Data<T>{ int count;
do {
count = input.read(b);
- if(count>0)output.write(b, 0, count);
- } while(count>=0);
+ if (count>0)output.write(b, 0, count);
+ } while (count>=0);
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java index 46c40ebb..524fc668 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBmar.java @@ -80,10 +80,10 @@ public class JAXBmar { }
public Marshaller get(boolean pretty, boolean fragment) throws JAXBException {
- if(pretty != p) {
+ if (pretty != p) {
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, p = pretty);
}
- if(fragment != f) {
+ if (fragment != f) {
m.setProperty(Marshaller.JAXB_FRAGMENT, f = fragment);
}
return m;
@@ -139,7 +139,7 @@ public class JAXBmar { Pool<PMarshaller> mp;
synchronized(pools) {
mp = pools.get(classes);
- if(mp==null) {
+ if (mp==null) {
pools.put(classes,mp = new Pool<PMarshaller>(new Creator(classes)));
}
}
@@ -165,7 +165,7 @@ public class JAXBmar { fragment = options.length>1?options[1]:this.fragment;
Pooled<PMarshaller> m = mpool.get(lt);
try {
- if(qname==null) {
+ if (qname==null) {
m.content.get(pretty,fragment).marshal(o, writer);
} else {
m.content.get(pretty,fragment).marshal(
@@ -185,7 +185,7 @@ public class JAXBmar { fragment = options.length>1?options[1]:this.fragment;
Pooled<PMarshaller> m = mpool.get(lt);
try {
- if(qname==null) {
+ if (qname==null) {
m.content.get(pretty,fragment).marshal(o, os);
} else {
m.content.get(pretty,fragment).marshal(
@@ -200,7 +200,7 @@ public class JAXBmar { public<O> O marshal(LogTarget lt, O o, Writer writer, Class<O> clss) throws JAXBException, APIException {
Pooled<PMarshaller> m = mpool.get(lt);
try {
- if(qname==null) {
+ if (qname==null) {
m.content.get(pretty,fragment).marshal(o, writer);
} else {
m.content.get(pretty,fragment).marshal(
@@ -216,7 +216,7 @@ public class JAXBmar { public<O> O marshal(LogTarget lt, O o, OutputStream os, Class<O> clss) throws JAXBException, APIException {
Pooled<PMarshaller> m = mpool.get(lt);
try {
- if(qname==null) {
+ if (qname==null) {
m.content.get(pretty,fragment).marshal(o, os);
} else {
m.content.get(pretty,fragment).marshal(
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java index fe3f0145..30345e7c 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/jaxb/JAXBumar.java @@ -85,7 +85,7 @@ public class JAXBumar { }
public Unmarshaller get(Schema schema) throws JAXBException {
- if(s != schema) {
+ if (s != schema) {
u.setSchema(s = schema);
}
return u;
@@ -135,7 +135,7 @@ public class JAXBumar { Pool<SUnmarshaller> mp;
synchronized(pools) {
mp = pools.get(classes);
- if(mp==null) {
+ if (mp==null) {
pools.put(classes,mp = new Pool<SUnmarshaller>(new Creator(classes)));
}
}
@@ -174,7 +174,7 @@ public class JAXBumar { @SuppressWarnings("unchecked")
public<O> O unmarshal(LogTarget env, String xml) throws JAXBException, APIException {
- if(xml==null) throw new JAXBException("Null Input for String unmarshal");
+ if (xml==null) throw new JAXBException("Null Input for String unmarshal");
Pooled<SUnmarshaller> s = mpool.get(env);
try {
return (O)s.content.get(schema).unmarshal(
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java index ae78918c..553d7ade 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Chrono.java @@ -107,17 +107,17 @@ public class Chrono { }
public static String utcStamp(Date date) {
- if(date==null)return "";
+ if (date==null)return "";
return utcFmt.format(date);
}
public static String utcStamp(GregorianCalendar gc) {
- if(gc==null)return "";
+ if (gc==null)return "";
return utcFmt.format(gc.getTime());
}
public static String utcStamp(XMLGregorianCalendar xgc) {
- if(xgc==null)return "";
+ if (xgc==null)return "";
return utcFmt.format(xgc.toGregorianCalendar().getTime());
}
@@ -126,17 +126,17 @@ public class Chrono { }
public static String dateStamp(GregorianCalendar gc) {
- if(gc == null)return "";
+ if (gc == null)return "";
return dateFmt.format(gc.getTime());
}
public static String dateStamp(Date date) {
- if(date == null)return "";
+ if (date == null)return "";
return dateFmt.format(date);
}
public static String dateStamp(XMLGregorianCalendar xgc) {
- if(xgc==null)return "";
+ if (xgc==null)return "";
return dateFmt.format(xgc.toGregorianCalendar().getTime());
}
@@ -172,7 +172,7 @@ public class Chrono { * @return
*/
public static String dateTime(GregorianCalendar gc) {
- if(gc == null)return "";
+ if (gc == null)return "";
TimeZone tz = gc.getTimeZone();
int tz1 = (tz.getRawOffset()+tz.getDSTSavings())/0x8CA0;
int tz1abs = Math.abs(tz1);
@@ -251,7 +251,7 @@ public class Chrono { }
public static GregorianCalendar firstMomentOfDay(GregorianCalendar begin) {
- if(begin==null)begin = new GregorianCalendar();
+ if (begin==null)begin = new GregorianCalendar();
begin.set(GregorianCalendar.HOUR, 0);
begin.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);
begin.set(GregorianCalendar.MINUTE, 0);
@@ -261,7 +261,7 @@ public class Chrono { }
public static GregorianCalendar lastMomentOfDay(GregorianCalendar end) {
- if(end==null)end = new GregorianCalendar();
+ if (end==null)end = new GregorianCalendar();
end.set(GregorianCalendar.HOUR, 11);
end.set(GregorianCalendar.MINUTE, 59);
end.set(GregorianCalendar.SECOND, 59);
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java index 97d9de99..b9191c00 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/DoubleOutputStream.java @@ -43,7 +43,7 @@ public class DoubleOutputStream extends OutputStream { */
@Override
public void write(int c) throws IOException {
- for(OutputStream os : oss) {
+ for (OutputStream os : oss) {
os.write(c);
}
}
@@ -58,14 +58,14 @@ public class DoubleOutputStream extends OutputStream { */
@Override
public void write(byte bbuf[], int off, int len) throws IOException {
- for(OutputStream os : oss) {
+ for (OutputStream os : oss) {
os.write(bbuf,off,len);
}
}
@Override
public void write(byte[] b) throws IOException {
- for(OutputStream os : oss) {
+ for (OutputStream os : oss) {
os.write(b);
}
}
@@ -75,8 +75,8 @@ public class DoubleOutputStream extends OutputStream { */
@Override
public void close() throws IOException {
- for(int i=0;i<oss.length;++i) {
- if(close[i]) {
+ for (int i=0;i<oss.length;++i) {
+ if (close[i]) {
oss[i].close();
}
}
@@ -87,7 +87,7 @@ public class DoubleOutputStream extends OutputStream { */
@Override
public void flush() throws IOException {
- for(OutputStream os : oss) {
+ for (OutputStream os : oss) {
os.flush();
}
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java index 759a8c8b..3d6416cd 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/RefreshableThreadObject.java @@ -87,7 +87,7 @@ public class RefreshableThreadObject<T extends Creatable<T>> { public T get(Env env) throws APIException {
Thread t = Thread.currentThread();
T obj = objs.get(t);
- if(obj==null || refreshed>obj.created()) {
+ if (obj==null || refreshed>obj.created()) {
try {
obj = cnst.newInstance(new Object[]{env});
} catch (InvocationTargetException e) {
@@ -96,7 +96,7 @@ public class RefreshableThreadObject<T extends Creatable<T>> { throw new APIException(e);
}
T destroyMe = objs.put(t,obj);
- if(destroyMe!=null) {
+ if (destroyMe!=null) {
destroyMe.destroy(env);
}
}
@@ -118,7 +118,7 @@ public class RefreshableThreadObject<T extends Creatable<T>> { */
public void remove(Env env) {
T obj = objs.remove(Thread.currentThread());
- if(obj!=null)
+ if (obj!=null)
obj.destroy(env);
}
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java index 4069c329..b0da8ba2 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/Split.java @@ -33,20 +33,20 @@ public class Split { private static final String[] BLANK = new String[0];
public static String[] split(char c, String value) {
- if(value==null) {
+ if (value==null) {
return BLANK;
}
// Count items to preallocate Array (memory alloc is more expensive than counting twice)
int count,idx;
- for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);
+ for (count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);
String[] rv = new String[count];
- if(count==1) {
+ if (count==1) {
rv[0]=value;
} else {
int last=0;
count=-1;
- for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {
+ for (idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {
rv[++count]=value.substring(last,idx);
last = ++idx;
}
@@ -56,19 +56,19 @@ public class Split { }
public static String[] splitTrim(char c, String value) {
- if(value==null) {
+ if (value==null) {
return BLANK;
}
// Count items to preallocate Array (memory alloc is more expensive than counting twice)
int count,idx;
- for(count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);
+ for (count=1,idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,++idx),++count);
String[] rv = new String[count];
- if(count==1) {
+ if (count==1) {
rv[0]=value.trim();
} else {
int last=0;
count=-1;
- for(idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {
+ for (idx=value.indexOf(c);idx>=0;idx=value.indexOf(c,idx)) {
rv[++count]=value.substring(last,idx).trim();
last = ++idx;
}
@@ -78,19 +78,19 @@ public class Split { }
public static String[] splitTrim(char c, String value, int size) {
- if(value==null) {
+ if (value==null) {
return BLANK;
}
int idx;
String[] rv = new String[size];
- if(size==1) {
+ if (size==1) {
rv[0]=value.trim();
} else {
int last=0;
int count=-1;
size-=2;
- for(idx=value.indexOf(c);idx>=0 && count<size;idx=value.indexOf(c,idx)) {
+ for (idx=value.indexOf(c);idx>=0 && count<size;idx=value.indexOf(c,idx)) {
rv[++count]=value.substring(last,idx).trim();
last = ++idx;
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/util/StringBuilderOutputStream.java b/misc/env/src/main/java/org/onap/aaf/misc/env/util/StringBuilderOutputStream.java index c512b09a..31d4bf3c 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/util/StringBuilderOutputStream.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/util/StringBuilderOutputStream.java @@ -114,7 +114,7 @@ public class StringBuilderOutputStream extends OutputStream { if (csq == null) {
write("null");
} else {
- for(int i = 0;i<csq.length();++i) {
+ for (int i = 0;i<csq.length();++i) {
buf.append(csq.charAt(i));
}
}
diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java index 914a01b0..9feaf3ef 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_Log4JLogTargetTest.java @@ -48,7 +48,7 @@ public class JU_Log4JLogTargetTest { MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(Logger.class);
when(Logger.getLogger("Info")).thenReturn(log);
- when(log.isEnabledFor(Level.DEBUG)).thenReturn(false);
+ when(log.isEnabledFor (Level.DEBUG)).thenReturn(false);
}
@Test
diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java index 353261a0..582c750c 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InJson.java @@ -32,7 +32,7 @@ public class InJson implements Parse<Reader, State> { public Parsed<State> parse(Reader r, Parsed<State> parsed) throws ParseException { // First things first, if there's a "leftover" event, process that immediately State state = (State)parsed.state; - if(state.unsent > 0) { + if (state.unsent > 0) { parsed.event = state.unsent; state.unsent = 0; return parsed; @@ -45,13 +45,13 @@ public class InJson implements Parse<Reader, State> { boolean go = true; try { // Gather data from Reader, looking for special characters when not in Quotes - while(go && (ch=r.read())>=0) { - if(state.braces>=0 || ch==Parse.START_OBJ) { // ignore garbage/whitespace before content + while (go && (ch=r.read())>=0) { + if (state.braces>=0 || ch==Parse.START_OBJ) { // ignore garbage/whitespace before content c=(char)ch; // Character is a quote. - if(c=='"') { - if(inQuotes) { - if(escaped) { // if escaped Quote, add to data. + if (c=='"') { + if (inQuotes) { + if (escaped) { // if escaped Quote, add to data. sb.append(c); escaped = false; } else { @@ -62,9 +62,9 @@ public class InJson implements Parse<Reader, State> { inQuotes = true; } } else { // Not a Quote - if(inQuotes) { - if(c=='\\') { - if(escaped) { + if (inQuotes) { + if (c=='\\') { + if (escaped) { sb.append("\\\\"); escaped = false; } else { @@ -80,7 +80,7 @@ public class InJson implements Parse<Reader, State> { parsed.isString = false; break; case Parse.START_OBJ: - if(state.braces++ == 0) { + if (state.braces++ == 0) { parsed.event = START_DOC; state.unsent = c; } else { @@ -89,7 +89,7 @@ public class InJson implements Parse<Reader, State> { go = false; break; case Parse.END_OBJ: - if(--state.braces == 0) { + if (--state.braces == 0) { parsed.event = c; state.unsent = END_DOC; } else { @@ -99,7 +99,7 @@ public class InJson implements Parse<Reader, State> { break; // These three end the data gathering, and send it along with the event that is ending the data gathering case Parse.NEXT: - if(parsed.name.startsWith("__")) { + if (parsed.name.startsWith("__")) { parsed.event = Parse.ATTRIB; parsed.name = parsed.name.substring(2); } else { diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java index 91b7c57d..175a2aa2 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/InXML.java @@ -51,13 +51,13 @@ public class InXML implements Parse<Reader, State> { State state = parsed.state; // OK, before anything else, see if there is leftover processing, if so, do it! - if(state.unevaluated!=null) { + if (state.unevaluated!=null) { DerTag dt = state.unevaluated; state.unevaluated = null; - if(!state.greatExp.eval(parsed, dt))return parsed; + if (!state.greatExp.eval(parsed, dt))return parsed; } - if(state.hasAttributes()) { + if (state.hasAttributes()) { Prop prop = state.pop(); parsed.event = Parse.ATTRIB; parsed.name = prop.tag; @@ -73,14 +73,14 @@ public class InXML implements Parse<Reader, State> { boolean go = true; try { - while(go && (ch=r.read())>=0) { + while (go && (ch=r.read())>=0) { c = (char)ch; - if(c == '"') { - if(state.greatExp instanceof LeafExpectations) { // within a set of Tags, make a Quote + if (c == '"') { + if (state.greatExp instanceof LeafExpectations) { // within a set of Tags, make a Quote sb.append(c); } else { - if(inQuotes) { - if(escaped) { + if (inQuotes) { + if (escaped) { sb.append('\\'); sb.append(c); escaped = false; @@ -92,11 +92,11 @@ public class InXML implements Parse<Reader, State> { inQuotes = true; } } - } else if(inQuotes) { + } else if (inQuotes) { sb.append(c); - } else if(c=='&') { + } else if (c=='&') { XmlEscape.xmlEscape(sb,r); - } else if(c=='\\') { + } else if (c=='\\') { escaped=true; } else { switch(c) { @@ -106,9 +106,9 @@ public class InXML implements Parse<Reader, State> { break; default: // don't add Whitespace to start of SB... saves removing later - if(sb.length()>0) { + if (sb.length()>0) { sb.append(c); - } else if(!Character.isWhitespace(c)) { + } else if (!Character.isWhitespace(c)) { sb.append(c); } } @@ -142,16 +142,16 @@ public class InXML implements Parse<Reader, State> { String tag = null; try { - if((ch = r.read())<0) throw new ParseException("Reader content ended before complete"); - if(ch=='?') { + if ((ch = r.read())<0) throw new ParseException("Reader content ended before complete"); + if (ch=='?') { isXmlInfo = true; } // TODO Check for !-- comments do { c=(char)ch; - if(c=='"') { - if(inQuotes) { - if(escaped) { + if (c=='"') { + if (inQuotes) { + if (escaped) { sb.append(c); escaped = false; } else { @@ -160,7 +160,7 @@ public class InXML implements Parse<Reader, State> { } else { inQuotes = true; } - } else if(inQuotes) { + } else if (inQuotes) { sb.append(c); } else { switch(c) { @@ -184,13 +184,13 @@ public class InXML implements Parse<Reader, State> { // sb.setLength(0); // break; case '?': - if(!isXmlInfo)sb.append(c); + if (!isXmlInfo)sb.append(c); break; default: sb.append(c); } } - } while(go && (ch=r.read())>=0); + } while (go && (ch=r.read())>=0); } catch (IOException e) { throw new ParseException(e); } @@ -198,14 +198,14 @@ public class InXML implements Parse<Reader, State> { } private void endField(String tag, StringBuilder sb) { - if(name==null) { + if (name==null) { name = sb.toString(); sb.setLength(0); } else { String value = sb.toString(); sb.setLength(0); - if(tag !=null && value != null) { - if(props==null)props = new ArrayList<>(); + if (tag !=null && value != null) { + if (props==null)props = new ArrayList<>(); props.add(new Prop(tag,value)); } } @@ -217,7 +217,7 @@ public class InXML implements Parse<Reader, State> { sb.append(" Tag\n"); sb.append(" Name: "); sb.append(name); - if(props!=null) for(Prop p : props) { + if (props!=null) for (Prop p : props) { sb.append("\n "); sb.append(p.tag); sb.append("=\""); @@ -250,7 +250,7 @@ public class InXML implements Parse<Reader, State> { } public void push(Prop prop) { - if(attribs==null) { + if (attribs==null) { attribs = new ArrayList<>(); idx = 0; } @@ -259,9 +259,9 @@ public class InXML implements Parse<Reader, State> { public Prop pop() { Prop rv = null; - if(attribs!=null) { + if (attribs!=null) { rv = attribs.get(idx++); - if(idx>=attribs.size())attribs = null; + if (idx>=attribs.size())attribs = null; } return rv; } @@ -282,8 +282,8 @@ public class InXML implements Parse<Reader, State> { // Recursively look back for any namespaces protected Map<String,String> getNS() { - if(ns!=null)return ns; - if(prev!=null) { + if (ns!=null)return ns; + if (prev!=null) { return prev.getNS(); } return null; @@ -291,47 +291,47 @@ public class InXML implements Parse<Reader, State> { private void addNS(Prop prop) { Map<String,String> existingNS = getNS(); - if(ns==null)ns = new HashMap<>(); + if (ns==null)ns = new HashMap<>(); // First make a copy of previous NSs so that we have everything we need, but can overwrite, if necessary - if(existingNS!=null && ns!=existingNS) { + if (existingNS!=null && ns!=existingNS) { ns.putAll(ns); } ns.put(prop.tag, prop.value); } private JaxInfo getDerived(State state, JaxInfo ji, DerTag derTag) throws ParseException { - if(derTag==null)return ji; + if (derTag==null)return ji; List<Prop> props = derTag.props; Prop derived = null; - if(props!=null) { + if (props!=null) { // Load Namespaces (if any) - for(Prop prop : props) { - if(prop.tag.startsWith("xmlns:")) { + for (Prop prop : props) { + if (prop.tag.startsWith("xmlns:")) { addNS(prop); } } - for(Prop prop : props) { - if(prop.tag.endsWith(":type")) { + for (Prop prop : props) { + if (prop.tag.endsWith(":type")) { int idx = prop.tag.indexOf(':'); String potentialNS = "xmlns:"+prop.tag.substring(0,idx); Map<String,String> ns = getNS(); boolean noNamespace = false; - if(ns==null) { + if (ns==null) { noNamespace = true; } else { String nsVal = ns.get(potentialNS); - if(nsVal==null) noNamespace = true; + if (nsVal==null) noNamespace = true; else { derived = new Prop(Parsed.EXTENSION_TAG,prop.value); state.push(derived); } } - if(noNamespace) { + if (noNamespace) { throw new ParseException(prop.tag + " utilizes an invalid Namespace prefix"); } - } else if(!prop.tag.startsWith("xmlns")) { + } else if (!prop.tag.startsWith("xmlns")) { state.push(prop); } } @@ -348,10 +348,10 @@ public class InXML implements Parse<Reader, State> { // @Override public boolean eval(Parsed<State> parsed, DerTag derTag) throws ParseException { - if(derTag.isXmlInfo) { + if (derTag.isXmlInfo) { parsed.event = START_DOC; - } else if(ji.name.equals(derTag.name)) { - if(derTag.isEndTag) { + } else if (ji.name.equals(derTag.name)) { + if (derTag.isEndTag) { parsed.event = END_DOC; parsed.state.greatExp = prev; } else { @@ -374,22 +374,22 @@ public class InXML implements Parse<Reader, State> { // @Override public boolean eval(Parsed<State> parsed, DerTag derTag) throws ParseException { - if(derTag.isEndTag && ji.name.equals(derTag.name)) { + if (derTag.isEndTag && ji.name.equals(derTag.name)) { parsed.state.greatExp = prev; parsed.event = END_OBJ; - if(printName)parsed.name = ji.name; + if (printName)parsed.name = ji.name; } else { //Standard Members - for(JaxInfo memb : ji.members) { - if(memb.name.equals(derTag.name)) { + for (JaxInfo memb : ji.members) { + if (memb.name.equals(derTag.name)) { parsed.name = memb.name; - if(memb.isArray) { + if (memb.isArray) { parsed.state.unevaluated = derTag; // evaluate within Array Context parsed.event = START_ARRAY; parsed.state.greatExp = new ArrayExpectations(parsed.state,memb,this); return false; - } else if(memb.isObject()) { - if(derTag.isEndTag) { + } else if (memb.isObject()) { + if (derTag.isEndTag) { throw new ParseException("Unexpected End Tag </" + derTag.name + '>'); } else { parsed.event = START_OBJ; @@ -398,7 +398,7 @@ public class InXML implements Parse<Reader, State> { return false; } } else { // a leaf - if(derTag.isEndTag) { + if (derTag.isEndTag) { throw new ParseException("Misplaced End Tag </" + parsed.name + '>'); } else { parsed.state.greatExp = new LeafExpectations(parsed.state,memb, this); @@ -421,7 +421,7 @@ public class InXML implements Parse<Reader, State> { // @Override public boolean eval(Parsed<State> parsed, DerTag derTag) throws ParseException { - if(ji.name.equals(derTag.name) && derTag.isEndTag) { + if (ji.name.equals(derTag.name) && derTag.isEndTag) { parsed.event = NEXT; parsed.isString = ji.isString; parsed.state.greatExp = prev; @@ -435,18 +435,18 @@ public class InXML implements Parse<Reader, State> { private static class ArrayExpectations extends GreatExpectations { public ArrayExpectations(State state, JaxInfo ji, GreatExpectations prev) throws ParseException { super(state, ji, prev,null); - if(state.arrayInfo==null)state.arrayInfo=new Stack<ArrayState>(); + if (state.arrayInfo==null)state.arrayInfo=new Stack<ArrayState>(); state.arrayInfo.push(new ArrayState()); } // @Override public boolean eval(Parsed<State> parsed, DerTag derTag) throws ParseException { - if(ji.name.equals(derTag.name) && !derTag.isEndTag) { - if(ji.isObject()) { - if(derTag.isEndTag) { + if (ji.name.equals(derTag.name) && !derTag.isEndTag) { + if (ji.isObject()) { + if (derTag.isEndTag) { throw new ParseException("Unexpected End Tag </" + derTag.name + '>'); } else { ArrayState ai = parsed.state.arrayInfo.peek(); - if(ai.firstObj || ai.didNext) { + if (ai.firstObj || ai.didNext) { ai.firstObj = false; ai.didNext = false; parsed.event = START_OBJ; @@ -459,7 +459,7 @@ public class InXML implements Parse<Reader, State> { } } } else { // a leave - if(derTag.isEndTag) { + if (derTag.isEndTag) { throw new ParseException("Misplaced End Tag </" + parsed.name + '>'); } else { parsed.state.greatExp = new LeafExpectations(parsed.state, ji, this); diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java index edc5f787..d209f02f 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxInfo.java @@ -65,22 +65,22 @@ public class JaxInfo { public int getType() { - if(isArray)return ARRAY; - else if(members!=null)return OBJECT; + if (isArray)return ARRAY; + else if (members!=null)return OBJECT; return DATA; } public JaxInfo getDerived(String derivedName) { JaxInfo derived; // Lazy Instantiation - if(extensions == null) { + if (extensions == null) { extensions = new HashMap<>(); derived = null; } else { derived = extensions.get(derivedName); } - if(derived == null) { + if (derived == null) { //TODO for the moment, Classes are in same package Package pkg = clss.getPackage(); try { @@ -95,8 +95,8 @@ public class JaxInfo { } public static JaxInfo get(JaxInfo[] fields, String name) { - for(JaxInfo f : fields) { - if(name.equals(f.name)) return f; + for (JaxInfo f : fields) { + if (name.equals(f.name)) return f; } return null; } @@ -128,7 +128,7 @@ public class JaxInfo { */ public static JaxInfo build(Class<?> cls, String ... rootNns) throws SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException { String defaultNS; - if(rootNns.length>0 && rootNns[0]!=null) { + if (rootNns.length>0 && rootNns[0]!=null) { defaultNS = rootNns[0]; } else { Package pkg = cls.getPackage(); @@ -136,15 +136,15 @@ public class JaxInfo { defaultNS = xs==null?"":xs.namespace(); } String name; - if(rootNns.length>1) { + if (rootNns.length>1) { name = rootNns[1]; } else { XmlRootElement xre = cls.getAnnotation(XmlRootElement.class); - if(xre!=null) { + if (xre!=null) { name = xre.name(); } else { XmlType xt = cls.getAnnotation(XmlType.class); - if(xt!=null) { + if (xt!=null) { name=xt.name(); } else { throw new ParseException("Need a JAXB Object with XmlRootElement, or stipulate in parms"); @@ -162,10 +162,10 @@ public class JaxInfo { Class<?> cls = clazz; // Build up Method names from JAXB Annotations XmlType xt; - while((xt = cls.getAnnotation(XmlType.class))!=null) { - if(fields==null)fields = new ArrayList<>(); - for(String field : xt.propOrder()) { - if("".equals(field)) break; // odd bug. "" returned when no fields exist, rather than empty array + while ((xt = cls.getAnnotation(XmlType.class))!=null) { + if (fields==null)fields = new ArrayList<>(); + for (String field : xt.propOrder()) { + if ("".equals(field)) break; // odd bug. "" returned when no fields exist, rather than empty array Field rf = cls.getDeclaredField(field); Class<?> ft = rf.getType(); @@ -175,27 +175,27 @@ public class JaxInfo { String namespace = defaultNS; XmlElement xe = rf.getAnnotation(XmlElement.class); - if(xe!=null) { + if (xe!=null) { xmlName=xe.name(); required = xe.required(); nillable = false; - if(DEFAULT.equals(xmlName)) { + if (DEFAULT.equals(xmlName)) { xmlName = field; } namespace = xe.namespace(); - if(DEFAULT.equals(namespace)) { + if (DEFAULT.equals(namespace)) { namespace = defaultNS; } } // If object is a List, then it is possible multiple, per XML/JAXB evaluation - if(ft.isAssignableFrom(List.class)) { + if (ft.isAssignableFrom(List.class)) { Type t = rf.getGenericType(); String classname = t.toString(); int start = classname.indexOf('<'); int end = classname.indexOf('>'); Class<?> genClass = Class.forName(classname.substring(start+1, end)); xe = genClass.getAnnotation(XmlElement.class); - if(xe!=null && !DEFAULT.equals(xe.namespace())) { + if (xe!=null && !DEFAULT.equals(xe.namespace())) { namespace = xe.namespace(); } // add recursed recursed member, marked as array @@ -208,7 +208,7 @@ public class JaxInfo { } cls = cls.getSuperclass(); }; - if(fields!=null) { + if (fields!=null) { JaxInfo[] rv = new JaxInfo[fields.size()]; fields.toArray(rv); return rv; @@ -219,17 +219,17 @@ public class JaxInfo { public StringBuilder dump(StringBuilder sb, int idx) { - for(int i=0;i<idx;++i)sb.append(' '); + for (int i=0;i<idx;++i)sb.append(' '); sb.append("Field "); sb.append(name); sb.append(" ["); sb.append(clss.getName()); sb.append("] "); - if(isArray)sb.append(" (array)"); - if(required)sb.append(" (required)"); - if(nillable)sb.append(" (nillable)"); - if(members!=null) { - for(JaxInfo f : members) { + if (isArray)sb.append(" (array)"); + if (required)sb.append(" (required)"); + if (nillable)sb.append(" (nillable)"); + if (members!=null) { + for (JaxInfo f : members) { sb.append('\n'); f.dump(sb,idx+2); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxSet.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxSet.java index 6a779fb8..2d7af059 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxSet.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/JaxSet.java @@ -45,11 +45,11 @@ public class JaxSet<T> { members = new TreeMap<>(); XmlType xmltype = cls.getAnnotation(XmlType.class); Class<?> paramType[] = new Class[] {String.class}; - for(String str : xmltype.propOrder()) { + for (String str : xmltype.propOrder()) { try { String setName = "set" + Character.toUpperCase(str.charAt(0)) + str.subSequence(1, str.length()); Method meth = cls.getMethod(setName,paramType ); - if(meth!=null) { + if (meth!=null) { members.put(str, new Setter<T>(meth) { public void set(T o, Object t) throws ParseException { try { @@ -78,7 +78,7 @@ public class JaxSet<T> { synchronized(jsets) { @SuppressWarnings("unchecked") JaxSet<X> js = (JaxSet<X>)jsets.get(cls); - if(js == null) { + if (js == null) { jsets.put(cls, js = new JaxSet<>(cls)); } return js; diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java index 5e03ac91..6ff627b9 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Ladder.java @@ -55,7 +55,7 @@ public class Ladder<T> { public void top() { rung = struts.length-1; - while(rung>0 && struts[rung]==null)--rung; + while (rung>0 && struts[rung]==null)--rung; } public int howHigh() { @@ -63,7 +63,7 @@ public class Ladder<T> { } public void jumpTo(int rung) { - if(rung>=struts.length) { + if (rung>=struts.length) { Object[] temp = new Object[init_size*((rung/init_size)+1)]; System.arraycopy(struts, 0, temp, 0, struts.length); struts = temp; @@ -83,7 +83,7 @@ public class Ladder<T> { public void ascend() { ++rung; - if(rung>=struts.length) { + if (rung>=struts.length) { Object[] temp = new Object[struts.length+init_size]; System.arraycopy(struts, 0, temp, 0, struts.length); struts = temp; diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java index 4b8d2bf3..3729d1e3 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Marshal.java @@ -59,7 +59,7 @@ public abstract class Marshal<T> implements Parse<T, Marshal.State> { @Override public Void next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return null; diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java index 2716c8be..4fb52d86 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJax.java @@ -35,8 +35,8 @@ public class OutJax extends Out { public <IN,S> void extract(IN in, Writer writer, Parse<IN, S> parse, boolean... options) throws IOException, ParseException { Parsed<S> p = parse.newParsed(); JaxEval je = this.jaxEval; - while((p = parse.parse(in,p.reuse())).valid()) { - if(je==null)throw new ParseException("Incomplete content"); + while ((p = parse.parse(in,p.reuse())).valid()) { + if (je==null)throw new ParseException("Incomplete content"); je = je.eval(p); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java index d0a26784..6c868378 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutJson.java @@ -33,7 +33,7 @@ public class OutJson extends Out { public<IN,S> void extract(IN in, Writer writer, Parse<IN, S> prs, boolean ... options) throws IOException, ParseException { Parsed<S> p = prs.newParsed(); IndentPrintWriter ipw; - if(options.length>0 && options[0]) { // is Pretty + if (options.length>0 && options[0]) { // is Pretty ipw = writer instanceof IndentPrintWriter?(IndentPrintWriter)writer:new IndentPrintWriter(writer); writer = ipw; } else { @@ -47,13 +47,13 @@ public class OutJson extends Out { char afterName=0, beforeName=0, maybe = 0, prev=0; int count = 0; - while((p = prs.parse(in,p.reuse())).valid()) { + while ((p = prs.parse(in,p.reuse())).valid()) { ++count; switch(p.event) { case 1: continue; case 2: - if(count==2) { // it's empty, write open/close on it's own + if (count==2) { // it's empty, write open/close on it's own writer.append('{'); writer.append('}'); } @@ -61,7 +61,7 @@ public class OutJson extends Out { return; case '{': afterName = '{'; - if(jsonLevel.peek().printObjectName) { + if (jsonLevel.peek().printObjectName) { print = true; } else { // don't print names on first print=false; @@ -70,7 +70,7 @@ public class OutJson extends Out { jsonLevel.push(new LevelStack(true)); break; case '}': - if(p.hasData()) { // if we have data, we print that, so may need to prepend a comma. + if (p.hasData()) { // if we have data, we print that, so may need to prepend a comma. maybe = jsonLevel.peek().listItem(); } else { // No data means just print, p.name = ""; // XML tags come through with names, but no data @@ -81,7 +81,7 @@ public class OutJson extends Out { break; case '[': afterName = p.event; - if((prev==',' && !hadData) || prev==']')maybe=','; + if ((prev==',' && !hadData) || prev==']')maybe=','; else maybe = jsonLevel.peek().listItem(); jsonLevel.push(new LevelStack(false)); @@ -89,8 +89,8 @@ public class OutJson extends Out { break; case ']': afterName = p.event; - if(p.hasData()) { - if(prev==',' && !hadData)maybe=','; + if (p.hasData()) { + if (prev==',' && !hadData)maybe=','; else maybe = jsonLevel.peek().listItem(); } else { p.name = ""; // XML tags come through with names, but no data @@ -101,7 +101,7 @@ public class OutJson extends Out { break; case 3: case ',': - if(!p.hasData()) { + if (!p.hasData()) { p.isString=false; print=false; } else { @@ -113,36 +113,36 @@ public class OutJson extends Out { print = true; } - if(maybe!=0) { - if(ipw==null)writer.append(maybe); + if (maybe!=0) { + if (ipw==null)writer.append(maybe); else ipw.println(maybe); maybe = 0; } - if(beforeName!=0) { - if(ipw==null)writer.append(beforeName); + if (beforeName!=0) { + if (ipw==null)writer.append(beforeName); else ipw.println(beforeName); beforeName = 0; } - if(print) { - if(p.hasName()) { + if (print) { + if (p.hasName()) { writer.append('"'); - if(p.event==3)writer.append("__"); + if (p.event==3)writer.append("__"); writer.append(p.name); writer.append("\":"); } - if(p.hasData()) { - if(p.isString) { + if (p.hasData()) { + if (p.isString) { writer.append('"'); escapedWrite(writer, p.sb); writer.append('"'); - } else if(p.sb.length()>0) { + } else if (p.sb.length()>0) { writer.append(p.sb); } } } - if(afterName!=0) { - if(ipw==null)writer.append(afterName); + if (afterName!=0) { + if (ipw==null)writer.append(afterName); else { switch(afterName) { case '{': @@ -155,7 +155,7 @@ public class OutJson extends Out { ipw.print(afterName); break; case ']': - if(prev=='}' || prev==',')ipw.println(); + if (prev=='}' || prev==',')ipw.println(); ipw.dec(); ipw.print(afterName); break; @@ -170,7 +170,7 @@ public class OutJson extends Out { afterName = 0; } - if(ipw!=null) { + if (ipw!=null) { switch(p.event) { case '[': ipw.inc(); @@ -187,11 +187,11 @@ public class OutJson extends Out { private void escapedWrite(Writer writer, StringBuilder sb) throws IOException { char c; - for(int i=0;i<sb.length();++i) { + for (int i=0;i<sb.length();++i) { switch(c=sb.charAt(i)) { case '\\': writer.append(c); - if(i<sb.length()) { + if (i<sb.length()) { c=sb.charAt(++i); writer.append(c); } @@ -221,7 +221,7 @@ public class OutJson extends Out { } public char listItem() { - if(first_n_List) { + if (first_n_List) { first_n_List=false; return 0; } else { diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutRaw.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutRaw.java index babf53de..f07498b3 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutRaw.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutRaw.java @@ -30,7 +30,7 @@ public class OutRaw extends Out{ public<IN,S> void extract(IN in, Writer writer, Parse<IN,S> prs, boolean ... options) throws IOException, ParseException { Parsed<S> p = prs.newParsed(); - while((p = prs.parse(in,p.reuse())).valid()) { + while ((p = prs.parse(in,p.reuse())).valid()) { writer.append(p.toString()); writer.append('\n'); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java index a887cb96..6472c88e 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/OutXML.java @@ -43,9 +43,9 @@ public class OutXML extends Out{ public OutXML(String root, String ... params) { this.root = root; props = new ArrayList<>(); - for(String p : params) { + for (String p : params) { String[] tv=p.split("="); - if(tv.length==2) + if (tv.length==2) props.add(new Prop(tv[0],tv[1])); } } @@ -71,8 +71,8 @@ public class OutXML extends Out{ boolean pretty = (options.length>0&&options[0]); IndentPrintWriter ipw; - if(pretty) { - if(writer instanceof IndentPrintWriter) { + if (pretty) { + if (writer instanceof IndentPrintWriter) { ipw = (IndentPrintWriter)writer; } else { writer = ipw = new IndentPrintWriter(writer); @@ -82,19 +82,19 @@ public class OutXML extends Out{ } boolean closeTag = false; Level level = new Level(null); - while((p = prs.parse(in,p.reuse())).valid()) { - if(!p.hasName() && level.multi!=null) { + while ((p = prs.parse(in,p.reuse())).valid()) { + if (!p.hasName() && level.multi!=null) { p.name=level.multi; } - if(closeTag && p.event!=Parse.ATTRIB) { + if (closeTag && p.event!=Parse.ATTRIB) { writer.append('>'); - if(pretty)writer.append('\n'); + if (pretty)writer.append('\n'); closeTag = false; } switch(p.event) { case Parse.START_DOC: - if(!(options.length>1&&options[1])) // if not a fragment, print XML Info data - if(pretty)ipw.println(XML_INFO); + if (!(options.length>1&&options[1])) // if not a fragment, print XML Info data + if (pretty)ipw.println(XML_INFO); else writer.append(XML_INFO); break; case Parse.END_DOC: @@ -102,21 +102,21 @@ public class OutXML extends Out{ case Parse.START_OBJ: stack.push(level); level = new Level(level); - if(p.hasName()) { + if (p.hasName()) { closeTag = tag(writer,level.sbw,pretty,pretty,p.name,null); - } else if(root!=null && stack.size()==1) { // first Object + } else if (root!=null && stack.size()==1) { // first Object closeTag = tag(writer,level.sbw,pretty,pretty,root,null); // Write Root Props - for(Prop prop : props) { + for (Prop prop : props) { attrib(writer,pretty,prop.tag, prop.value,level); } } - if(pretty)ipw.inc(); + if (pretty)ipw.inc(); break; case Parse.END_OBJ: - if(p.hasData()) + if (p.hasData()) closeTag = tag(writer,writer,pretty,false,p.name, XmlEscape.convert(p.sb)); - if(pretty)ipw.dec(); + if (pretty)ipw.dec(); writer.append(level.sbw.getBuffer()); level = stack.pop(); break; @@ -124,16 +124,16 @@ public class OutXML extends Out{ level.multi = p.name; break; case Parse.END_ARRAY: - if(p.hasData()) + if (p.hasData()) closeTag = tag(writer,writer,pretty,false, p.name, XmlEscape.convert(p.sb)); level.multi=null; break; case Parse.ATTRIB: - if(p.hasData()) + if (p.hasData()) attrib(writer,pretty,p.name, XmlEscape.convert(p.sb), level); break; case Parse.NEXT: - if(p.hasData()) + if (p.hasData()) closeTag = tag(writer,writer,pretty, false,p.name, XmlEscape.convert(p.sb)); break; } @@ -156,15 +156,15 @@ public class OutXML extends Out{ public boolean hasPrinted(String ns, String value, boolean create) { boolean rv = false; - if(nses==null) { - if(prev!=null)rv = prev.hasPrinted(ns, value, false); + if (nses==null) { + if (prev!=null)rv = prev.hasPrinted(ns, value, false); } else { String v = nses.get(ns); return value.equals(v); // note: accomodates not finding NS as well } - if(create && !rv) { - if(nses == null) nses = new HashMap<>(); + if (create && !rv) { + if (nses == null) nses = new HashMap<>(); nses.put(ns, value); } return rv; @@ -177,25 +177,25 @@ public class OutXML extends Out{ private boolean tag(Writer fore, Writer aft, boolean pretty, boolean returns, String tag, String data) throws IOException { fore.append('<'); fore.append(tag); - if(data!=null) { + if (data!=null) { fore.append('>'); // if no data, it may need some attributes... fore.append(data); - if(returns)fore.append('\n'); + if (returns)fore.append('\n'); } aft.append("</"); aft.append(tag); aft.append(">"); - if(pretty)aft.append('\n'); + if (pretty)aft.append('\n'); return data==null; } private void attrib(Writer fore, boolean pretty, String tag, String value, Level level) throws IOException { String realTag = tag.startsWith("__")?tag.substring(2):tag; // remove __ - if(realTag.equals(Parsed.EXTENSION_TAG)) { // Convert Derived name into XML defined Inheritance + if (realTag.equals(Parsed.EXTENSION_TAG)) { // Convert Derived name into XML defined Inheritance fore.append(" xsi:type=\""); fore.append(value); fore.append('"'); - if(!level.hasPrinted(XMLNS_XSI, XML_SCHEMA_INSTANCE,true)) { + if (!level.hasPrinted(XMLNS_XSI, XML_SCHEMA_INSTANCE,true)) { fore.append(' '); fore.append(XMLNS_XSI); fore.append("=\""); @@ -203,8 +203,8 @@ public class OutXML extends Out{ fore.append("\""); } } else { - if(realTag.startsWith("xmlns:") ) { - if(level.hasPrinted(realTag, value, true)) { + if (realTag.startsWith("xmlns:") ) { + if (level.hasPrinted(realTag, value, true)) { return; } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java index a4c679db..29a86de8 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Parsed.java @@ -73,15 +73,15 @@ public class Parsed<S> { public String toString() { StringBuilder sb2 = new StringBuilder(); - if(event<40)sb2.append((int)event); + if (event<40)sb2.append((int)event); else sb2.append(event); sb2.append(" - "); sb2.append(name); - if(sb.length()>0) { + if (sb.length()>0) { sb2.append(" : "); - if(isString)sb2.append('"'); + if (isString)sb2.append('"'); sb2.append(sb); - if(isString)sb2.append('"'); + if (isString)sb2.append('"'); } return sb2.toString(); } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java index ae9c8934..d46fc8be 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Prop.java @@ -31,7 +31,7 @@ class Prop { public Prop(String t_equals_v) { String[] tv = t_equals_v.split("="); - if(tv.length>1) { + if (tv.length>1) { tag = tv[0]; value = tv[1]; } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java index a596b705..efb4ce4b 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/Saved.java @@ -50,20 +50,20 @@ public class Saved extends Out implements Parse<Reader, State>{ // @Override public<IN,S> void extract(IN in, Writer ignore, Parse<IN,S> parser, boolean ... options) throws IOException, ParseException { Parsed<S> p = parser.newParsed(); - if(!append) { + if (!append) { // reuse array if not too big - if(content==null||content.length>INIT_SIZE*3) { + if (content==null||content.length>INIT_SIZE*3) { content = new Content[INIT_SIZE]; idx = -1; } else do { content[idx]=null; - } while(--idx>=0); + } while (--idx>=0); } // Note: idx needs to be -1 on initialization and no appendages - while((p = parser.parse(in,p.reuse())).valid()) { - if(!(append && (p.event==START_DOC || p.event==END_DOC))) { // skip any start/end of document in appendages - if(++idx>=content.length) { + while ((p = parser.parse(in,p.reuse())).valid()) { + if (!(append && (p.event==START_DOC || p.event==END_DOC))) { // skip any start/end of document in appendages + if (++idx>=content.length) { Content temp[] = new Content[content.length*2]; System.arraycopy(content, 0, temp, 0, idx); content = temp; @@ -76,7 +76,7 @@ public class Saved extends Out implements Parse<Reader, State>{ // @Override public Parsed<State> parse(Reader ignore, Parsed<State> parsed) throws ParseException { int i; - if((i=parsed.state.count++)<=idx) + if ((i=parsed.state.count++)<=idx) content[i].load(parsed); else parsed.event = Parse.NONE; @@ -85,9 +85,9 @@ public class Saved extends Out implements Parse<Reader, State>{ public Content[] cut(char event, int count) { append = true; - for(int i=idx;i>=0;--i) { - if(content[i].event==event) count--; - if(count==0) { + for (int i=idx;i>=0;--i) { + if (content[i].event==event) count--; + if (count==0) { Content[] appended = new Content[idx-i+1]; System.arraycopy(content, i, appended, 0, appended.length); idx = i-1; @@ -98,8 +98,8 @@ public class Saved extends Out implements Parse<Reader, State>{ } public void paste(Content[] appended) { - if(appended!=null) { - if(idx+appended.length>content.length) { + if (appended!=null) { + if (idx+appended.length>content.length) { Content temp[] = new Content[content.length*2]; System.arraycopy(content, 0, temp, 0, idx); content = temp; @@ -134,7 +134,7 @@ public class Saved extends Out implements Parse<Reader, State>{ p.isString = isString; p.event = event; p.name = name; - if(str!=null) + if (str!=null) p.sb.append(str); } @@ -144,14 +144,14 @@ public class Saved extends Out implements Parse<Reader, State>{ sb.append(" - "); sb.append(name); sb.append(": "); - if(isString)sb.append('"'); + if (isString)sb.append('"'); sb.append(str); - if(isString)sb.append('"'); + if (isString)sb.append('"'); sb.append(' '); - if(props!=null) { + if (props!=null) { boolean comma = false; - for(Prop prop : props) { - if(comma)sb.append(','); + for (Prop prop : props) { + if (comma)sb.append(','); else comma = true; sb.append(prop.tag); sb.append('='); diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java index 1b0eec07..3007ea95 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/XmlEscape.java @@ -36,13 +36,13 @@ public class XmlEscape { try { int c; StringBuilder esc = new StringBuilder(); - for(int cnt = 0;cnt<9 /*max*/; ++cnt) { - if((c=r.read())<0)throw new ParseException("Invalid Data: Unfinished Escape Sequence"); - if(c!=';') { + for (int cnt = 0;cnt<9 /*max*/; ++cnt) { + if ((c=r.read())<0)throw new ParseException("Invalid Data: Unfinished Escape Sequence"); + if (c!=';') { esc.append((char)c); } else { // evaluate Integer i = charMap.get(esc.toString()); - if(i==null) { + if (i==null) { // leave in nasty XML format for now. sb.append('&'); sb.append(esc); @@ -69,20 +69,20 @@ public class XmlEscape { public static String convert(StringBuilder insb) { int idx, ch; StringBuilder sb=null; - for(idx=0;idx<insb.length();++idx) { + for (idx=0;idx<insb.length();++idx) { ch = insb.charAt(idx); - if(ch>=160 || ch==34 || ch==38 || ch==39 || ch==60 || ch==62) { + if (ch>=160 || ch==34 || ch==38 || ch==39 || ch==60 || ch==62) { sb = new StringBuilder(); sb.append(insb,0,idx); break; } } - if(sb==null)return insb.toString(); + if (sb==null)return insb.toString(); - for(int i=idx;i<insb.length();++i) { + for (int i=idx;i<insb.length();++i) { ch = insb.charAt(i); - if(ch<160) { + if (ch<160) { switch(ch) { case 34: sb.append("""); break; case 38: sb.append("&"); break; @@ -94,7 +94,7 @@ public class XmlEscape { } } else { // use map String s = intMap.get(ch); - if(s==null)sb.append((char)ch); + if (s==null)sb.append((char)ch); else { sb.append('&'); sb.append(s); @@ -362,8 +362,8 @@ public class XmlEscape { charMap.put("hearts",9829); charMap.put("diams",9830); - for( Entry<String, Integer> es: charMap.entrySet()) { - if(es.getValue()>=160); // save small space... note that no longer has amp, etc. + for ( Entry<String, Integer> es: charMap.entrySet()) { + if (es.getValue()>=160); // save small space... note that no longer has amp, etc. intMap.put(es.getValue(), es.getKey()); } } diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java index 69926974..a95da8ea 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaDF.java @@ -217,7 +217,7 @@ public class RosettaDF<T> extends BaseDataFactory implements DataFactory<T> { * @return */ public RosettaDF<T> rootMarshal(Marshal<T> marshal) { - if(marshal instanceof DocMarshal) { + if (marshal instanceof DocMarshal) { this.marshal = marshal; } else { this.marshal = DocMarshal.root(marshal); @@ -229,7 +229,7 @@ public class RosettaDF<T> extends BaseDataFactory implements DataFactory<T> { Out out = getOut(outType); TimeTaken tt = trans.start(out.logName(),logType(outType)); // determine from Out.. without dependency on Env? try { - if(marshal==null) { // Unknown marshaller... do working XML marshal/extraction + if (marshal==null) { // Unknown marshaller... do working XML marshal/extraction StringWriter sw = new StringWriter(); jaxMar.marshal(trans.debug(), t, sw, options); out.extract(new StringReader(sw.toString()), new OutputStreamWriter(os), inXML,options); @@ -247,7 +247,7 @@ public class RosettaDF<T> extends BaseDataFactory implements DataFactory<T> { Out out = getOut(outType); TimeTaken tt = trans.start(out.logName(),logType(outType)); // determine from Out.. without dependency on Env? try { - if(marshal==null) { // Unknown marshaller... do working XML marshal/extraction + if (marshal==null) { // Unknown marshaller... do working XML marshal/extraction StringWriter sw = new StringWriter(); jaxMar.marshal(trans.debug(), t, sw, options); out.extract(new StringReader(sw.toString()), writer, inXML,options); diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java index 97f68dae..fa29dcdc 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/env/RosettaData.java @@ -129,7 +129,7 @@ public class RosettaData<T> implements Data<T>{ Parse<?,?> in = df.getIn(inType); TimeTaken tt = in.start(trans); try { - if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction + if (df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction StringWriter sw = new StringWriter(); df.jaxMar.marshal(trans.debug(), t, sw, options); saved.extract(new StringReader(xml = sw.toString()), (Writer)null, df.inXML); @@ -169,15 +169,15 @@ public class RosettaData<T> implements Data<T>{ Out out = df.getOut(outType); TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? try { - if(outType==TYPE.XML) { - if(xml==null) { + if (outType==TYPE.XML) { + if (xml==null) { StringWriter sw = new StringWriter(); out.extract(null, sw, saved, options); xml = sw.toString(); } return xml; } else { // is JSON - if(json==null) { + if (json==null) { StringWriter sw = new StringWriter(); out.extract(null, sw, saved, options); json = sw.toString(); @@ -197,9 +197,9 @@ public class RosettaData<T> implements Data<T>{ Out out = df.getOut(outType); TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? try { - if(outType==TYPE.XML && xml!=null) { + if (outType==TYPE.XML && xml!=null) { os.write(xml.getBytes()); - } else if(outType==TYPE.JSON && json!=null) { + } else if (outType==TYPE.JSON && json!=null) { os.write(json.getBytes()); } else { out.extract(null, os, saved, options); @@ -217,9 +217,9 @@ public class RosettaData<T> implements Data<T>{ Out out = df.getOut(outType); TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? try { - if(outType==TYPE.XML && xml!=null) { + if (outType==TYPE.XML && xml!=null) { writer.append(xml); - } else if(outType==TYPE.JSON && json!=null) { + } else if (outType==TYPE.JSON && json!=null) { writer.append(json); } else { out.extract(null, writer, saved, options); @@ -260,7 +260,7 @@ public class RosettaData<T> implements Data<T>{ Out out = df.getOut(outType); TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? try { - if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction + if (df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction StringWriter sw = new StringWriter(); df.jaxMar.marshal(trans.debug(), t, sw, options); out.extract(new StringReader(xml = sw.toString()), writer, df.inXML,options); @@ -278,8 +278,8 @@ public class RosettaData<T> implements Data<T>{ Out out = df.getOut(outType); TimeTaken tt = trans.start(out.logName(),df.logType(outType)); // determine from Out.. without dependency on Env? try { - if(df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction - if(outType.equals(TYPE.XML)) { + if (df.marshal==null) { // Unknown marshaller... do working XML marshal/extraction + if (outType.equals(TYPE.XML)) { df.jaxMar.marshal(trans.debug(), t, os, options); } else { StringWriter sw = new StringWriter(); diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java index 849a3214..0617e01d 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DataWriter.java @@ -127,7 +127,7 @@ public abstract class DataWriter<T> { // String in "HexString" or the processing in // "String.format" //sb.append("0x"); - for(int i=0;i<ba.length;++i) { + for (int i=0;i<ba.length;++i) { byte b = ba[i]; sb.append(chars[((b&0xF0)>>4)]); sb.append(chars[b&0xF]); diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java index 6cabe068..1fa17010 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/DocMarshal.java @@ -40,18 +40,18 @@ public class DocMarshal<T> extends Marshal<T> { public Parsed<State> parse(T t, Parsed<State> parsed) throws ParseException { Ladder<Iterator<?>> ladder = parsed.state.ladder; Iterator<?> iter = ladder.peek(); - if(iter==null) { + if (iter==null) { ladder.push(PENDING_ITERATOR); parsed.event = START_DOC; } else if (DONE_ITERATOR.equals(iter)) { } else { ladder.ascend(); // look at field info Iterator<?> currFieldIter = ladder.peek(); - if(!DONE_ITERATOR.equals(currFieldIter)){ + if (!DONE_ITERATOR.equals(currFieldIter)){ parsed = root.parse(t, parsed); } ladder.descend(); - if(DONE_ITERATOR.equals(currFieldIter) || parsed.event==NONE) { + if (DONE_ITERATOR.equals(currFieldIter) || parsed.event==NONE) { parsed.event = END_DOC; ladder.push(DONE_ITERATOR); } @@ -68,7 +68,7 @@ public class DocMarshal<T> extends Marshal<T> { @Override public Void next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return null; diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java index 48f3608d..abc19b26 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/FieldArray.java @@ -44,9 +44,9 @@ public abstract class FieldArray<T,S> extends Marshal<T> { public Parsed<State> parse(T t, Parsed<State> parsed) throws ParseException { Ladder<Iterator<?>> ladder = parsed.state.ladder; Iterator<?> iter = ladder.peek(); - if(iter==null) { + if (iter==null) { List<S> list = data(t); - if(list.isEmpty() && parsed.state.smallest) { + if (list.isEmpty() && parsed.state.smallest) { ladder.push(DONE_ITERATOR); } else { ladder.push(new ListIterator<S>(list)); @@ -59,24 +59,24 @@ public abstract class FieldArray<T,S> extends Marshal<T> { Iterator<?> memIter = ladder.peek(); ListIterator<S> mems = (ListIterator<S>)iter; S mem; - if(memIter==null) { + if (memIter==null) { mem=mems.next(); - } else if(!DONE_ITERATOR.equals(memIter)) { + } else if (!DONE_ITERATOR.equals(memIter)) { mem=mems.peek(); - } else if(iter.hasNext()) { + } else if (iter.hasNext()) { mem=null; ladder.push(null); } else { mem=null; } - if(mem!=null) { + if (mem!=null) { parsed.isString=dataWriter.write(mem, parsed.sb); parsed.event = NEXT; } ladder.descend(); - if(mem==null) { - if(iter.hasNext()) { + if (mem==null) { + if (iter.hasNext()) { parsed.event = NEXT; } else { parsed.event = END_ARRAY; diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java index 384e0c98..9c64e83d 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjArray.java @@ -44,9 +44,9 @@ public abstract class ObjArray<T,S> extends Marshal<T> { public Parsed<State> parse(T t, Parsed<State> parsed) throws ParseException { Ladder<Iterator<?>> ladder = parsed.state.ladder; Iterator<?> iter = ladder.peek(); - if(iter==null) { + if (iter==null) { List<S> list = data(t); - if(list.isEmpty() && parsed.state.smallest) { + if (list.isEmpty() && parsed.state.smallest) { ladder.push(DONE_ITERATOR); } else { ladder.push(new ListIterator<S>(list)); @@ -58,22 +58,22 @@ public abstract class ObjArray<T,S> extends Marshal<T> { Iterator<?> memIter = ladder.peek(); ListIterator<S> mems = (ListIterator<S>)iter; S mem; - if(memIter==null) { + if (memIter==null) { mem=mems.next(); - } else if(!DONE_ITERATOR.equals(memIter)) { + } else if (!DONE_ITERATOR.equals(memIter)) { mem=mems.peek(); - } else if(iter.hasNext()) { + } else if (iter.hasNext()) { mem=null; ladder.push(null); } else { mem=null; } - if(mem!=null) + if (mem!=null) parsed = subMarshaller.parse(mem, parsed); ladder.descend(); - if(mem==null) { - if(iter.hasNext()) { + if (mem==null) { + if (iter.hasNext()) { parsed.event = NEXT; } else { parsed.event = END_ARRAY; diff --git a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java index 31e214b5..d96a44d0 100644 --- a/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java +++ b/misc/rosetta/src/main/java/org/onap/aaf/misc/rosetta/marshal/ObjMarshal.java @@ -47,9 +47,9 @@ public abstract class ObjMarshal<T> extends Marshal<T> { */ @SuppressWarnings("unchecked") protected void add(Marshal<T> pm) { - if(pml==null) { + if (pml==null) { pml = new Marshal[Ladder.DEFAULT_INIT_SIZE]; - } else if(end>pml.length) { + } else if (end>pml.length) { Object temp[] = pml; pml = new Marshal[pml.length+Ladder.DEFAULT_INIT_SIZE]; System.arraycopy(temp, 0, pml, 0, pml.length); @@ -66,8 +66,8 @@ public abstract class ObjMarshal<T> extends Marshal<T> { public Parsed<State> parse(T in, Parsed<State> parsed) throws ParseException { Ladder<Iterator<?>> ladder = parsed.state.ladder; Iterator<Marshal<T>> iter = (Iterator<Marshal<T>>)ladder.peek(); - if(iter==null) { - if(pml.length>0) { + if (iter==null) { + if (pml.length>0) { ladder.push(new FieldsIterator()); parsed.event = START_OBJ; } else { @@ -78,22 +78,22 @@ public abstract class ObjMarshal<T> extends Marshal<T> { ladder.ascend(); // look at field info Iterator<?> currFieldIter = ladder.peek(); Marshal<T> marshal; - if(currFieldIter==null) { + if (currFieldIter==null) { marshal=fields.next(); - } else if(!DONE_ITERATOR.equals(currFieldIter)) { + } else if (!DONE_ITERATOR.equals(currFieldIter)) { marshal=fields.peek(); - if(marshal==null && fields.hasNext())marshal=fields.next(); - } else if(fields.hasNext()) { + if (marshal==null && fields.hasNext())marshal=fields.next(); + } else if (fields.hasNext()) { marshal=fields.next(); ladder.push(null); } else { marshal=null; } - if(marshal!=null) + if (marshal!=null) parsed = marshal.parse(in, parsed); ladder.descend(); - if(marshal==null || parsed.event==NONE) { + if (marshal==null || parsed.event==NONE) { parsed.event = END_OBJ; ladder.push(DONE_ITERATOR); } @@ -111,7 +111,7 @@ public abstract class ObjMarshal<T> extends Marshal<T> { @Override public Marshal<T> next() { - if(!hasNext()) { + if (!hasNext()) { throw new NoSuchElementException(); } return pml[++idx]; diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java index 3e12f594..67565122 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromJSON.java @@ -90,7 +90,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); String result = sbw.toString(); System.out.println(result); @@ -120,7 +120,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -147,7 +147,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -175,7 +175,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.JSON); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -218,7 +218,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -260,7 +260,7 @@ public class JU_FromJSON { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java index 2a4e3d2d..4fefe622 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_FromXML.java @@ -100,7 +100,7 @@ public class JU_FromXML { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -127,7 +127,7 @@ public class JU_FromXML { tt.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -136,7 +136,7 @@ public class JU_FromXML { @Test public void warmup() throws Exception { - if(ITERATIONS>20) { + if (ITERATIONS>20) { System.out.println("*** Warmup JAXB ***"); JAXBumar jaxbUmar = new JAXBumar(LargerData.class); @@ -170,7 +170,7 @@ public class JU_FromXML { all.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); @@ -209,7 +209,7 @@ public class JU_FromXML { all.done(); } report.glean(trans,Env.XML); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); } @@ -225,7 +225,7 @@ public class JU_FromXML { Trans trans = EnvFactory.newTrans(); LargerData ld; - for(int i=0;i<ITERATIONS;++i) { + for (int i=0;i<ITERATIONS;++i) { sbw.reset(); TimeTaken all = trans.start("Combo", Env.SUB); try { @@ -247,7 +247,7 @@ public class JU_FromXML { } sbw.append('\n'); Metric m; - if(ITERATIONS>20) { + if (ITERATIONS>20) { m = trans.auditTrail(0,null); } else { m = trans.auditTrail(0, sbw.getBuffer()); diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java index 9ab06e7c..af58ea57 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_JSON.java @@ -123,7 +123,7 @@ public class JU_JSON { System.out.println(sw); String result = sw.toString(); - if(!result.equals(cmp)) { + if (!result.equals(cmp)) { sw.getBuffer().setLength(0); new OutRaw().extract(new StringReader(str), sw, in); System.out.println(sw); diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java index 229f1bf4..fd6142b1 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Ladder.java @@ -32,22 +32,22 @@ public class JU_Ladder { public void test() { Ladder<String> ladder = new Ladder<String>(); - for(int i=0;i<30;++i) { - for(int j=0;j<i;++j)ladder.ascend(); + for (int i=0;i<30;++i) { + for (int j=0;j<i;++j)ladder.ascend(); String str = "Rung " + i; assertEquals(ladder.peek(),null); ladder.push(str); assertEquals(str,ladder.peek()); assertEquals(str,ladder.pop()); assertEquals(null,ladder.peek()); - for(int j=0;j<i;++j)ladder.descend(); + for (int j=0;j<i;++j)ladder.descend(); } assertEquals(ladder.height(),32); // Sizing, when naturally created is by 8 ladder.cutTo(8); assertEquals(ladder.height(),8); - for(int i=0;i<30;++i) { + for (int i=0;i<30;++i) { ladder.jumpTo(i); String str = "Rung " + i; assertEquals(ladder.peek(),null); @@ -57,7 +57,7 @@ public class JU_Ladder { ladder.bottom(); - for(int i=0;i<30;++i) { + for (int i=0;i<30;++i) { assertEquals("Rung " + i,ladder.peek()); ladder.ascend(); } @@ -66,7 +66,7 @@ public class JU_Ladder { ladder.top(); assertEquals("Rung 29",ladder.peek()); - for(int i=0;i<30;++i) { + for (int i=0;i<30;++i) { ladder.jumpTo(i); assertEquals("Rung " + i,ladder.peek()); } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java index 1a5f86f3..ccc29317 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_RosettaDF.java @@ -95,7 +95,7 @@ public class JU_RosettaDF { tt.done(); } report.glean(trans, 1,2,3,4,5); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw); @@ -117,7 +117,7 @@ public class JU_RosettaDF { RosettaData<?> data = df.newData(trans).in(Data.TYPE.JSON).out(Data.TYPE.XML); data.direct(new StringReader(JU_FromJSON.str), sbw); report.glean(trans); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw); diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java index de1b5500..a0847f4c 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Saved.java @@ -95,7 +95,7 @@ public class JU_Saved<b> { tt.done(); } report.glean(trans,1,2,3,4); - } while(report.go()); + } while (report.go()); report.report(sbw); System.out.println(sbw.toString()); diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java index 7e767e5d..40c41596 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Struct.java @@ -57,7 +57,7 @@ public class JU_Struct { // Setter<SampleData> setter = jaxSet.setter("id"); // setter.set(sd, "Your ID"); // -// for(Entry<String, Getter<SampleData>> es : jaxSet.getters()) { +// for (Entry<String, Getter<SampleData>> es : jaxSet.getters()) { // System.out.print(es.getKey()); // System.out.print(' '); // System.out.println(es.getValue().get(sd)); diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java index 032f9f1c..2aca5f52 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/JU_Types.java @@ -120,9 +120,9 @@ public class JU_Types { Multi multi = new Multi(); MultiMarshal pmulti = new MultiMarshal(); - for(int i=0;i<10;++i) { + for (int i=0;i<10;++i) { System.out.println("===== Multi Iteration " + i + " ====="); - if(i>0) { + if (i>0) { multi.getSingle().add(setSData()); } System.out.println(" ===== RAW ====="); @@ -151,9 +151,9 @@ public class JU_Types { Multi multi = new Multi(); DocMarshal<Multi> doc = DocMarshal.root(new MultiMarshal()); - for(int i=0;i<3;++i) { + for (int i=0;i<3;++i) { System.out.println("===== Multi Iteration " + i + " ====="); - if(i>0) { + if (i>0) { multi.getSingle().add(setSData()); } System.out.println(" ===== RAW ====="); @@ -194,14 +194,14 @@ public class JU_Types { Trans trans = env.newTrans(); RosettaData<Multi> data = df.newData(trans); // Prime pump - for(int i=0;i<100;++i) { + for (int i=0;i<100;++i) { data.load(multi); } trans = env.newTrans(); data = df.newData(trans); int iters = 10000; - for(int i=0;i<iters;++i) { + for (int i=0;i<iters;++i) { data.load(multi); } Metric metrics = trans.auditTrail(0, null,Env.JSON,Env.XML); @@ -215,13 +215,13 @@ public class JU_Types { data = df.newData(trans); // Prime pump - for(int i=0;i<100;++i) { + for (int i=0;i<100;++i) { data.load(multi); } trans = env.newTrans(); data = df.newData(trans); - for(int i=0;i<iters;++i) { + for (int i=0;i<iters;++i) { data.load(multi); } metrics = trans.auditTrail(0, null,Env.JSON,Env.XML); @@ -235,14 +235,14 @@ public class JU_Types { data = df.newData(trans); StringBuilderWriter sbw = new StringBuilderWriter(256); // Prime pump - for(int i=0;i<100;++i) { + for (int i=0;i<100;++i) { sbw.reset(); data.direct(multi, sbw, true); } trans = env.newTrans(); data = df.newData(trans); - for(int i=0;i<iters;++i) { + for (int i=0;i<iters;++i) { sbw.reset(); data.direct(multi, sbw, true); } @@ -287,7 +287,7 @@ public class JU_Types { System.out.println(sw); String result = sw.toString(); - if(!result.equals(str)) { + if (!result.equals(str)) { sw.getBuffer().setLength(0); new OutRaw().extract(new StringReader(str), sw, in); System.out.println(sw); diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java index 6ebd07a3..7e230822 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/OutDump.java @@ -38,7 +38,7 @@ public class OutDump extends Out{ Parsed<S> p = prs.newParsed(); - while((p = prs.parse(in,p.reuse())).valid()) { + while ((p = prs.parse(in,p.reuse())).valid()) { switch(p.event) { case Parse.START_OBJ: ipw.append("Start Object "); @@ -71,9 +71,9 @@ public class OutDump extends Out{ } private void printData(IndentPrintWriter ipw, Parsed<?> parsed) { - if(parsed.hasData()) { + if (parsed.hasData()) { ipw.append("Data:["); - if(parsed.hasName()) { + if (parsed.hasName()) { ipw.append(parsed.name); ipw.append(" : "); } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java index df4fec07..acb33010 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/test/Report.java @@ -46,7 +46,7 @@ public class Report { Metric m = trans.auditTrail(0, null, type); total+=m.total; int min = Math.min(buckets.length, m.buckets.length); - for(int b=0;b<min;++b) { + for (int b=0;b<min;++b) { buckets[b]+=m.buckets[b]; } } @@ -59,7 +59,7 @@ public class Report { public void report(Writer sbw) throws IOException { sbw.append("\n"+count + " entries, Total Time: " + total + "ms, Avg Time: " + total/count + "ms\n"); int min = Math.min(buckets.length, names.length); - for(int i=0;i<min;++i) { + for (int i=0;i<min;++i) { sbw.append(" Time: " + names[i] + ' ' + buckets[i] + "ms, Avg Time: " + buckets[i]/count + "ms\n"); } diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java index 3edf8b60..eb58fc25 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/CacheGen.java @@ -71,7 +71,7 @@ public abstract class CacheGen<G extends XGen<G>> { }
public void replay(State<Env> state, Trans trans,Writer w, String theme) throws IOException, APIException {
- if(thematic!=null) {
+ if (thematic!=null) {
theme = thematic.themeResolve(theme);
}
/* Theme
@@ -87,7 +87,7 @@ public abstract class CacheGen<G extends XGen<G>> { int i=0;
@SuppressWarnings("unchecked")
Section<G>[] reverse = new Section[sections.size()];
- for(Section<G> section : sections) {
+ for (Section<G> section : sections) {
s = section.use(state, trans, buff); // note, doesn't change cached, only dynamic, which is created for thread
int tempIndent = s.getIndent();
s.setIndent(indent);
@@ -97,7 +97,7 @@ public abstract class CacheGen<G extends XGen<G>> { reverse[i++]=s;
}
- for(--i;i>=0;--i) {
+ for (--i;i>=0;--i) {
reverse[i].back(w);
}
w.flush();
@@ -116,7 +116,7 @@ public abstract class CacheGen<G extends XGen<G>> { // Clone Dynamic to make Thread Safe
Dynamic d = new Dynamic(indent,code);
buff.setIndent(indent);
- if(code instanceof DynamicCode) {
+ if (code instanceof DynamicCode) {
buff.run(state,trans,Cache.Null.singleton(), (DynamicCode<G,?,? extends Trans>)code);
} else {
buff.run((Cache<G>)Cache.Null.singleton(), code);
diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java index 7b0a4263..b68ad6e5 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/XGen.java @@ -61,7 +61,7 @@ public class XGen<RT extends XGen<RT>> { }
protected void prettyln(PrintWriter pw) {
- if(pretty)pw.println();
+ if (pretty)pw.println();
}
public RT leaf(Mark mark, String tag, String ... args) {
@@ -110,10 +110,10 @@ public class XGen<RT extends XGen<RT>> { back.append(tag);
back.append('>');
- if(pretty) {
- if(mark!=null && mark.comment!=null) {
+ if (pretty) {
+ if (mark!=null && mark.comment!=null) {
int fi = forward.getIndent()*IndentPrintWriter.INDENT_MULTIPLIER;
- for(int i = fi+backSB.length();i<=COMMENT_COLUMN;++i) {
+ for (int i = fi+backSB.length();i<=COMMENT_COLUMN;++i) {
back.append(' ');
}
back.append("<!-- end ");
@@ -126,12 +126,12 @@ public class XGen<RT extends XGen<RT>> { forward.append(" -->");
}
forward.inc();
- if(!oneLine) {
+ if (!oneLine) {
forward.println();
}
back.println();
}
- if(mark!=null)mark.spot = backStack.size();
+ if (mark!=null)mark.spot = backStack.size();
backStack.push(new Back(backSB.toString(),true, false));
backSB.setLength(0);
return (RT)this;
@@ -143,7 +143,7 @@ public class XGen<RT extends XGen<RT>> { forward.append(tag);
addAttrs(attrs);
forward.append(" />");
- if(pretty) {
+ if (pretty) {
forward.println();
}
return (RT)this;
@@ -157,7 +157,7 @@ public class XGen<RT extends XGen<RT>> { @SuppressWarnings("unchecked")
public RT xml(String txt) {
- for(int i=0; i<txt.length();++i) {
+ for (int i=0; i<txt.length();++i) {
char c = txt.charAt(i);
switch(c) {
case '<':
@@ -179,11 +179,11 @@ public class XGen<RT extends XGen<RT>> { @SuppressWarnings("unchecked")
public RT textCR(int tabs, String txt) {
- for(int i=0;i<tabs;++i) {
+ for (int i=0;i<tabs;++i) {
forward.append(" ");
}
forward.append(txt);
- if(pretty)forward.println();
+ if (pretty)forward.println();
return (RT)this;
}
@@ -218,13 +218,13 @@ public class XGen<RT extends XGen<RT>> { int size = backStack.size();
Back c;
boolean println = false;
- for(int i=mark==null?0:mark.spot;i<size;++i) {
+ for (int i=mark==null?0:mark.spot;i<size;++i) {
c = backStack.pop();
- if(c.dec)forward.dec();
+ if (c.dec)forward.dec();
forward.append(c.str);
println = c.cr;
}
- if(pretty && println) {
+ if (pretty && println) {
forward.println();
}
return (RT)this;
@@ -233,14 +233,14 @@ public class XGen<RT extends XGen<RT>> { public RT end() {
Mark mark = new Mark();
mark.spot=backStack.size()-1;
- if(mark.spot<0)mark.spot=0;
+ if (mark.spot<0)mark.spot=0;
return end(mark);
}
public RT end(int i) {
Mark mark = new Mark();
mark.spot=backStack.size()-i;
- if(mark.spot<0)mark.spot=0;
+ if (mark.spot<0)mark.spot=0;
return end(mark);
}
@@ -250,9 +250,9 @@ public class XGen<RT extends XGen<RT>> { }
protected void addAttrs(String[] attrs) {
- if(attrs!=null) {
- for(String attr : attrs) {
- if(attr!=null && attr.length()>0) {
+ if (attrs!=null) {
+ for (String attr : attrs) {
+ if (attr!=null && attr.length()>0) {
forward.append(' ');
String[] split = attr.split("=",2);
switch(split.length) {
@@ -276,7 +276,7 @@ public class XGen<RT extends XGen<RT>> { @SuppressWarnings("unchecked")
public RT comment(String string) {
- if(pretty) {
+ if (pretty) {
forward.print("<!-- ");
forward.print(string);
forward.println(" -->");
diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java index 16ac60ae..846ab5a1 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML4Gen.java @@ -121,13 +121,13 @@ public class HTML4Gen extends HTMLGen { // @Override
// protected void importCSS(Imports imports) {
-// if(imports.css.size()==1) {
+// if (imports.css.size()==1) {
// cssInline(imports.css.get(0));
// } else {
// text("<style type=\"text/css\">");
// prettyln(forward);
// forward.inc();
-// for(String str : imports.css) {
+// for (String str : imports.css) {
// forward.print("@import url(\"");
// forward.print(imports.themePath(null));
// forward.print(str);
diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java index 5e4cee7e..b502c6c6 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTML5Gen.java @@ -106,10 +106,10 @@ public class HTML5Gen extends HTMLGen { // @Override
// protected void importCSS(Imports imports) {
-// if(imports.css.size() == 1) {
+// if (imports.css.size() == 1) {
// cssInline(imports.css.get(0));
// } else {
-// for(String str : imports.css) {
+// for (String str : imports.css) {
// forward.print("<link rel=\"stylesheet\" href=\"");
// forward.print(imports.themePath(null));
// forward.print(str);
diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java index b2fb81d1..0db67913 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/HTMLGen.java @@ -69,14 +69,14 @@ public abstract class HTMLGen extends XGen<HTMLGen> { public HTMLGen imports(Imports imports) {
//this.imports=imports;
- for(String str : imports.css) {
+ for (String str : imports.css) {
forward.print("<link rel=\"stylesheet\" href=\"");
forward.print(imports.themePath(null));
forward.print(str);
forward.println("\">");
}
- for(String str : imports.js) {
+ for (String str : imports.js) {
forward.print("<script type=\"text/javascript\" src=\"");
forward.print(imports.themePath(null));
forward.print(str);
@@ -87,8 +87,8 @@ public abstract class HTMLGen extends XGen<HTMLGen> { public HTMLGen jsVars(String ... attrs) {
forward.println("<script type=text/javascript>");
- if(attrs!=null) {
- for(int i=0; i<attrs.length;++i) {
+ if (attrs!=null) {
+ for (int i=0; i<attrs.length;++i) {
forward.append(' ');
String[] split = attrs[i].split("=",2);
switch(split.length) {
@@ -121,7 +121,7 @@ public abstract class HTMLGen extends XGen<HTMLGen> { forward.append(tag);
addAttrs(attrs);
forward.append('>');
- if(pretty) {
+ if (pretty) {
forward.println();
}
return this;
@@ -129,7 +129,7 @@ public abstract class HTMLGen extends XGen<HTMLGen> { public Mark divID(String ... attrs) {
Mark div;
- if(attrs.length>0) {
+ if (attrs.length>0) {
div = new Mark(attrs[0]);
attrs[0]="id="+attrs[0];
} else {
@@ -168,7 +168,7 @@ public abstract class HTMLGen extends XGen<HTMLGen> { nattrs[0]="id="+id;
nattrs[1]="name="+id;
System.arraycopy(attrs, 0, nattrs, 2, attrs.length);
- if(required) {
+ if (required) {
nattrs[nattrs.length-1]="required";
}
incr(mtd);
@@ -180,7 +180,7 @@ public abstract class HTMLGen extends XGen<HTMLGen> { // Common tags that do not have standard endings. These are here to help people who don't know to pick directive
public HTMLGen br() {
forward.append("<br>");
- if(pretty) {
+ if (pretty) {
forward.println();
}
return this;
@@ -188,10 +188,10 @@ public abstract class HTMLGen extends XGen<HTMLGen> { public HTMLGen p(String ... text) {
forward.append("<p>");
- for(String s : text) {
+ for (String s : text) {
forward.append(s);
}
- if(pretty) {
+ if (pretty) {
forward.println();
}
return this;
@@ -199,7 +199,7 @@ public abstract class HTMLGen extends XGen<HTMLGen> { public HTMLGen hr() {
forward.append("<hr>");
- if(pretty) {
+ if (pretty) {
forward.println();
}
return this;
@@ -221,7 +221,7 @@ public abstract class HTMLGen extends XGen<HTMLGen> { // try {
// forward.print("<style>");
// prettyln(forward);
-// while((line=br.readLine())!=null) {
+// while ((line=br.readLine())!=null) {
// forward.print((pretty?line:line.trim()));
// prettyln(forward);
// }
diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java index 00e7f30f..84e449b1 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/Imports.java @@ -62,9 +62,9 @@ public class Imports implements Thematic{ @Override
public String themePath(String theTheme) {
StringBuilder src = dots(new StringBuilder());
- if(theTheme==null||theTheme.length()==0) {
+ if (theTheme==null||theTheme.length()==0) {
src.append(theme);
- if(theme.length()>0)src.append('/');
+ if (theme.length()>0)src.append('/');
} else {
src.append(theTheme);
src.append('/');
@@ -87,7 +87,7 @@ public class Imports implements Thematic{ }
public StringBuilder dots(StringBuilder src) {
- for(int i=0;i<backdots;++i) {
+ for (int i=0;i<backdots;++i) {
src.append("../");
}
return src;
diff --git a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/JSGen.java b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/JSGen.java index 5d9a507d..a1f8f522 100644 --- a/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/JSGen.java +++ b/misc/xgen/src/main/java/org/onap/aaf/misc/xgen/html/JSGen.java @@ -49,27 +49,27 @@ public class JSGen { boolean pretty = htmlGen.pretty;
String line, el;
int l, end;
- while((line=br.readLine())!=null) {
- if(pretty) {
+ while ((line=br.readLine())!=null) {
+ if (pretty) {
String[] elements = line.split("\t");
- for(int i=0; i<elements.length;++i) {
+ for (int i=0; i<elements.length;++i) {
el = elements[i];
l = el.length();
- if(l==0) {// was a Tab
+ if (l==0) {// was a Tab
ipw.print(" ");
} else {
el = el.trim();
l = l-el.length();
end = l/tabstop;
- for(int j=0;j<end;++j) {
+ for (int j=0;j<end;++j) {
ipw.print(" ");
}
end = l%tabstop;
- for(int j=0;j<end;++j) {
+ for (int j=0;j<end;++j) {
ipw.print(' ');
}
- if(i>0) ipw.print(' ');
+ if (i>0) ipw.print(' ');
ipw.print(el);
}
}
@@ -94,40 +94,40 @@ public class JSGen { }
public JSGen pst(Mark jm, String ... lines) {
- if(lines.length>0) ipw.append(lines[0]);
+ if (lines.length>0) ipw.append(lines[0]);
ipw.append('(');
- for(int i=1;i<lines.length;++i) {
+ for (int i=1;i<lines.length;++i) {
ipw.print(lines[i]);
ipw.print(", ");
}
Back back;
- if(htmlGen.pretty) {
+ if (htmlGen.pretty) {
back = new Back(");\n",false,false);
} else {
back = new Back(");",false,false);
}
int spot = htmlGen.pushBack(back);
- if(jm!=null)jm.spot(spot);
+ if (jm!=null)jm.spot(spot);
return this;
}
public JSGen li(String ... lines) {
int current = ipw.getIndent();
- for(int i=0;i<lines.length;++i) {
- if(i==1)ipw.inc();
- if(i>0)ipw.println();
+ for (int i=0;i<lines.length;++i) {
+ if (i==1)ipw.inc();
+ if (i>0)ipw.println();
ipw.print(lines[i]);
}
ipw.setIndent(current);
ipw.append(';');
- if(htmlGen.pretty)ipw.println();
+ if (htmlGen.pretty)ipw.println();
return this;
}
public JSGen text(String text) {
ipw.append(text);
- if(htmlGen.pretty)ipw.println();
+ if (htmlGen.pretty)ipw.println();
return this;
}
@@ -144,17 +144,17 @@ public class JSGen { ipw.print("function ");
ipw.print(name);
ipw.print('(');
- for(int i=0;i<params.length;++i) {
- if(i!=0)ipw.print(", ");
+ for (int i=0;i<params.length;++i) {
+ if (i!=0)ipw.print(", ");
ipw.print(params[i]);
}
ipw.print(") {");
- if(htmlGen.pretty) {
+ if (htmlGen.pretty) {
ipw.println();
ipw.inc();
}
int spot = htmlGen.pushBack(new Back("}",true,true));
- if(jm!=null)jm.spot(spot);
+ if (jm!=null)jm.spot(spot);
return this;
}
@@ -164,27 +164,27 @@ public class JSGen { public JSGen cb(Mark jm, String ... lines) {
int current = ipw.getIndent();
- for(int i=0;i<lines.length;++i) {
- if(i==1)ipw.inc();
- if(i>0)ipw.println();
+ for (int i=0;i<lines.length;++i) {
+ if (i==1)ipw.inc();
+ if (i>0)ipw.println();
ipw.print(lines[i]);
}
ipw.setIndent(current);
ipw.print('{');
- if(htmlGen.pretty) {
+ if (htmlGen.pretty) {
ipw.println();
ipw.inc();
}
int spot = htmlGen.pushBack(new Back("}",true,true));
- if(jm!=null)jm.spot(spot);
+ if (jm!=null)jm.spot(spot);
return this;
}
public JSGen comment(String ... lines) {
- if(htmlGen.pretty) {
- for(int i=0;i<lines.length;++i) {
+ if (htmlGen.pretty) {
+ for (int i=0;i<lines.length;++i) {
ipw.print("// ");
ipw.println(lines[i]);
}
|