diff options
246 files changed, 20013 insertions, 20013 deletions
diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java index 36a88b64..f361e750 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/Batch.java @@ -81,7 +81,7 @@ public abstract class Batch { protected static boolean dryRun; protected static String batchEnv; - private static File logdir; + private static File logdir; public static final String CASS_ENV = "CASS_ENV"; public static final String LOG_DIR = "LOG_DIR"; @@ -90,10 +90,10 @@ public abstract class Batch { public static final String GUI_URL="GUI_URL"; protected final Organization org; - protected String version; - protected static final Date now = new Date(); - protected static final Date never = new Date(0); - + protected String version; + protected static final Date now = new Date(); + protected static final Date never = new Date(0); + protected Batch(AuthzEnv env) throws APIException, IOException, OrganizationException { if (batchEnv != null) { env.info().log("Redirecting to ",batchEnv,"environment"); @@ -116,7 +116,7 @@ public abstract class Batch { // Setup for Dry Run if(cluster==null) { - cluster = CassAccess.cluster(env,batchEnv); + cluster = CassAccess.cluster(env,batchEnv); } env.info().log("cluster name - ",cluster.getClusterName()); String dryRunStr = env.getProperty( "DRY_RUN" ); @@ -129,7 +129,7 @@ public abstract class Batch { org = OrganizationFactory.init(env); if(org==null) { - throw new OrganizationException("Organization MUST be defined for Batch"); + throw new OrganizationException("Organization MUST be defined for Batch"); } org.setTestMode(dryRun); @@ -143,9 +143,9 @@ public abstract class Batch { for (String s :names.split(",") ) { env.info().log("\tspecial: " + s ); if(s.indexOf('@')>0) { - specialNames.add( s.trim() ); + specialNames.add( s.trim() ); } else { - specialDomains.add(s.trim()); + specialDomains.add(s.trim()); } } } @@ -166,21 +166,21 @@ public abstract class Batch { } public boolean isSpecial(String user) { - if(user==null) { - return false; - } + if(user==null) { + return false; + } if (specialNames != null && specialNames.contains(user)) { env.info().log("specialName: " + user); return (true); } else { - if(specialDomains!=null) { - for(String sd : specialDomains) { - if(user.endsWith(sd)) { - env.info().log("specialDomain: " + user + " matches " + sd); - return (true); - } - } - } + if(specialDomains!=null) { + for(String sd : specialDomains) { + if(user.endsWith(sd)) { + env.info().log("specialDomain: " + user + " matches " + sd); + return (true); + } + } + } } return (false); } @@ -339,18 +339,18 @@ public abstract class Batch { protected static File logDir() { if(logdir == null) { - String ld = env.getProperty(LOG_DIR); - if (ld==null) { - if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir - ld = "logs/"; - } else { - ld = "logs/"+batchEnv; - } - } - logdir = new File(ld); - if(!logdir.exists()) { - logdir.mkdirs(); - } + String ld = env.getProperty(LOG_DIR); + if (ld==null) { + if (batchEnv==null) { // Deployed Batch doesn't use different ENVs, and a common logdir + ld = "logs/"; + } else { + ld = "logs/"+batchEnv; + } + } + logdir = new File(ld); + if(!logdir.exists()) { + logdir.mkdirs(); + } } return logdir; } @@ -369,8 +369,8 @@ public abstract class Batch { public final void close(AuthzTrans trans) { _close(trans); if(session!=null) { - session.close(); - session = null; + session.close(); + session = null; } if(cluster!=null && !cluster.isClosed()) { cluster.close(); @@ -378,13 +378,13 @@ public abstract class Batch { } public static void main(String[] args) { - // Use a StringBuilder to save off logs until a File can be setup - StringBuilderOutputStream sbos = new StringBuilderOutputStream(); + // Use a StringBuilder to save off logs until a File can be setup + StringBuilderOutputStream sbos = new StringBuilderOutputStream(); PropAccess access = new PropAccess(new PrintStream(sbos),args); access.log(Level.INIT, "------- Starting Batch ------\n Args: "); for(String s: args) { - sbos.getBuffer().append(s); - sbos.getBuffer().append(' '); + sbos.getBuffer().append(s); + sbos.getBuffer().append(' '); } InputStream is = null; @@ -394,32 +394,32 @@ public abstract class Batch { Define.set(access); if(access.getProperty(Config.CADI_PROP_FILES)==null) { - File f = new File("authBatch.props"); - try { - if (f.exists()) { - filename = f.getAbsolutePath(); - is = new FileInputStream(f); - propLoc = f.getPath(); - } else { - URL rsrc = ClassLoader.getSystemResource("authBatch.props"); - filename = rsrc.toString(); - is = rsrc.openStream(); - propLoc = rsrc.getPath(); - } - access.load(is); - } finally { - if (is == null) { - System.err.println("authBatch.props must exist in current dir, or in Classpath"); - System.exit(1); - } - is.close(); - } - if (filename != null) { - access.log(Level.INFO,"Instantiated properties from", filename); - } - - // Log where Config found - access.log(Level.INFO,"Configuring from", propLoc); + File f = new File("authBatch.props"); + try { + if (f.exists()) { + filename = f.getAbsolutePath(); + is = new FileInputStream(f); + propLoc = f.getPath(); + } else { + URL rsrc = ClassLoader.getSystemResource("authBatch.props"); + filename = rsrc.toString(); + is = rsrc.openStream(); + propLoc = rsrc.getPath(); + } + access.load(is); + } finally { + if (is == null) { + System.err.println("authBatch.props must exist in current dir, or in Classpath"); + System.exit(1); + } + is.close(); + } + if (filename != null) { + access.log(Level.INFO,"Instantiated properties from", filename); + } + + // Log where Config found + access.log(Level.INFO,"Configuring from", propLoc); } @@ -432,119 +432,119 @@ public abstract class Batch { // PERF.cassandra.clusters=.... batchEnv = env.getProperty(CASS_ENV); if(batchEnv!=null) { - batchEnv = batchEnv.trim(); + batchEnv = batchEnv.trim(); } File logFile = new File(logDir() + "/batch" + Chrono.dateOnlyStamp(new Date()) + ".log" ); PrintStream batchLog = new PrintStream(new FileOutputStream(logFile,true)); try { - access.setStreamLogIt(batchLog); - sbos.flush(); - batchLog.print(sbos.getBuffer()); - sbos = null; - Logger.getRootLogger().addAppender(new Log4JAccessAppender(access)); - - Batch batch = null; - AuthzTrans trans = env.newTrans(); - - TimeTaken tt = trans.start("Total Run", Env.SUB); - try { - int len = args.length; - if (len > 0) { - String toolName = args[0]; - len -= 1; - if (len < 0) - len = 0; - String nargs[] = new String[len]; - if (len > 0) { - System.arraycopy(args, 1, nargs, 0, len); - } - - env.put(ssargs = env.staticSlot("ARGS"), nargs); - - /* - * Add New Batch Programs (inherit from Batch) here - */ - - // Might be a Report, Update or Temp Batch - Class<?> cls = null; - String classifier = ""; - - String[] pkgs = new String[] { - "org.onap.aaf.auth.batch.update", - "org.onap.aaf.auth.batch.reports", - "org.onap.aaf.auth.batch.temp" - }; - - String ebp = env.getProperty("EXTRA_BATCH_PKGS"); - if(ebp!=null) { - String[] ebps = Split.splitTrim(':', ebp); - String[] temp = new String[ebps.length + pkgs.length]; - System.arraycopy(pkgs,0, temp, 0, pkgs.length); - System.arraycopy(ebps,0,temp,pkgs.length,ebps.length); - pkgs = temp; - } - - for(String p : pkgs) { - try { - cls = ClassLoader.getSystemClassLoader().loadClass(p + '.' + toolName); - int lastDot = p.lastIndexOf('.'); - if(p.length()>0 || p.length()!=lastDot) { - StringBuilder sb = new StringBuilder(); - sb.append(Character.toUpperCase(p.charAt(++lastDot))); - while(++lastDot<p.length()) { - sb.append(p.charAt(lastDot)); - } - sb.append(':'); - classifier = sb.toString(); - break; - } - } catch (ClassNotFoundException e) { - cls = null; - } - } - if (cls != null) { - Constructor<?> cnst = cls.getConstructor(AuthzTrans.class); - batch = (Batch) cnst.newInstance(trans); - env.info().log("Begin", classifier, toolName); - } - - - if (batch == null) { - trans.error().log("No Batch named", toolName, "found"); - } - /* - * End New Batch Programs (inherit from Batch) here - */ - - } - if (batch != null) { - try { - batch.run(trans); - } catch (Exception e) { - if(cluster!=null && !cluster.isClosed()) { - cluster.close(); - } - trans.error().log(e); - } - } - } finally { - tt.done(); - if (batch != null) { - batch.close(trans); - } - StringBuilder sb = new StringBuilder("Task Times\n"); - trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE); - trans.info().log(sb); - } + access.setStreamLogIt(batchLog); + sbos.flush(); + batchLog.print(sbos.getBuffer()); + sbos = null; + Logger.getRootLogger().addAppender(new Log4JAccessAppender(access)); + + Batch batch = null; + AuthzTrans trans = env.newTrans(); + + TimeTaken tt = trans.start("Total Run", Env.SUB); + try { + int len = args.length; + if (len > 0) { + String toolName = args[0]; + len -= 1; + if (len < 0) + len = 0; + String nargs[] = new String[len]; + if (len > 0) { + System.arraycopy(args, 1, nargs, 0, len); + } + + env.put(ssargs = env.staticSlot("ARGS"), nargs); + + /* + * Add New Batch Programs (inherit from Batch) here + */ + + // Might be a Report, Update or Temp Batch + Class<?> cls = null; + String classifier = ""; + + String[] pkgs = new String[] { + "org.onap.aaf.auth.batch.update", + "org.onap.aaf.auth.batch.reports", + "org.onap.aaf.auth.batch.temp" + }; + + String ebp = env.getProperty("EXTRA_BATCH_PKGS"); + if(ebp!=null) { + String[] ebps = Split.splitTrim(':', ebp); + String[] temp = new String[ebps.length + pkgs.length]; + System.arraycopy(pkgs,0, temp, 0, pkgs.length); + System.arraycopy(ebps,0,temp,pkgs.length,ebps.length); + pkgs = temp; + } + + for(String p : pkgs) { + try { + cls = ClassLoader.getSystemClassLoader().loadClass(p + '.' + toolName); + int lastDot = p.lastIndexOf('.'); + if(p.length()>0 || p.length()!=lastDot) { + StringBuilder sb = new StringBuilder(); + sb.append(Character.toUpperCase(p.charAt(++lastDot))); + while(++lastDot<p.length()) { + sb.append(p.charAt(lastDot)); + } + sb.append(':'); + classifier = sb.toString(); + break; + } + } catch (ClassNotFoundException e) { + cls = null; + } + } + if (cls != null) { + Constructor<?> cnst = cls.getConstructor(AuthzTrans.class); + batch = (Batch) cnst.newInstance(trans); + env.info().log("Begin", classifier, toolName); + } + + + if (batch == null) { + trans.error().log("No Batch named", toolName, "found"); + } + /* + * End New Batch Programs (inherit from Batch) here + */ + + } + if (batch != null) { + try { + batch.run(trans); + } catch (Exception e) { + if(cluster!=null && !cluster.isClosed()) { + cluster.close(); + } + trans.error().log(e); + } + } + } finally { + tt.done(); + if (batch != null) { + batch.close(trans); + } + StringBuilder sb = new StringBuilder("Task Times\n"); + trans.auditTrail(4, sb, AuthzTrans.SUB, AuthzTrans.REMOTE); + trans.info().log(sb); + } } finally { - batchLog.close(); + batchLog.close(); } } catch (Exception e) { - if(cluster!=null && !cluster.isClosed()) { - cluster.close(); - } + if(cluster!=null && !cluster.isClosed()) { + cluster.close(); + } e.printStackTrace(System.err); } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/ApprovalSet.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/ApprovalSet.java index 661e40f7..163f1e2c 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/ApprovalSet.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/ApprovalSet.java @@ -35,67 +35,67 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.misc.env.util.Chrono; public class ApprovalSet { - private DataView dataview; - protected FutureDAO.Data fdd; - protected List<ApprovalDAO.Data> ladd; - - public ApprovalSet(final GregorianCalendar start, final String target, final DataView dv) { - dataview = dv; - fdd = new FutureDAO.Data(); - fdd.id = Chrono.dateToUUID(System.currentTimeMillis()); - fdd.target = target; - fdd.start = start.getTime(); - ladd = new ArrayList<>(); - } - - protected void setConstruct(final ByteBuffer bytes) { - fdd.construct = bytes; - } + private DataView dataview; + protected FutureDAO.Data fdd; + protected List<ApprovalDAO.Data> ladd; + + public ApprovalSet(final GregorianCalendar start, final String target, final DataView dv) { + dataview = dv; + fdd = new FutureDAO.Data(); + fdd.id = Chrono.dateToUUID(System.currentTimeMillis()); + fdd.target = target; + fdd.start = start.getTime(); + ladd = new ArrayList<>(); + } + + protected void setConstruct(final ByteBuffer bytes) { + fdd.construct = bytes; + } - protected void setMemo(final String memo) { - fdd.memo = memo; - } - - protected void setExpires(final GregorianCalendar expires) { - fdd.expires = expires.getTime(); - } - - public Result<Void> write(AuthzTrans trans) { - StringBuilder errs = null; - if(ladd == null || ladd.isEmpty()) { - errs = new StringBuilder("No Approvers for "); - errs .append(fdd.memo); - } else { - Result<FutureDAO.Data> rf = dataview.insert(trans, fdd); - if(rf.notOK()) { - errs = new StringBuilder(); - errs.append(rf.errorString()); - } else { - for(ApprovalDAO.Data add : ladd) { - Result<ApprovalDAO.Data> af = dataview.insert(trans, add); - if(af.notOK()) { - if(errs==null) { - errs = new StringBuilder(); - } else { - errs.append('\n'); - } - errs.append(af.errorString()); - } - } - } - } - return errs==null?Result.ok():Result.err(Result.ERR_Backend,errs.toString()); - } + protected void setMemo(final String memo) { + fdd.memo = memo; + } + + protected void setExpires(final GregorianCalendar expires) { + fdd.expires = expires.getTime(); + } + + public Result<Void> write(AuthzTrans trans) { + StringBuilder errs = null; + if(ladd == null || ladd.isEmpty()) { + errs = new StringBuilder("No Approvers for "); + errs .append(fdd.memo); + } else { + Result<FutureDAO.Data> rf = dataview.insert(trans, fdd); + if(rf.notOK()) { + errs = new StringBuilder(); + errs.append(rf.errorString()); + } else { + for(ApprovalDAO.Data add : ladd) { + Result<ApprovalDAO.Data> af = dataview.insert(trans, add); + if(af.notOK()) { + if(errs==null) { + errs = new StringBuilder(); + } else { + errs.append('\n'); + } + errs.append(af.errorString()); + } + } + } + } + return errs==null?Result.ok():Result.err(Result.ERR_Backend,errs.toString()); + } - public boolean hasApprovals() { - return !ladd.isEmpty(); - } - - public Set<String> approvers() { - Set<String> rv = new HashSet<>(); - for(ApprovalDAO.Data app : ladd) { - rv.add(app.approver); - } - return rv; - } + public boolean hasApprovals() { + return !ladd.isEmpty(); + } + + public Set<String> approvers() { + Set<String> rv = new HashSet<>(); + for(ApprovalDAO.Data app : ladd) { + rv.add(app.approver); + } + return rv; + } }
\ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/DataView.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/DataView.java index 3b90f3a9..c197f7f2 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/DataView.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/DataView.java @@ -37,7 +37,7 @@ import org.onap.aaf.auth.layer.Result; * 2) tested in Memory * 3) combined for REAL time by running Cached Memory * 4) Streamable in - * a) Binary + * a) Binary * b) CSV * c) JSON * d) XML @@ -46,7 +46,7 @@ import org.onap.aaf.auth.layer.Result; * But in the end, it looks like: * 1) Data Structures * 2) Find the Data Structures by various means, accounting for - * a) Multiple Responses + * a) Multiple Responses * b) Errors from the deepest level, made available through the call stack * 3) * @@ -54,20 +54,20 @@ import org.onap.aaf.auth.layer.Result; * */ public interface DataView { - // Reads - public Result<NsDAO.Data> ns(final AuthzTrans trans, final String id); - public Result<RoleDAO.Data> roleByName(final AuthzTrans trans, final String name); - public Result<List<UserRoleDAO.Data>> ursByRole(final AuthzTrans trans, final String role); - public Result<List<UserRoleDAO.Data>> ursByUser(final AuthzTrans trans, final String user); + // Reads + public Result<NsDAO.Data> ns(final AuthzTrans trans, final String id); + public Result<RoleDAO.Data> roleByName(final AuthzTrans trans, final String name); + public Result<List<UserRoleDAO.Data>> ursByRole(final AuthzTrans trans, final String role); + public Result<List<UserRoleDAO.Data>> ursByUser(final AuthzTrans trans, final String user); - // Inserts - public Result<ApprovalDAO.Data> insert(final AuthzTrans trans, final ApprovalDAO.Data add); - public Result<FutureDAO.Data> insert(final AuthzTrans trans, final FutureDAO.Data add); - - // Deletes - public Result<ApprovalDAO.Data> delete(final AuthzTrans trans, final ApprovalDAO.Data add); - public Result<FutureDAO.Data> delete(final AuthzTrans trans, final FutureDAO.Data add); - - // Clear any buffers - public void flush(); + // Inserts + public Result<ApprovalDAO.Data> insert(final AuthzTrans trans, final ApprovalDAO.Data add); + public Result<FutureDAO.Data> insert(final AuthzTrans trans, final FutureDAO.Data add); + + // Deletes + public Result<ApprovalDAO.Data> delete(final AuthzTrans trans, final ApprovalDAO.Data add); + public Result<FutureDAO.Data> delete(final AuthzTrans trans, final FutureDAO.Data add); + + // Clear any buffers + public void flush(); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Loader.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Loader.java index 806599e0..8bade4a4 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Loader.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Loader.java @@ -23,5 +23,5 @@ package org.onap.aaf.auth.batch.approvalsets; import org.onap.aaf.cadi.CadiException; public interface Loader<T> { - public T load() throws CadiException; + public T load() throws CadiException; } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Pending.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Pending.java index 5d720c2f..eed67338 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Pending.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Pending.java @@ -28,82 +28,82 @@ import org.onap.aaf.cadi.util.CSV.Writer; import org.onap.aaf.misc.env.util.Chrono; public class Pending { - public static final String REMIND = "remind"; - - int qty; - boolean hasNew; - Date earliest; - - /** - * Use this constructor to indicate when last Notified - * @param last_notified - */ - public Pending(Date last_notified) { - qty = 1; - hasNew = last_notified==null; - earliest = last_notified; - } + public static final String REMIND = "remind"; + + int qty; + boolean hasNew; + Date earliest; + + /** + * Use this constructor to indicate when last Notified + * @param last_notified + */ + public Pending(Date last_notified) { + qty = 1; + hasNew = last_notified==null; + earliest = last_notified; + } - /** - * Create from CSV Row - * @param row - * @throws ParseException - */ - public Pending(List<String> row) throws ParseException { - hasNew = Boolean.parseBoolean(row.get(2)); - String d = row.get(3); - if(d==null || d.isEmpty()) { - earliest = null; - } else { - earliest = Chrono.dateOnlyFmt.parse(d); - } - qty = Integer.parseInt(row.get(4)); - } + /** + * Create from CSV Row + * @param row + * @throws ParseException + */ + public Pending(List<String> row) throws ParseException { + hasNew = Boolean.parseBoolean(row.get(2)); + String d = row.get(3); + if(d==null || d.isEmpty()) { + earliest = null; + } else { + earliest = Chrono.dateOnlyFmt.parse(d); + } + qty = Integer.parseInt(row.get(4)); + } - /** - * Write CSV Row - * @param approveCW - * @param key - */ - public void row(Writer approveCW, String key) { - approveCW.row(REMIND,key,hasNew,Chrono.dateOnlyStamp(earliest),qty); - } + /** + * Write CSV Row + * @param approveCW + * @param key + */ + public void row(Writer approveCW, String key) { + approveCW.row(REMIND,key,hasNew,Chrono.dateOnlyStamp(earliest),qty); + } - public void inc() { - ++qty; - } - - public void inc(Pending value) { - qty+=value.qty; - if(earliest==null) { - earliest = value.earliest; - } else if(value.earliest!=null && value.earliest.before(earliest)) { - earliest = value.earliest; - } - } + public void inc() { + ++qty; + } + + public void inc(Pending value) { + qty+=value.qty; + if(earliest==null) { + earliest = value.earliest; + } else if(value.earliest!=null && value.earliest.before(earliest)) { + earliest = value.earliest; + } + } - public void earliest(Date lastnotified) { - if(lastnotified==null) { - hasNew=true; - } else if (earliest==null || lastnotified.before(earliest)) { - earliest = lastnotified; - } - } - - public int qty() { - return qty; - } - - public Date earliest() { - return earliest; - } - - public boolean newApprovals() { - return hasNew; - } + public void earliest(Date lastnotified) { + if(lastnotified==null) { + hasNew=true; + } else if (earliest==null || lastnotified.before(earliest)) { + earliest = lastnotified; + } + } + + public int qty() { + return qty; + } + + public Date earliest() { + return earliest; + } + + public boolean newApprovals() { + return hasNew; + } - public static Pending create() { - return new Pending((Date)null); - } + public static Pending create() { + return new Pending((Date)null); + } }
\ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Ticket.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Ticket.java index 1259c87e..1884262f 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Ticket.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/Ticket.java @@ -27,11 +27,11 @@ import org.onap.aaf.auth.batch.helpers.Approval; import org.onap.aaf.auth.batch.helpers.Future; public class Ticket { - public final Future f; - public final Set<Approval> approvals; - - public Ticket(Future future) { - this.f = future; - approvals = new HashSet<>(); - } + public final Future f; + public final Set<Approval> approvals; + + public Ticket(Future future) { + this.f = future; + approvals = new HashSet<>(); + } }
\ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/URApprovalSet.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/URApprovalSet.java index 91006c41..da13e84c 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/URApprovalSet.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/approvalsets/URApprovalSet.java @@ -41,111 +41,111 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.misc.env.util.Chrono; public class URApprovalSet extends ApprovalSet { - private static final String FMT_SUFFIX = "%s] - Expires %s"; - private static final String EXTEND_ACCESS_FMT = Approval.RE_APPROVAL_IN_ROLE + "%s] to Role [" + FMT_SUFFIX; - private static final String REVALIDATE_AS_ADMIN_FMT = Approval.RE_VALIDATE_ADMIN + FMT_SUFFIX; - private static final String REVALIDATE_AS_OWNER_FMT = Approval.RE_VALIDATE_OWNER + FMT_SUFFIX; + private static final String FMT_SUFFIX = "%s] - Expires %s"; + private static final String EXTEND_ACCESS_FMT = Approval.RE_APPROVAL_IN_ROLE + "%s] to Role [" + FMT_SUFFIX; + private static final String REVALIDATE_AS_ADMIN_FMT = Approval.RE_VALIDATE_ADMIN + FMT_SUFFIX; + private static final String REVALIDATE_AS_OWNER_FMT = Approval.RE_VALIDATE_OWNER + FMT_SUFFIX; - public URApprovalSet(final AuthzTrans trans, final GregorianCalendar start, final DataView dv, final Loader<UserRoleDAO.Data> lurdd) throws IOException, CadiException { - super(start, "user_role", dv); - Organization org = trans.org(); - UserRoleDAO.Data urdd = lurdd.load(); - setConstruct(urdd.bytify()); - setMemo(getMemo(urdd)); - GregorianCalendar expires = org.expiration(null, Organization.Expiration.UserInRole); - if(urdd.expires.before(expires.getTime())) { - expires.setTime(urdd.expires); - } - setExpires(expires); - setTargetKey(urdd.user+'|'+urdd.role); - setTargetDate(urdd.expires); - - Result<RoleDAO.Data> r = dv.roleByName(trans, urdd.role); - if(r.notOKorIsEmpty()) { - throw new CadiException(r.errorString()); - } - Result<NsDAO.Data> n = dv.ns(trans, urdd.ns); - if(n.notOKorIsEmpty()) { - throw new CadiException(n.errorString()); - } - UserRoleDAO.Data found = null; - Result<List<Data>> lur = dv.ursByRole(trans, urdd.role); - if(lur.isOK()) { - for(UserRoleDAO.Data ur : lur.value) { - if(urdd.user.equals(ur.user)) { - found = ur; - break; - } - } - } - if(found==null) { - throw new CadiException(String.format("User '%s' in Role '%s' does not exist", urdd.user,urdd.role)); - } - - // Primarily, Owners are responsible, unless it's owned by self - boolean isOwner = false; - Result<List<UserRoleDAO.Data>> owners = dv.ursByRole(trans, urdd.ns+".owner"); - if(owners.isOK()) { - for(UserRoleDAO.Data owner : owners.value) { - if(urdd.user.equals(owner.user)) { - isOwner = true; - } else { - ApprovalDAO.Data add = newApproval(urdd); - add.approver = owner.user; - add.type="owner"; - ladd.add(add); - } - } - } + public URApprovalSet(final AuthzTrans trans, final GregorianCalendar start, final DataView dv, final Loader<UserRoleDAO.Data> lurdd) throws IOException, CadiException { + super(start, "user_role", dv); + Organization org = trans.org(); + UserRoleDAO.Data urdd = lurdd.load(); + setConstruct(urdd.bytify()); + setMemo(getMemo(urdd)); + GregorianCalendar expires = org.expiration(null, Organization.Expiration.UserInRole); + if(urdd.expires.before(expires.getTime())) { + expires.setTime(urdd.expires); + } + setExpires(expires); + setTargetKey(urdd.user+'|'+urdd.role); + setTargetDate(urdd.expires); + + Result<RoleDAO.Data> r = dv.roleByName(trans, urdd.role); + if(r.notOKorIsEmpty()) { + throw new CadiException(r.errorString()); + } + Result<NsDAO.Data> n = dv.ns(trans, urdd.ns); + if(n.notOKorIsEmpty()) { + throw new CadiException(n.errorString()); + } + UserRoleDAO.Data found = null; + Result<List<Data>> lur = dv.ursByRole(trans, urdd.role); + if(lur.isOK()) { + for(UserRoleDAO.Data ur : lur.value) { + if(urdd.user.equals(ur.user)) { + found = ur; + break; + } + } + } + if(found==null) { + throw new CadiException(String.format("User '%s' in Role '%s' does not exist", urdd.user,urdd.role)); + } + + // Primarily, Owners are responsible, unless it's owned by self + boolean isOwner = false; + Result<List<UserRoleDAO.Data>> owners = dv.ursByRole(trans, urdd.ns+".owner"); + if(owners.isOK()) { + for(UserRoleDAO.Data owner : owners.value) { + if(urdd.user.equals(owner.user)) { + isOwner = true; + } else { + ApprovalDAO.Data add = newApproval(urdd); + add.approver = owner.user; + add.type="owner"; + ladd.add(add); + } + } + } - if(isOwner) { - try { - List<Identity> apprs = org.getApprovers(trans, urdd.user); - if(apprs!=null) { - for(Identity i : apprs) { - ApprovalDAO.Data add = newApproval(urdd); - add.approver = i.fullID(); - add.type = org.getApproverType(); - ladd.add(add); - } - } - } catch (OrganizationException e) { - throw new CadiException(e); - } - } - } - - private void setTargetDate(Date expires) { - fdd.target_date = expires; - } + if(isOwner) { + try { + List<Identity> apprs = org.getApprovers(trans, urdd.user); + if(apprs!=null) { + for(Identity i : apprs) { + ApprovalDAO.Data add = newApproval(urdd); + add.approver = i.fullID(); + add.type = org.getApproverType(); + ladd.add(add); + } + } + } catch (OrganizationException e) { + throw new CadiException(e); + } + } + } + + private void setTargetDate(Date expires) { + fdd.target_date = expires; + } - private void setTargetKey(String key) { - fdd.target_key = key; - } + private void setTargetKey(String key) { + fdd.target_key = key; + } - private ApprovalDAO.Data newApproval(UserRoleDAO.Data urdd) { - ApprovalDAO.Data add = new ApprovalDAO.Data(); - add.id = Chrono.dateToUUID(System.currentTimeMillis()); - add.ticket = fdd.id; - add.user = urdd.user; - add.operation = FUTURE_OP.A.name(); - add.status = ApprovalDAO.PENDING; - add.memo = getMemo(urdd); - return add; - } + private ApprovalDAO.Data newApproval(UserRoleDAO.Data urdd) { + ApprovalDAO.Data add = new ApprovalDAO.Data(); + add.id = Chrono.dateToUUID(System.currentTimeMillis()); + add.ticket = fdd.id; + add.user = urdd.user; + add.operation = FUTURE_OP.A.name(); + add.status = ApprovalDAO.PENDING; + add.memo = getMemo(urdd); + return add; + } - private String getMemo(Data urdd) { - switch(urdd.rname) { - case "owner": - return String.format(REVALIDATE_AS_OWNER_FMT,urdd.ns,Chrono.dateOnlyStamp(urdd.expires)); - case "admin": - return String.format(REVALIDATE_AS_ADMIN_FMT,urdd.ns,Chrono.dateOnlyStamp(urdd.expires)); - default: - return String.format(EXTEND_ACCESS_FMT, - urdd.user, - urdd.role, - Chrono.dateOnlyStamp(urdd.expires)); - } - } + private String getMemo(Data urdd) { + switch(urdd.rname) { + case "owner": + return String.format(REVALIDATE_AS_OWNER_FMT,urdd.ns,Chrono.dateOnlyStamp(urdd.expires)); + case "admin": + return String.format(REVALIDATE_AS_ADMIN_FMT,urdd.ns,Chrono.dateOnlyStamp(urdd.expires)); + default: + return String.format(EXTEND_ACCESS_FMT, + urdd.user, + urdd.role, + Chrono.dateOnlyStamp(urdd.expires)); + } + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java index c32db2e2..a9029626 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Approval.java @@ -45,7 +45,7 @@ import com.datastax.driver.core.SimpleStatement; import com.datastax.driver.core.Statement; public class Approval implements CacheChange.Data { - public static final String ADD_USER_TO_ROLE = "Add User ["; + public static final String ADD_USER_TO_ROLE = "Add User ["; public static final String RE_APPROVAL_IN_ROLE = "Extend access of User ["; public static final String RE_VALIDATE_ADMIN = "Revalidate as Admin of AAF Namespace ["; public static final String RE_VALIDATE_OWNER = "Revalidate as Owner of AAF Namespace ["; @@ -139,14 +139,14 @@ public class Approval implements CacheChange.Data { } else if (memo.startsWith(RE_VALIDATE_OWNER)) { return role + ".owner"; } else { - first = memo.indexOf('[',second); - if(first>=0) { - second = memo.indexOf(']', ++first); - if(second>=0 && (memo.startsWith(RE_APPROVAL_IN_ROLE) || + first = memo.indexOf('[',second); + if(first>=0) { + second = memo.indexOf(']', ++first); + if(second>=0 && (memo.startsWith(RE_APPROVAL_IN_ROLE) || memo.startsWith(ADD_USER_TO_ROLE))) { - return memo.substring(first, second); - } - } + return memo.substring(first, second); + } + } } } } @@ -154,47 +154,47 @@ public class Approval implements CacheChange.Data { } public static int load(Trans trans, Session session, Creator<Approval> creator, Visitor<Approval> visitor) { - int count = 0; - try { - count+=call(trans,session,creator.query(null), creator, visitor); + int count = 0; + try { + count+=call(trans,session,creator.query(null), creator, visitor); } finally { trans.info().log("Found",count,"Approval Records"); } - return count; + return count; } - public static int load(Trans trans, Session session, Creator<Approval> creator ) { - int count = 0; - try { - count+=call(trans,session,creator.query(null), creator, FullLoad); + public static int load(Trans trans, Session session, Creator<Approval> creator ) { + int count = 0; + try { + count+=call(trans,session,creator.query(null), creator, FullLoad); } finally { trans.info().log("Found",count,"Approval Records"); } - return count; + return count; } public static int loadUsers(Trans trans, Session session, Set<String> users, Visitor<Approval> visitor) { - int total = 0; - for(String user : users) { - total+=call(trans,session,String.format("%s WHERE user='%s';",v2_0_17.select(), user),v2_0_17,visitor); - } - return total; + int total = 0; + for(String user : users) { + total+=call(trans,session,String.format("%s WHERE user='%s';",v2_0_17.select(), user),v2_0_17,visitor); + } + return total; } public static void row(CSV.RowSetter crs, Approval app) { - crs.row("approval",app.add.id,app.add.ticket,app.add.user,app.role,app.add.memo); - } + crs.row("approval",app.add.id,app.add.ticket,app.add.user,app.role,app.add.memo); + } - private static int call(Trans trans, Session session, String query, Creator<Approval> creator, Visitor<Approval> visitor) { - TimeTaken tt = trans.start("DB Query", Trans.REMOTE); + private static int call(Trans trans, Session session, String query, Creator<Approval> creator, Visitor<Approval> visitor) { + TimeTaken tt = trans.start("DB Query", Trans.REMOTE); ResultSet results; try { Statement stmt = new SimpleStatement( query ); results = session.execute(stmt); int count = 0; for (Row row : results.all()) { - ++count; - visitor.visit(creator.create(row)); + ++count; + visitor.visit(creator.create(row)); } return count; } finally { @@ -223,11 +223,11 @@ public class Approval implements CacheChange.Data { } public static void clear() { - byApprover.clear(); - byUser.clear(); - byTicket.clear(); - list.clear(); - cache.resetLocalData(); + byApprover.clear(); + byUser.clear(); + byTicket.clear(); + list.clear(); + cache.resetLocalData(); } /** @@ -332,10 +332,10 @@ public class Approval implements CacheChange.Data { return cache.contains(a); } - public static void deleteByIDBatch(StringBuilder sb, String id) { - sb.append("DELETE from authz.approval where id="); - sb.append(id); - sb.append(";\n"); - } + public static void deleteByIDBatch(StringBuilder sb, String id) { + sb.append("DELETE from authz.approval where id="); + sb.append(id); + sb.append(";\n"); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/BatchDataView.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/BatchDataView.java index 9f269d0d..ab3a49fa 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/BatchDataView.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/BatchDataView.java @@ -42,147 +42,147 @@ import org.onap.aaf.misc.env.util.Chrono; import com.datastax.driver.core.Session; public class BatchDataView implements DataView { - private static final String QUOTE_PAREN_SEMI = "');\n"; - private static final String QUOTE_COMMA = "',"; - private static final String QUOTE_COMMA_QUOTE = "','"; - private static final String COMMA_QUOTE = ",'"; - private final CQLBatchLoop cqlBatch; - private final Session session; + private static final String QUOTE_PAREN_SEMI = "');\n"; + private static final String QUOTE_COMMA = "',"; + private static final String QUOTE_COMMA_QUOTE = "','"; + private static final String COMMA_QUOTE = ",'"; + private final CQLBatchLoop cqlBatch; + private final Session session; - public BatchDataView(final AuthzTrans trans, final Session session, final boolean dryRun ) throws APIException, IOException { - this.session = session; - cqlBatch = new CQLBatchLoop(new CQLBatch(trans.info(),session),50,dryRun); - } + public BatchDataView(final AuthzTrans trans, final Session session, final boolean dryRun ) throws APIException, IOException { + this.session = session; + cqlBatch = new CQLBatchLoop(new CQLBatch(trans.info(),session),50,dryRun); + } - public Session getSession(AuthzTrans trans) throws APIException, IOException { - return session; - } - - public Result<NsDAO.Data> ns(AuthzTrans trans, String id) { - NS n; - TimeTaken tt = trans.start("Get NS by ID %s", Trans.SUB, id); - try { - n=NS.data.get(id); - } finally { - tt.done(); - } - - if(n==null || n.ndd==null) { - return Result.err(Result.ERR_Backend,"Namespace '%s' does not exist", id); - } - return Result.ok(n.ndd); - } + public Session getSession(AuthzTrans trans) throws APIException, IOException { + return session; + } + + public Result<NsDAO.Data> ns(AuthzTrans trans, String id) { + NS n; + TimeTaken tt = trans.start("Get NS by ID %s", Trans.SUB, id); + try { + n=NS.data.get(id); + } finally { + tt.done(); + } + + if(n==null || n.ndd==null) { + return Result.err(Result.ERR_Backend,"Namespace '%s' does not exist", id); + } + return Result.ok(n.ndd); + } - - @Override - public Result<RoleDAO.Data> roleByName(AuthzTrans trans, String name) { - Role r = Role.byName.get(name); - if(r==null || r.rdd==null) { - return Result.err(Result.ERR_Backend,"Role '%s' does not exist", name); - } - return Result.ok(r.rdd); - } + + @Override + public Result<RoleDAO.Data> roleByName(AuthzTrans trans, String name) { + Role r = Role.byName.get(name); + if(r==null || r.rdd==null) { + return Result.err(Result.ERR_Backend,"Role '%s' does not exist", name); + } + return Result.ok(r.rdd); + } - @Override - public Result<List<UserRoleDAO.Data>> ursByRole(AuthzTrans trans, String role) { - List<UserRole> urs = UserRole.getByRole().get(role); - if(urs==null) { - return Result.err(Result.ERR_Backend, "UserRoles for Role '%s' does not exist", role); - } - return toLURDD(urs); - } + @Override + public Result<List<UserRoleDAO.Data>> ursByRole(AuthzTrans trans, String role) { + List<UserRole> urs = UserRole.getByRole().get(role); + if(urs==null) { + return Result.err(Result.ERR_Backend, "UserRoles for Role '%s' does not exist", role); + } + return toLURDD(urs); + } - private Result<List<Data>> toLURDD(List<UserRole> urs) { - List<UserRoleDAO.Data> rv = new ArrayList<>(); - if(urs!=null) { - for(UserRole ur : urs) { - rv.add(ur.urdd()); - } - } - return Result.ok(rv); - } + private Result<List<Data>> toLURDD(List<UserRole> urs) { + List<UserRoleDAO.Data> rv = new ArrayList<>(); + if(urs!=null) { + for(UserRole ur : urs) { + rv.add(ur.urdd()); + } + } + return Result.ok(rv); + } - @Override - public Result<List<UserRoleDAO.Data>> ursByUser(AuthzTrans trans, String user) { - List<UserRole> urs = UserRole.getByUser().get(user); - if(urs==null) { - return Result.err(Result.ERR_Backend, "UserRoles for User '%s' does not exist", user); - } - return toLURDD(urs); - } + @Override + public Result<List<UserRoleDAO.Data>> ursByUser(AuthzTrans trans, String user) { + List<UserRole> urs = UserRole.getByUser().get(user); + if(urs==null) { + return Result.err(Result.ERR_Backend, "UserRoles for User '%s' does not exist", user); + } + return toLURDD(urs); + } - @Override - public Result<FutureDAO.Data> delete(AuthzTrans trans, FutureDAO.Data fdd) { - StringBuilder sb = cqlBatch.inc(); - sb.append("DELETE from authz.future WHERE id = "); - sb.append(fdd.id.toString()); - return Result.ok(fdd); - } - - @Override - public Result<ApprovalDAO.Data> delete(AuthzTrans trans, ApprovalDAO.Data add) { - StringBuilder sb = cqlBatch.inc(); - sb.append("DELETE from authz.approval WHERE id = "); - sb.append(add.id.toString()); - return Result.ok(add); - } + @Override + public Result<FutureDAO.Data> delete(AuthzTrans trans, FutureDAO.Data fdd) { + StringBuilder sb = cqlBatch.inc(); + sb.append("DELETE from authz.future WHERE id = "); + sb.append(fdd.id.toString()); + return Result.ok(fdd); + } + + @Override + public Result<ApprovalDAO.Data> delete(AuthzTrans trans, ApprovalDAO.Data add) { + StringBuilder sb = cqlBatch.inc(); + sb.append("DELETE from authz.approval WHERE id = "); + sb.append(add.id.toString()); + return Result.ok(add); + } - @Override - public Result<ApprovalDAO.Data> insert(AuthzTrans trans, ApprovalDAO.Data add) { - StringBuilder sb = cqlBatch.inc(); - sb.append("INSERT INTO authz.approval (id,approver,memo,operation,status,ticket,type,user) VALUES ("); - sb.append(add.id.toString()); - sb.append(COMMA_QUOTE); - sb.append(add.approver); -// sb.append(QUOTE_COMMA_QUOTE); -// sb.append(Chrono.utcStamp(add.last_notified)); - sb.append(QUOTE_COMMA_QUOTE); - sb.append(add.memo.replace("'", "''")); - sb.append(QUOTE_COMMA_QUOTE); - sb.append(add.operation); - sb.append(QUOTE_COMMA_QUOTE); - sb.append(add.status); - sb.append(QUOTE_COMMA); - sb.append(add.ticket.toString()); - sb.append(COMMA_QUOTE); - sb.append(add.type); - sb.append(QUOTE_COMMA_QUOTE); - sb.append(add.user); - sb.append(QUOTE_PAREN_SEMI); - return Result.ok(add); - } + @Override + public Result<ApprovalDAO.Data> insert(AuthzTrans trans, ApprovalDAO.Data add) { + StringBuilder sb = cqlBatch.inc(); + sb.append("INSERT INTO authz.approval (id,approver,memo,operation,status,ticket,type,user) VALUES ("); + sb.append(add.id.toString()); + sb.append(COMMA_QUOTE); + sb.append(add.approver); +// sb.append(QUOTE_COMMA_QUOTE); +// sb.append(Chrono.utcStamp(add.last_notified)); + sb.append(QUOTE_COMMA_QUOTE); + sb.append(add.memo.replace("'", "''")); + sb.append(QUOTE_COMMA_QUOTE); + sb.append(add.operation); + sb.append(QUOTE_COMMA_QUOTE); + sb.append(add.status); + sb.append(QUOTE_COMMA); + sb.append(add.ticket.toString()); + sb.append(COMMA_QUOTE); + sb.append(add.type); + sb.append(QUOTE_COMMA_QUOTE); + sb.append(add.user); + sb.append(QUOTE_PAREN_SEMI); + return Result.ok(add); + } - @Override - public Result<FutureDAO.Data> insert(AuthzTrans trans, FutureDAO.Data fdd) { - StringBuilder sb = cqlBatch.inc(); - sb.append("INSERT INTO authz.future (id,construct,expires,memo,start,target,target_key,target_date) VALUES ("); - sb.append(fdd.id.toString()); - sb.append(','); - fdd.construct.hasArray(); - sb.append(Hash.toHex(fdd.construct.array())); - sb.append(COMMA_QUOTE); - sb.append(Chrono.utcStamp(fdd.expires)); - sb.append(QUOTE_COMMA_QUOTE); - sb.append(fdd.memo.replace("'", "''")); - sb.append(QUOTE_COMMA_QUOTE); - sb.append(Chrono.utcStamp(fdd.expires)); - sb.append(QUOTE_COMMA_QUOTE); - sb.append(fdd.target); - if(fdd.target_key==null) { - sb.append("',,'"); - } else { - sb.append(QUOTE_COMMA_QUOTE); - sb.append(fdd.target_key==null?"":fdd.target_key); - sb.append(QUOTE_COMMA_QUOTE); - } - sb.append(Chrono.utcStamp(fdd.target_date)); - sb.append(QUOTE_PAREN_SEMI); - return Result.ok(fdd); - } - - @Override - public void flush() { - cqlBatch.flush(); - } + @Override + public Result<FutureDAO.Data> insert(AuthzTrans trans, FutureDAO.Data fdd) { + StringBuilder sb = cqlBatch.inc(); + sb.append("INSERT INTO authz.future (id,construct,expires,memo,start,target,target_key,target_date) VALUES ("); + sb.append(fdd.id.toString()); + sb.append(','); + fdd.construct.hasArray(); + sb.append(Hash.toHex(fdd.construct.array())); + sb.append(COMMA_QUOTE); + sb.append(Chrono.utcStamp(fdd.expires)); + sb.append(QUOTE_COMMA_QUOTE); + sb.append(fdd.memo.replace("'", "''")); + sb.append(QUOTE_COMMA_QUOTE); + sb.append(Chrono.utcStamp(fdd.expires)); + sb.append(QUOTE_COMMA_QUOTE); + sb.append(fdd.target); + if(fdd.target_key==null) { + sb.append("',,'"); + } else { + sb.append(QUOTE_COMMA_QUOTE); + sb.append(fdd.target_key==null?"":fdd.target_key); + sb.append(QUOTE_COMMA_QUOTE); + } + sb.append(Chrono.utcStamp(fdd.target_date)); + sb.append(QUOTE_PAREN_SEMI); + return Result.ok(fdd); + } + + @Override + public void flush() { + cqlBatch.flush(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java index 4547fb1b..b626bae7 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatch.java @@ -26,74 +26,74 @@ import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; public class CQLBatch { - private Session session; - private StringBuilder sb; - private int hasAdded; - private LogTarget log; + private Session session; + private StringBuilder sb; + private int hasAdded; + private LogTarget log; - public CQLBatch(LogTarget log, Session session) { - this.log = log; - this.session = session; - sb = new StringBuilder(); - hasAdded = 0; - } - public StringBuilder begin() { - sb.setLength(0); - sb.append("BEGIN BATCH\n"); - hasAdded = sb.length(); - return sb; - } - - private boolean end() { - if(sb.length()==hasAdded) { - return false; - } else { - sb.append("APPLY BATCH;\n"); - log.log(sb); - return true; - } - } - - public ResultSet execute() { - if(end()) { - return session.execute(sb.toString()); - } else { - return null; - } - } - - public ResultSet execute(boolean dryRun) { - ResultSet rv = null; - if(dryRun) { - end(); - } else { - rv = execute(); - } - sb.setLength(0); - return rv; - } - - public ResultSet singleExec(StringBuilder query, boolean dryRun) { - if(dryRun) { - return null; - } else { - return session.execute(query.toString()); - } - } - - public void touch(String table, int begin, int end, boolean dryRun) { - StringBuilder sb = begin(); - for(int i=begin;i<end;++i) { - sb.append("UPDATE cache SET touched=dateof(now()) WHERE name='"); - sb.append(table); - sb.append("' AND seg="); - sb.append(i); - sb.append(";\n"); - } - execute(dryRun); - } - - public String toString() { - return sb.toString(); - } + public CQLBatch(LogTarget log, Session session) { + this.log = log; + this.session = session; + sb = new StringBuilder(); + hasAdded = 0; + } + public StringBuilder begin() { + sb.setLength(0); + sb.append("BEGIN BATCH\n"); + hasAdded = sb.length(); + return sb; + } + + private boolean end() { + if(sb.length()==hasAdded) { + return false; + } else { + sb.append("APPLY BATCH;\n"); + log.log(sb); + return true; + } + } + + public ResultSet execute() { + if(end()) { + return session.execute(sb.toString()); + } else { + return null; + } + } + + public ResultSet execute(boolean dryRun) { + ResultSet rv = null; + if(dryRun) { + end(); + } else { + rv = execute(); + } + sb.setLength(0); + return rv; + } + + public ResultSet singleExec(StringBuilder query, boolean dryRun) { + if(dryRun) { + return null; + } else { + return session.execute(query.toString()); + } + } + + public void touch(String table, int begin, int end, boolean dryRun) { + StringBuilder sb = begin(); + for(int i=begin;i<end;++i) { + sb.append("UPDATE cache SET touched=dateof(now()) WHERE name='"); + sb.append(table); + sb.append("' AND seg="); + sb.append(i); + sb.append(";\n"); + } + execute(dryRun); + } + + public String toString() { + return sb.toString(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatchLoop.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatchLoop.java index 2836d041..2604364b 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatchLoop.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/CQLBatchLoop.java @@ -21,111 +21,111 @@ package org.onap.aaf.auth.batch.helpers; public class CQLBatchLoop { - private static final int MAX_CHARS = (50 * 1024)/2; - - private final CQLBatch cqlBatch; - private final int maxBatch; - private final StringBuilder sb; - private final boolean dryRun; - private int i; - private int total; - private int batches; - private final StringBuilder current; - private boolean showProgress; - - public CQLBatchLoop(CQLBatch cb, int max, boolean dryRun) { - cqlBatch = cb; - i=0; - total = 0; - maxBatch = max; - sb = cqlBatch.begin(); - current = new StringBuilder(); - this.dryRun = dryRun; - showProgress = false; - } + private static final int MAX_CHARS = (50 * 1024)/2; + + private final CQLBatch cqlBatch; + private final int maxBatch; + private final StringBuilder sb; + private final boolean dryRun; + private int i; + private int total; + private int batches; + private final StringBuilder current; + private boolean showProgress; + + public CQLBatchLoop(CQLBatch cb, int max, boolean dryRun) { + cqlBatch = cb; + i=0; + total = 0; + maxBatch = max; + sb = cqlBatch.begin(); + current = new StringBuilder(); + this.dryRun = dryRun; + showProgress = false; + } - public CQLBatchLoop showProgress() { - showProgress = true; - return this; - } - /** - * Assume this is another line in the Batch - * @return - */ - public StringBuilder inc() { - if(i>=maxBatch || current.length()+sb.length()>MAX_CHARS) { - if(i>0) { - cqlBatch.execute(dryRun); - i = -1; - incBatch(); - } - } - if(i<0) { - cqlBatch.begin(); - i=0; - } - if(current.length() > MAX_CHARS) { - cqlBatch.singleExec(current, dryRun); - } else { - sb.append(current); - } - current.setLength(0); - ++i; - ++total; - return current; - } - - /** - * Close up when finished. - */ - public void flush() { - if(current.length()+sb.length()>MAX_CHARS) { - if(i>0) { - cqlBatch.execute(dryRun); - incBatch(); - } - if(current.length()>0) { - cqlBatch.singleExec(current, dryRun); - current.setLength(0); - incBatch(); - } - } else { - if(i<0) { - cqlBatch.begin(); - } - sb.append(current); - current.setLength(0); - cqlBatch.execute(dryRun); - incBatch(); - } - i=-1; - } + public CQLBatchLoop showProgress() { + showProgress = true; + return this; + } + /** + * Assume this is another line in the Batch + * @return + */ + public StringBuilder inc() { + if(i>=maxBatch || current.length()+sb.length()>MAX_CHARS) { + if(i>0) { + cqlBatch.execute(dryRun); + i = -1; + incBatch(); + } + } + if(i<0) { + cqlBatch.begin(); + i=0; + } + if(current.length() > MAX_CHARS) { + cqlBatch.singleExec(current, dryRun); + } else { + sb.append(current); + } + current.setLength(0); + ++i; + ++total; + return current; + } + + /** + * Close up when finished. + */ + public void flush() { + if(current.length()+sb.length()>MAX_CHARS) { + if(i>0) { + cqlBatch.execute(dryRun); + incBatch(); + } + if(current.length()>0) { + cqlBatch.singleExec(current, dryRun); + current.setLength(0); + incBatch(); + } + } else { + if(i<0) { + cqlBatch.begin(); + } + sb.append(current); + current.setLength(0); + cqlBatch.execute(dryRun); + incBatch(); + } + i=-1; + } - private void incBatch() { - ++batches; - if(showProgress) { - System.out.print('.'); - if(batches%70==0) { - System.out.println(); - } - } - } + private void incBatch() { + ++batches; + if(showProgress) { + System.out.print('.'); + if(batches%70==0) { + System.out.println(); + } + } + } - public int total() { - return total; - } - - public int batches() { - return batches; - } + public int total() { + return total; + } + + public int batches() { + return batches; + } - public void reset() { - total = 0; - batches = 0; - i = -1; - } - - public String toString() { - return cqlBatch.toString(); - } + public void reset() { + total = 0; + batches = 0; + i = -1; + } + + public String toString() { + return cqlBatch.toString(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java index 9d0cfa7f..a4e4112f 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Creator.java @@ -28,22 +28,22 @@ public abstract class Creator<T> { public abstract String select(); public String suffix() { - return ""; + return ""; } public String query(String where) { StringBuilder sb = new StringBuilder(select()); if (where!=null) { sb.append(" WHERE "); - int index = where.indexOf(" ALLOW FILTERING"); - if(index< 0 ) { - sb.append(where); + int index = where.indexOf(" ALLOW FILTERING"); + if(index< 0 ) { + sb.append(where); sb.append(suffix()); - } else { - sb.append(where.substring(0, index)); + } else { + sb.append(where.substring(0, index)); sb.append(suffix()); sb.append(" ALLOW FILTERING"); - } + } } sb.append(';'); return sb.toString(); diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java index f5669331..1f5a1f40 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Cred.java @@ -79,29 +79,29 @@ public class Cred { * @return */ public List<Note> notes() { - return notes; + return notes; } public void addNote(int level, String note) { - if(notes==null) { - notes=new ArrayList<>(); - } - notes.add(new Note(level,note)); + if(notes==null) { + notes=new ArrayList<>(); + } + notes.add(new Note(level,note)); } public String toString() { - return expires.toString() + ": " + type + ' ' + tag; + return expires.toString() + ": " + type + ' ' + tag; } } public static class Note { - public final int level; - public final String note; - - public Note(int level, String note) { - this.level = level; - this.note = note; - } + public final int level; + public final String note; + + public Note(int level, String note) { + this.level = level; + this.note = note; + } } public Date last(final int ... types) { Date last = null; @@ -168,7 +168,7 @@ public class Cred { boolean hastype = false; for (int t : types) { if (t==type) { - hastype=true; + hastype=true; break; } } @@ -177,7 +177,7 @@ public class Cred { } } add(row.getString(0), row.getInt(1),row.getTimestamp(2),row.getInt(3),row.getLong(4), - row.getString(5)); + row.getString(5)); } } finally { tt.done(); @@ -188,13 +188,13 @@ public class Cred { } public static void add( - final String id, - final int type, - final Date timestamp, - final int other, - final long written, - final String tag - ) { + final String id, + final int type, + final Date timestamp, + final int other, + final long written, + final String tag + ) { Cred cred = data.get(id); if (cred==null) { cred = new Cred(id); @@ -216,10 +216,10 @@ public class Cred { if (!found) { lscd.add(cred); } - } + } - /** + /** * Count entries in Cred data. * Note, as opposed to other methods, need to load the whole cred table for the Types. * @param numbuckets @@ -306,28 +306,28 @@ public class Cred { } public void row(final CSV.Writer csvw, final Instance inst) { - csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires), - inst.expires.getTime(),inst.tag); + csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires), + inst.expires.getTime(),inst.tag); } public void row(final CSV.Writer csvw, final Instance inst, final String reason) { - csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires), - inst.expires.getTime(),inst.tag,reason); + csvw.row("cred",id,ns,Integer.toString(inst.type),Chrono.dateOnlyStamp(inst.expires), + inst.expires.getTime(),inst.tag,reason); } public static void batchDelete(StringBuilder sb, List<String> row) { - sb.append("DELETE from authz.cred WHERE id='"); - sb.append(row.get(1)); - sb.append("' AND type="); - sb.append(Integer.parseInt(row.get(3))); - // Note: We have to work with long, because Expires is part of Key... can't easily do date. - sb.append(" AND expires=dateof(maxtimeuuid("); - sb.append(row.get(5)); - sb.append("));\n"); - } + sb.append("DELETE from authz.cred WHERE id='"); + sb.append(row.get(1)); + sb.append("' AND type="); + sb.append(Integer.parseInt(row.get(3))); + // Note: We have to work with long, because Expires is part of Key... can't easily do date. + sb.append(" AND expires=dateof(maxtimeuuid("); + sb.append(row.get(5)); + sb.append("));\n"); + } - public String toString() { + public String toString() { StringBuilder sb = new StringBuilder(id); sb.append('['); for (Instance i : instances) { @@ -358,24 +358,24 @@ public class Cred { } - public static String histSubject(List<String> row) { - return row.get(1); - } + public static String histSubject(List<String> row) { + return row.get(1); + } - public static String histMemo(String fmt, String orgName, List<String> row) { - String reason; - if(row.size()>5) { // Reason included - reason = row.get(5); - } else { - reason = String.format(fmt, row.get(1),orgName,row.get(4)); - } - return reason; - } + public static String histMemo(String fmt, String orgName, List<String> row) { + String reason; + if(row.size()>5) { // Reason included + reason = row.get(5); + } else { + reason = String.format(fmt, row.get(1),orgName,row.get(4)); + } + return reason; + } - public static void clear() { - data.clear(); - byNS.clear(); - } + public static void clear() { + data.clear(); + byNS.clear(); + } }
\ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java index f742a465..c7d4e7d4 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/ExpireRange.java @@ -35,197 +35,197 @@ import org.onap.aaf.auth.org.Organization.Identity; import org.onap.aaf.cadi.Access; public class ExpireRange { - private static final String DELETE = "Delete"; - public static final String ONE_MONTH = "OneMonth"; - public static final String TWO_MONTH = "TwoMonth"; - public static final String TWO_WEEK = "TwoWeek"; - public static final String ONE_WEEK = "OneWeek"; - private static final String AAF_BATCH_RANGE = "aaf_batch_range."; - public final Map<String,List<Range>> ranges; - private final Map<Integer,Date> intervalDates; - private static final Date now = new Date(); - public final Range approveDelete ; + private static final String DELETE = "Delete"; + public static final String ONE_MONTH = "OneMonth"; + public static final String TWO_MONTH = "TwoMonth"; + public static final String TWO_WEEK = "TwoWeek"; + public static final String ONE_WEEK = "OneWeek"; + private static final String AAF_BATCH_RANGE = "aaf_batch_range."; + public final Map<String,List<Range>> ranges; + private final Map<Integer,Date> intervalDates; + private static final Date now = new Date(); + public final Range approveDelete ; - private Range delRange; - - public ExpireRange(final Access access) { - ranges = new HashMap<>(); - intervalDates = new HashMap<>(); - int i=0; - approveDelete = new Range(DELETE,0,0,0,-1,0,GregorianCalendar.DAY_OF_YEAR,-100); - String prop = access.getProperty(AAF_BATCH_RANGE + i,null); - if(prop==null && i==0) { - List<Range> lcred = getRangeList("cred"); - List<Range> lur = getRangeList("ur"); - List<Range> lx509 = getRangeList("x509"); - - - /* - Range(Name, ReportingLevel, PeopleInterval, AppInterval, Start(Type,Qty) End(Type,Qty) ) - Interval of -1 Means "only once" - Interval of 0 means none - Interval > 0 means only X number of Days. - */ - delRange = new Range(DELETE,0,0,0,-1,0,GregorianCalendar.WEEK_OF_MONTH,-2); - lur.add(delRange); - lcred.add(delRange); - lx509.add(delRange); - - lcred.add(new Range(ONE_WEEK ,3,-1,1,0,0,GregorianCalendar.WEEK_OF_MONTH,1)); - lcred.add(new Range(TWO_WEEK ,2,-1,-1,GregorianCalendar.WEEK_OF_MONTH,1,GregorianCalendar.WEEK_OF_MONTH,2)); - lcred.add(new Range(ONE_MONTH,1,7,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); - lcred.add(new Range(TWO_MONTH,1,-1,-1,GregorianCalendar.MONTH,1,GregorianCalendar.MONTH,2)); - - lur.add( new Range(ONE_MONTH,1,-1,-1,0,0,GregorianCalendar.MONTH,1)); - // Comment out until we can get some more clear actions in place for GUI - // lur.add( new Range(ONE_MONTH,1,-1,-1,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); - // lur.add( new Range(ONE_WEEK,2,-1,1,0,0,GregorianCalendar.WEEK_OF_MONTH,1)); - - lx509.add(new Range(ONE_MONTH,1,-1,-1,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); - } - } - - public Range newFutureRange() { - return new Range("Approval",7,7,1,0,0,GregorianCalendar.MONTH,1); - } - - public Set<String> names() { - Set<String> names = new HashSet<>(); + private Range delRange; + + public ExpireRange(final Access access) { + ranges = new HashMap<>(); + intervalDates = new HashMap<>(); + int i=0; + approveDelete = new Range(DELETE,0,0,0,-1,0,GregorianCalendar.DAY_OF_YEAR,-100); + String prop = access.getProperty(AAF_BATCH_RANGE + i,null); + if(prop==null && i==0) { + List<Range> lcred = getRangeList("cred"); + List<Range> lur = getRangeList("ur"); + List<Range> lx509 = getRangeList("x509"); + + + /* + Range(Name, ReportingLevel, PeopleInterval, AppInterval, Start(Type,Qty) End(Type,Qty) ) + Interval of -1 Means "only once" + Interval of 0 means none + Interval > 0 means only X number of Days. + */ + delRange = new Range(DELETE,0,0,0,-1,0,GregorianCalendar.WEEK_OF_MONTH,-2); + lur.add(delRange); + lcred.add(delRange); + lx509.add(delRange); + + lcred.add(new Range(ONE_WEEK ,3,-1,1,0,0,GregorianCalendar.WEEK_OF_MONTH,1)); + lcred.add(new Range(TWO_WEEK ,2,-1,-1,GregorianCalendar.WEEK_OF_MONTH,1,GregorianCalendar.WEEK_OF_MONTH,2)); + lcred.add(new Range(ONE_MONTH,1,7,7,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); + lcred.add(new Range(TWO_MONTH,1,-1,-1,GregorianCalendar.MONTH,1,GregorianCalendar.MONTH,2)); + + lur.add( new Range(ONE_MONTH,1,-1,-1,0,0,GregorianCalendar.MONTH,1)); + // Comment out until we can get some more clear actions in place for GUI + // lur.add( new Range(ONE_MONTH,1,-1,-1,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); + // lur.add( new Range(ONE_WEEK,2,-1,1,0,0,GregorianCalendar.WEEK_OF_MONTH,1)); + + lx509.add(new Range(ONE_MONTH,1,-1,-1,GregorianCalendar.WEEK_OF_MONTH,2,GregorianCalendar.MONTH,1)); + } + } + + public Range newFutureRange() { + return new Range("Approval",7,7,1,0,0,GregorianCalendar.MONTH,1); + } + + public Set<String> names() { + Set<String> names = new HashSet<>(); for(List<Range> lr : ranges.values()) { - for(Range r : lr) { - names.add(r.name); - } + for(Range r : lr) { + names.add(r.name); + } } - return names; - } - - private synchronized List<Range> getRangeList(final String key) { - List<Range> rv = ranges.get(key); - if(rv==null) { - rv = new ArrayList<>(); - ranges.put(key, rv); - } - return rv; - } - - public class Range { - private final String name; - private final int reportingLevel; - private final int peopleInterval; // in Days - private final int appInterval; // in Days - private final Date start; - private final Date end; - private final Date lowerValid; - - public Range( - final String name, final int reportingLevel, - final int peopleInterval, final int appInterval, - final int startGCType, final int startQty, - final int endGCType,final int endQty) { - this.name = name; - this.reportingLevel = reportingLevel; - this.peopleInterval = peopleInterval; - this.appInterval = appInterval; - GregorianCalendar gc = new GregorianCalendar(); - if(startGCType<0) { - gc.set(GregorianCalendar.YEAR, 1); - } else { - gc.setTime(now); - gc.add(startGCType, startQty); - } - start = gc.getTime(); - - if(endGCType<0) { - gc.set(GregorianCalendar.YEAR, 1); - } else { - gc.setTime(now); - gc.add(endGCType, endQty); - } - end = gc.getTime(); - + return names; + } + + private synchronized List<Range> getRangeList(final String key) { + List<Range> rv = ranges.get(key); + if(rv==null) { + rv = new ArrayList<>(); + ranges.put(key, rv); + } + return rv; + } + + public class Range { + private final String name; + private final int reportingLevel; + private final int peopleInterval; // in Days + private final int appInterval; // in Days + private final Date start; + private final Date end; + private final Date lowerValid; + + public Range( + final String name, final int reportingLevel, + final int peopleInterval, final int appInterval, + final int startGCType, final int startQty, + final int endGCType,final int endQty) { + this.name = name; + this.reportingLevel = reportingLevel; + this.peopleInterval = peopleInterval; + this.appInterval = appInterval; + GregorianCalendar gc = new GregorianCalendar(); + if(startGCType<0) { + gc.set(GregorianCalendar.YEAR, 1); + } else { + gc.setTime(now); + gc.add(startGCType, startQty); + } + start = gc.getTime(); + + if(endGCType<0) { + gc.set(GregorianCalendar.YEAR, 1); + } else { + gc.setTime(now); + gc.add(endGCType, endQty); + } + end = gc.getTime(); + - if(endGCType<0) { - gc.set(GregorianCalendar.YEAR, -1); - } else { - gc.setTime(now); - gc.add(endGCType, endQty * -1); - } - lowerValid = gc.getTime(); + if(endGCType<0) { + gc.set(GregorianCalendar.YEAR, -1); + } else { + gc.setTime(now); + gc.add(endGCType, endQty * -1); + } + lowerValid = gc.getTime(); - } - - public String name() { - return name; - } - - public int reportingLevel() { - return reportingLevel; - } + } + + public String name() { + return name; + } + + public int reportingLevel() { + return reportingLevel; + } - public boolean needsContact(Date lnd, Identity identity) { - final int interval; - if(identity==null || identity.isPerson()) { - interval = peopleInterval; - } else { - interval = appInterval; - } - if(interval == 0) { - return false; - } else if(interval < 0) { // "-1 = only once " - return (lnd==null || lnd.before(lowerValid)); - } else { - Date rv = intervalDates.get(interval); - if(rv==null) { - GregorianCalendar gc = new GregorianCalendar(); - gc.setTime(now); - gc.add(GregorianCalendar.DAY_OF_YEAR, -1*interval); - rv = gc.getTime(); - intervalDates.put(interval, rv); - } - return rv.after(lnd); - } - } + public boolean needsContact(Date lnd, Identity identity) { + final int interval; + if(identity==null || identity.isPerson()) { + interval = peopleInterval; + } else { + interval = appInterval; + } + if(interval == 0) { + return false; + } else if(interval < 0) { // "-1 = only once " + return (lnd==null || lnd.before(lowerValid)); + } else { + Date rv = intervalDates.get(interval); + if(rv==null) { + GregorianCalendar gc = new GregorianCalendar(); + gc.setTime(now); + gc.add(GregorianCalendar.DAY_OF_YEAR, -1*interval); + rv = gc.getTime(); + intervalDates.put(interval, rv); + } + return rv.after(lnd); + } + } - public Date getStart() { - return start; - } - - public Date getEnd() { - return end; - } - - public boolean inRange(final Date date) { - if(date==null) { - return false; - } else { - return date.getTime()>=start.getTime() && date.before(end); - } - } + public Date getStart() { + return start; + } + + public Date getEnd() { + return end; + } + + public boolean inRange(final Date date) { + if(date==null) { + return false; + } else { + return date.getTime()>=start.getTime() && date.before(end); + } + } - } + } - public Range getRange(final String key, final Date date) { - Range rv = null; - if(date!=null) { - List<Range> lr = ranges.get(key); - if(lr==null) { - return null; - } else { - for(Range r : lr) { - if(r.inRange(date)) { - rv = r; - break; - } - } - } - } - return rv; - } + public Range getRange(final String key, final Date date) { + Range rv = null; + if(date!=null) { + List<Range> lr = ranges.get(key); + if(lr==null) { + return null; + } else { + for(Range r : lr) { + if(r.inRange(date)) { + rv = r; + break; + } + } + } + } + return rv; + } - public Date now() { - return now; - } - + public Date now() { + return now; + } + } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java index 74c3411f..fd0de1fc 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Future.java @@ -104,7 +104,7 @@ public class Future implements CacheChange.Data, Comparable<Future> { e.printStackTrace(System.err); } } - this.role = role; + this.role = role; } public final UUID id() { @@ -128,7 +128,7 @@ public class Future implements CacheChange.Data, Comparable<Future> { } public static void load(Trans trans, Session session, Creator<Future> creator) { - load(trans,session,creator, f -> { + load(trans,session,creator, f -> { data.put(f.fdd.id,f); if (f.role==null) { return; @@ -154,8 +154,8 @@ public class Future implements CacheChange.Data, Comparable<Future> { tt = trans.start("Process Futures", Env.SUB); try { for (Row row : results.all()) { - ++count; - visitor.visit(creator.create(row)); + ++count; + visitor.visit(creator.create(row)); } } finally { tt.done(); @@ -216,15 +216,15 @@ public class Future implements CacheChange.Data, Comparable<Future> { return cache.contains(f); } - public static void row(CSV.Writer cw, Future f) { - cw.row("future",f.fdd.id,f.fdd.target,f.fdd.expires,f.role,f.fdd.memo); - } + public static void row(CSV.Writer cw, Future f) { + cw.row("future",f.fdd.id,f.fdd.target,f.fdd.expires,f.role,f.fdd.memo); + } - public static void deleteByIDBatch(StringBuilder sb, String id) { - sb.append("DELETE from authz.future where id="); - sb.append(id); - sb.append(";\n"); - } + public static void deleteByIDBatch(StringBuilder sb, String id) { + sb.append("DELETE from authz.future where id="); + sb.append(id); + sb.append(";\n"); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/LastNotified.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/LastNotified.java index e6942f09..258f430e 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/LastNotified.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/LastNotified.java @@ -45,101 +45,101 @@ import com.datastax.driver.core.SimpleStatement; import com.datastax.driver.core.Statement; public class LastNotified { - private Map<String,Date> lastNotified = new TreeMap<>(); - private Session session; - public static final Date NEVER = new Date(0); - private static final String SELECT = "SELECT user,target,key,last FROM authz.notified"; - - public LastNotified(Session session) { - this.session = session; - } - - public void add(Set<String> users) { - StringBuilder query = new StringBuilder(); - startQuery(query); - int cnt = 0; - for(String user : users) { - if(++cnt>1) { - query.append(','); - } - query.append('\''); - query.append(user); - query.append('\''); - if(cnt>=30) { - endQuery(query); - add(session.execute(query.toString()),lastNotified, (x,y) -> false); - query.setLength(0); - startQuery(query); - cnt=0; - } - } - if(cnt>0) { - endQuery(query); - add(session.execute(query.toString()),lastNotified, (x,y) -> false); - } - } + private Map<String,Date> lastNotified = new TreeMap<>(); + private Session session; + public static final Date NEVER = new Date(0); + private static final String SELECT = "SELECT user,target,key,last FROM authz.notified"; + + public LastNotified(Session session) { + this.session = session; + } + + public void add(Set<String> users) { + StringBuilder query = new StringBuilder(); + startQuery(query); + int cnt = 0; + for(String user : users) { + if(++cnt>1) { + query.append(','); + } + query.append('\''); + query.append(user); + query.append('\''); + if(cnt>=30) { + endQuery(query); + add(session.execute(query.toString()),lastNotified, (x,y) -> false); + query.setLength(0); + startQuery(query); + cnt=0; + } + } + if(cnt>0) { + endQuery(query); + add(session.execute(query.toString()),lastNotified, (x,y) -> false); + } + } - /** - * Note: target_key CAN also contain a Pipe. - * - * @param user - * @param target - * @param targetkey - * @return - */ - public Date lastNotified(String user, String target, String targetkey) { - String key = user + '|' + target + '|' + (targetkey==null?"":targetkey); - return lastNotified(key); - } - - public Date lastNotified(String key) { - Date d = lastNotified.get(key); - return d==null?NEVER:d; - } - - private Date add(ResultSet result, Map<String, Date> lastNotified, MarkDelete md) { - Date last = null; - Row r; - for(Iterator<Row> iter = result.iterator(); iter.hasNext();) { - r = iter.next(); - String ttKey = r.getString(1) + '|' + - r.getString(2); + /** + * Note: target_key CAN also contain a Pipe. + * + * @param user + * @param target + * @param targetkey + * @return + */ + public Date lastNotified(String user, String target, String targetkey) { + String key = user + '|' + target + '|' + (targetkey==null?"":targetkey); + return lastNotified(key); + } + + public Date lastNotified(String key) { + Date d = lastNotified.get(key); + return d==null?NEVER:d; + } + + private Date add(ResultSet result, Map<String, Date> lastNotified, MarkDelete md) { + Date last = null; + Row r; + for(Iterator<Row> iter = result.iterator(); iter.hasNext();) { + r = iter.next(); + String ttKey = r.getString(1) + '|' + + r.getString(2); - String fullKey = r.getString(0) + '|' + - ttKey; - last=r.getTimestamp(3); - if(!md.process(fullKey, last)) { - lastNotified.put(fullKey, last); - Date d = lastNotified.get(ttKey); - if(d==null || d.after(last)) { // put most recent, if different - lastNotified.put(ttKey, last); - } - } - } - return last; - } - - private interface MarkDelete { - boolean process(String fullKey, Date last); - } + String fullKey = r.getString(0) + '|' + + ttKey; + last=r.getTimestamp(3); + if(!md.process(fullKey, last)) { + lastNotified.put(fullKey, last); + Date d = lastNotified.get(ttKey); + if(d==null || d.after(last)) { // put most recent, if different + lastNotified.put(ttKey, last); + } + } + } + return last; + } + + private interface MarkDelete { + boolean process(String fullKey, Date last); + } - private void startQuery(StringBuilder query) { - query.append(SELECT + " WHERE user in ("); - } + private void startQuery(StringBuilder query) { + query.append(SELECT + " WHERE user in ("); + } - private void endQuery(StringBuilder query) { - query.append(");"); - } + private void endQuery(StringBuilder query) { + query.append(");"); + } - public void update(StringBuilder query,String user, String target, String key) { - query.append("UPDATE authz.notified SET last=dateof(now()) WHERE user='"); - query.append(user); - query.append("' AND target='"); - query.append(target); - query.append("' AND key='"); - query.append(key); - query.append("';\n"); - } + public void update(StringBuilder query,String user, String target, String key) { + query.append("UPDATE authz.notified SET last=dateof(now()) WHERE user='"); + query.append(user); + query.append("' AND target='"); + query.append(target); + query.append("' AND key='"); + query.append(key); + query.append("';\n"); + } public LastNotified loadAll(Trans trans, final Range delRange, final CSV.Writer cw) { trans.debug().log( "query: ",SELECT ); @@ -150,14 +150,14 @@ public class LastNotified { Statement stmt = new SimpleStatement( SELECT ); results = session.execute(stmt); add(results,lastNotified, (fullKey, last) -> { - if(delRange.inRange(last)) { - String[] params = Split.splitTrim('|', fullKey,3); - if(params.length==3) { - cw.row("notified",params[0],params[1],params[2]); - return true; - } - } - return false; + if(delRange.inRange(last)) { + String[] params = Split.splitTrim('|', fullKey,3); + if(params.length==3) { + cw.row("notified",params[0],params[1],params[2]); + return true; + } + } + return false; }); } finally { tt.done(); @@ -165,26 +165,26 @@ public class LastNotified { return this; } - public static String newKey(UserRole ur) { - return "ur|" + ur.user() + '|'+ur.role(); - } + public static String newKey(UserRole ur) { + return "ur|" + ur.user() + '|'+ur.role(); + } - public static String newKey(Cred cred, Instance inst) { - return "cred|" + cred.id + '|' + inst.type + '|' + inst.tag; - } + public static String newKey(Cred cred, Instance inst) { + return "cred|" + cred.id + '|' + inst.type + '|' + inst.tag; + } - public static String newKey(X509 x509, X509Certificate x509Cert) { - return "x509|" + x509.id + '|' + x509Cert.getSerialNumber().toString(); - } + public static String newKey(X509 x509, X509Certificate x509Cert) { + return "x509|" + x509.id + '|' + x509Cert.getSerialNumber().toString(); + } - public static void delete(StringBuilder query, List<String> row) { - query.append("DELETE FROM authz.notified WHERE user='"); - query.append(row.get(1)); - query.append("' AND target='"); - query.append(row.get(2)); - query.append("' AND key='"); - query.append(row.get(3)); - query.append("';\n"); - } + public static void delete(StringBuilder query, List<String> row) { + query.append("DELETE FROM authz.notified WHERE user='"); + query.append(row.get(1)); + query.append("' AND target='"); + query.append(row.get(2)); + query.append("' AND key='"); + query.append(row.get(3)); + query.append("';\n"); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java index ad1ab373..e76f5235 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/NS.java @@ -57,7 +57,7 @@ public class NS implements Comparable<NS> { }; public NS(String name, String description, String parent, int type, int scope) { - ndd = new NsDAO.Data(); + ndd = new NsDAO.Data(); ndd.name = name; ndd.description = description; ndd.parent = parent; @@ -70,7 +70,7 @@ public class NS implements Comparable<NS> { "select name, description, parent, type, scope from authz.ns;" ,creator , v -> data.put(v.ndd.name,v) - ); + ); } public static void loadOne(Trans trans, Session session, Creator<NS> creator, String ns) { @@ -82,11 +82,11 @@ public class NS implements Comparable<NS> { } public static void load(Trans trans, Session session, Creator<NS> creator, Visitor<NS> visitor) { - load(trans,session,creator.query(null),creator, visitor); + load(trans,session,creator.query(null),creator, visitor); } public void row(final CSV.Writer csvw, String tag) { - csvw.row(tag,ndd.name,ndd.type,ndd.parent); + csvw.row(tag,ndd.name,ndd.type,ndd.parent); } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java index bb5e8c21..e69ef51d 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Role.java @@ -52,7 +52,7 @@ public class Role implements Comparable<Role> { private String encode; public Role(String full) { - rdd = new RoleDAO.Data(); + rdd = new RoleDAO.Data(); rdd.ns = ""; rdd.name = ""; rdd.description = ""; @@ -61,7 +61,7 @@ public class Role implements Comparable<Role> { } public Role(String ns, String name, String description,Set<String> perms) { - rdd = new RoleDAO.Data(); + rdd = new RoleDAO.Data(); rdd.ns = ns; rdd.name = name; rdd.description = description; @@ -179,11 +179,11 @@ public class Role implements Comparable<Role> { deleteRoles.clear(); } - public static void clear() { - data.clear(); - keys.clear(); - byName.clear(); - deleteRoles.clear(); - } + public static void clear() { + data.clear(); + keys.clear(); + byName.clear(); + deleteRoles.clear(); + } }
\ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java index 96169434..d5c0d771 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/UserRole.java @@ -51,7 +51,7 @@ public class UserRole implements Cloneable, CacheChange.Data { public static final String UR = "ur"; public static final String APPROVE_UR = "ur"; - private static final String SEPARATOR = "\",\""; + private static final String SEPARATOR = "\",\""; // CACHE Calling private static final String LOG_FMT = "%s UserRole - %s: %s-%s (%s, %s) expiring %s"; @@ -127,11 +127,11 @@ public class UserRole implements Cloneable, CacheChange.Data { } public static void load(Trans trans, CSV csv, Creator<UserRole> creator, Visitor<UserRole> visitor) throws IOException, CadiException { -// public UserRole(String user, String role, String ns, String rname, Date expires) { - csv.visit( row -> { - visitor.visit(new UserRole(row.get(1),row.get(2),row.get(3),row.get(4), - new Date(Long.parseLong(row.get(6))))); - }); +// public UserRole(String user, String role, String ns, String rname, Date expires) { + csv.visit( row -> { + visitor.visit(new UserRole(row.get(1),row.get(2),row.get(3),row.get(4), + new Date(Long.parseLong(row.get(6))))); + }); } private static void load(Trans trans, Session session, Creator<UserRole> creator, String where, Visitor<UserRole> visitor) { @@ -169,8 +169,8 @@ public class UserRole implements Cloneable, CacheChange.Data { } public static class DataLoadVisitor implements Visitor<UserRole> { - @Override - public void visit(UserRole ur) { + @Override + public void visit(UserRole ur) { data.add(ur); List<UserRole> lur = byUser.get(ur.urdd.user); @@ -186,7 +186,7 @@ public class UserRole implements Cloneable, CacheChange.Data { byRole.put(ur.urdd.role, lur); } lur.add(ur); - } + } } public int totalLoaded() { @@ -305,81 +305,81 @@ public class UserRole implements Cloneable, CacheChange.Data { } public void row(final CSV.Writer csvw, String tag) { - csvw.row(tag,user(),role(),ns(),rname(),Chrono.dateOnlyStamp(expires()),expires().getTime()); + csvw.row(tag,user(),role(),ns(),rname(),Chrono.dateOnlyStamp(expires()),expires().getTime()); } public void row(final CSV.Writer csvw, String tag, String reason) { - csvw.row(tag,user(),role(),ns(),rname(),Chrono.dateOnlyStamp(expires()),expires().getTime(),reason); + csvw.row(tag,user(),role(),ns(),rname(),Chrono.dateOnlyStamp(expires()),expires().getTime(),reason); } public static Data row(List<String> row) { - Data data = new Data(); - data.user = row.get(1); - data.role = row.get(2); - data.ns = row.get(3); - data.rname = row.get(4); - data.expires = new Date(Long.parseLong(row.get(6))); - return data; - } - - public static void batchDelete(StringBuilder sb, List<String> row) { - sb.append("DELETE from authz.user_role WHERE user='"); - sb.append(row.get(1)); - sb.append("' AND role='"); - sb.append(row.get(2)); - sb.append("';\n"); + Data data = new Data(); + data.user = row.get(1); + data.role = row.get(2); + data.ns = row.get(3); + data.rname = row.get(4); + data.expires = new Date(Long.parseLong(row.get(6))); + return data; + } + + public static void batchDelete(StringBuilder sb, List<String> row) { + sb.append("DELETE from authz.user_role WHERE user='"); + sb.append(row.get(1)); + sb.append("' AND role='"); + sb.append(row.get(2)); + sb.append("';\n"); } public static void batchExtend(StringBuilder sb, List<String> row, Date newDate ) { - sb.append("UPDATE authz.user_role SET expires='"); - sb.append(Chrono.dateTime(newDate)); - sb.append("' WHERE user='"); - sb.append(row.get(1)); - sb.append("' AND role='"); - sb.append(row.get(2)); - sb.append("';\n"); + sb.append("UPDATE authz.user_role SET expires='"); + sb.append(Chrono.dateTime(newDate)); + sb.append("' WHERE user='"); + sb.append(row.get(1)); + sb.append("' AND role='"); + sb.append(row.get(2)); + sb.append("';\n"); } public void batchExtend(StringBuilder sb, Date newDate) { - sb.append("UPDATE authz.user_role SET expires='"); - sb.append(Chrono.dateTime(newDate)); - sb.append("' WHERE user='"); - sb.append(user()); - sb.append("' AND role='"); - sb.append(role()); - sb.append("';\n"); + sb.append("UPDATE authz.user_role SET expires='"); + sb.append(Chrono.dateTime(newDate)); + sb.append("' WHERE user='"); + sb.append(user()); + sb.append("' AND role='"); + sb.append(role()); + sb.append("';\n"); } public void batchUpdateExpires(StringBuilder sb) { - sb.append("UPDATE authz.user_role SET expires='"); - sb.append(Chrono.dateTime(expires())); - sb.append("' WHERE user='"); - sb.append(user()); - sb.append("' AND role='"); - sb.append(role()); - sb.append("';\n"); - } - - public static String histMemo(String fmt, List<String> row) { - String reason; - if(row.size()>7) { // Reason included - reason = String.format("%s removed from %s because %s", - row.get(1),row.get(2),row.get(7)); - } else { - reason = String.format(fmt, row.get(1),row.get(2), row.get(5)); - } - return reason; - } - - public static String histSubject(List<String> row) { - return row.get(1) + '|' + row.get(2); - } - - public static void clear() { - data.clear(); - byUser.clear(); - byRole.clear(); - cache.resetLocalData(); - - } + sb.append("UPDATE authz.user_role SET expires='"); + sb.append(Chrono.dateTime(expires())); + sb.append("' WHERE user='"); + sb.append(user()); + sb.append("' AND role='"); + sb.append(role()); + sb.append("';\n"); + } + + public static String histMemo(String fmt, List<String> row) { + String reason; + if(row.size()>7) { // Reason included + reason = String.format("%s removed from %s because %s", + row.get(1),row.get(2),row.get(7)); + } else { + reason = String.format(fmt, row.get(1),row.get(2), row.get(5)); + } + return reason; + } + + public static String histSubject(List<String> row) { + return row.get(1) + '|' + row.get(2); + } + + public static void clear() { + data.clear(); + byUser.clear(); + byRole.clear(); + cache.resetLocalData(); + + } }
\ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java index 17f289a1..38a76477 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/Visitor.java @@ -21,20 +21,20 @@ package org.onap.aaf.auth.batch.helpers; public interface Visitor<T> { - void visit(T t); - - public static class Multi<T> implements Visitor<T> { - private final Visitor<T>[] visitors; - @SafeVarargs - public Multi(Visitor<T> ... vs) { - visitors = vs; - } - - @Override - public void visit(T t) { - for(Visitor<T> v : visitors) { - v.visit(t); - } - } - }; + void visit(T t); + + public static class Multi<T> implements Visitor<T> { + private final Visitor<T>[] visitors; + @SafeVarargs + public Multi(Visitor<T> ... vs) { + visitors = vs; + } + + @Override + public void visit(T t) { + for(Visitor<T> v : visitors) { + v.visit(t); + } + } + }; } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java index 6a7ffc59..c68a9945 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/helpers/X509.java @@ -50,11 +50,11 @@ public class X509 { public ByteBuffer serial; public X509(String ca, String id, String x500, String x509, ByteBuffer serial) { - this.ca = ca; - this.id = id; - this.x500 = x500; - this.x509 = x509; - this.serial = serial; + this.ca = ca; + this.id = id; + this.x500 = x500; + this.x509 = x509; + this.serial = serial; } @@ -81,7 +81,7 @@ public class X509 { tt = trans.start("Load X509s", Env.SUB); try { while (iter.hasNext()) { - ++count; + ++count; row = iter.next(); visitor.visit(new X509(row.getString(0),row.getString(1), row.getString(2),row.getString(3),row.getBytes(4))); } @@ -108,48 +108,48 @@ public class X509 { } - public void row(CSV.Writer cw, X509Certificate x509Cert) { - cw.row("x509",ca,Hash.toHex(serial.array()),Chrono.dateOnlyStamp(x509Cert.getNotAfter()),x500); - } + public void row(CSV.Writer cw, X509Certificate x509Cert) { + cw.row("x509",ca,Hash.toHex(serial.array()),Chrono.dateOnlyStamp(x509Cert.getNotAfter()),x500); + } - public void row(CSV.Writer cw, X509Certificate x509Cert,String reason) { - cw.row("x509",ca,Hash.toHex(serial.array()),Chrono.dateOnlyStamp(x509Cert.getNotAfter()),x500,reason); - } + public void row(CSV.Writer cw, X509Certificate x509Cert,String reason) { + cw.row("x509",ca,Hash.toHex(serial.array()),Chrono.dateOnlyStamp(x509Cert.getNotAfter()),x500,reason); + } - public static void row(StringBuilder sb, List<String> row) { - sb.append("DELETE from authz.x509 WHERE ca='"); - sb.append(row.get(1)); - sb.append("' AND serial="); - sb.append(row.get(2)); - sb.append(";\n"); - } + public static void row(StringBuilder sb, List<String> row) { + sb.append("DELETE from authz.x509 WHERE ca='"); + sb.append(row.get(1)); + sb.append("' AND serial="); + sb.append(row.get(2)); + sb.append(";\n"); + } public static void batchDelete(StringBuilder sb, List<String> row) { - sb.append("DELETE from authz.x509 WHERE ca='"); - sb.append(row.get(1)); - sb.append("' AND serial="); - sb.append(row.get(2)); - sb.append(";\n"); - } - public static String histSubject(List<String> row) { - return row.get(4); - } - - - public static String histMemo(String fmt, List<String> row) { - String id="n/a"; - for(String s : Split.splitTrim(',', row.get(4))) { - if(s.startsWith("OU=") && s.indexOf('@')>=0) { - int colon = s.indexOf(':'); - if(colon<0) { - colon=s.length(); - } - id=s.substring(3,colon); - break; - } - } - return String.format(fmt, "Cert for " + id,"CA " + row.get(1),row.get(3)); - } + sb.append("DELETE from authz.x509 WHERE ca='"); + sb.append(row.get(1)); + sb.append("' AND serial="); + sb.append(row.get(2)); + sb.append(";\n"); + } + public static String histSubject(List<String> row) { + return row.get(4); + } + + + public static String histMemo(String fmt, List<String> row) { + String id="n/a"; + for(String s : Split.splitTrim(',', row.get(4))) { + if(s.startsWith("OU=") && s.indexOf('@')>=0) { + int colon = s.indexOf(':'); + if(colon<0) { + colon=s.length(); + } + id=s.substring(3,colon); + break; + } + } + return String.format(fmt, "Cert for " + id,"CA " + row.get(1),row.get(3)); + } }
\ No newline at end of file diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Analyze.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Analyze.java index eb998b04..5780c603 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Analyze.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Analyze.java @@ -69,7 +69,7 @@ import org.onap.aaf.misc.env.util.Chrono; public class Analyze extends Batch { - private static final int unknown=0; + private static final int unknown=0; private static final int owner=1; private static final int supervisor=2; private static final int total=0; @@ -77,23 +77,23 @@ public class Analyze extends Batch { private static final int approved=2; - public static final String NEED_APPROVALS = "NeedApprovals"; - private static final String EXTEND = "Extend"; - private static final String EXPIRED_OWNERS = "ExpiredOwners"; - private static final String CSV = ".csv"; - private static final String INFO = "info"; - private int minOwners; - private Map<String, CSV.Writer> writerList; - private ExpireRange expireRange; - private Date deleteDate; - private CSV.Writer deleteCW; - private CSV.Writer needApproveCW; - private CSV.Writer extendCW; - private Range futureRange; - private final String sdate; - private LastNotified ln; - - public Analyze(AuthzTrans trans) throws APIException, IOException, OrganizationException { + public static final String NEED_APPROVALS = "NeedApprovals"; + private static final String EXTEND = "Extend"; + private static final String EXPIRED_OWNERS = "ExpiredOwners"; + private static final String CSV = ".csv"; + private static final String INFO = "info"; + private int minOwners; + private Map<String, CSV.Writer> writerList; + private ExpireRange expireRange; + private Date deleteDate; + private CSV.Writer deleteCW; + private CSV.Writer needApproveCW; + private CSV.Writer extendCW; + private Range futureRange; + private final String sdate; + private LastNotified ln; + + public Analyze(AuthzTrans trans) throws APIException, IOException, OrganizationException { super(trans.env()); trans.info().log("Starting Connection Process"); @@ -115,20 +115,20 @@ public class Analyze extends Batch { expireRange = new ExpireRange(trans.env().access()); sdate = Chrono.dateOnlyStamp(now); for( List<Range> lr : expireRange.ranges.values()) { - for(Range r : lr ) { - if(writerList.get(r.name())==null) { - File file = new File(logDir(),r.name() + sdate +CSV); - CSV csv = new CSV(env.access(),file); - CSV.Writer cw = csv.writer(false); - cw.row(INFO,r.name(),sdate,r.reportingLevel()); - writerList.put(r.name(),cw); - if("Delete".equals(r.name())) { - deleteDate = r.getEnd(); - deleteCW = cw; - } - trans.init().log("Creating File:",file.getAbsolutePath()); - } - } + for(Range r : lr ) { + if(writerList.get(r.name())==null) { + File file = new File(logDir(),r.name() + sdate +CSV); + CSV csv = new CSV(env.access(),file); + CSV.Writer cw = csv.writer(false); + cw.row(INFO,r.name(),sdate,r.reportingLevel()); + writerList.put(r.name(),cw); + if("Delete".equals(r.name())) { + deleteDate = r.getEnd(); + deleteCW = cw; + } + trans.init().log("Creating File:",file.getAbsolutePath()); + } + } } // Setup New Approvals file @@ -156,465 +156,465 @@ public class Analyze extends Batch { @Override protected void run(AuthzTrans trans) { - TimeTaken tt; - AuthzTrans noAvg = trans.env().newTransNoAvg(); - - //////////////////// - // Load all Notifieds, and either add to local Data, or mark for Deletion. - ln.loadAll(noAvg,expireRange.approveDelete,deleteCW); - - // Hold Good Tickets to keyed User/Role for UserRole Step - Map<String,Ticket> mur = new TreeMap<>(); + TimeTaken tt; + AuthzTrans noAvg = trans.env().newTransNoAvg(); + + //////////////////// + // Load all Notifieds, and either add to local Data, or mark for Deletion. + ln.loadAll(noAvg,expireRange.approveDelete,deleteCW); + + // Hold Good Tickets to keyed User/Role for UserRole Step + Map<String,Ticket> mur = new TreeMap<>(); - try { - Approval.load(trans, session, Approval.v2_0_17); - - //////////////////// - final Map<UUID,Ticket> goodTickets = new TreeMap<>(); - tt = trans.start("Analyze Expired Futures",Trans.SUB); - try { - Future.load(noAvg, session, Future.withConstruct, fut -> { - List<Approval> appls = Approval.byTicket.get(fut.id()); - if(!futureRange.inRange(fut.expires())) { - deleteCW.comment("Future %s expired", fut.id()); - Future.row(deleteCW,fut); - if(appls!=null) { - for(Approval a : appls) { - Approval.row(deleteCW, a); - } - } - } else if(appls==null) { // Orphaned Future (no Approvals) - deleteCW.comment("Future is Orphaned"); - Future.row(deleteCW,fut); - } else { - goodTickets.put(fut.fdd.id, new Ticket(fut)); - } - }); - } finally { - tt.done(); - } - - Set<String> approvers = new TreeSet<>(); - tt = trans.start("Connect Approvals with Futures",Trans.SUB); - try { - for(Approval appr : Approval.list) { - Ticket ticket=null; - UUID ticketID = appr.getTicket(); - if(ticketID!=null) { - ticket = goodTickets.get(appr.getTicket()); - } - if(ticket == null) { // Orphaned Approvals, no Futures - deleteCW.comment("Approval is Orphaned"); - Approval.row(deleteCW, appr); - } else { - // for users and approvers still valid - String user = appr.getUser(); - - if(org.isRevoked(noAvg, appr.getApprover())) { - deleteCW.comment("Approver ID is revoked"); - Approval.row(deleteCW, appr); - } else if(user!=null && !user.isEmpty() && org.isRevoked(noAvg, user)) { - deleteCW.comment("USER ID is revoked"); - Approval.row(deleteCW, appr); - } else { - ticket.approvals.add(appr); // add to found Ticket - approvers.add(appr.getApprover()); - } - } - } - } finally { - tt.done(); - } - - /* Run through all Futures, and see if - * 1) they have been executed (no longer valid) - * 2) The current Approvals indicate they can proceed - */ - Map<String,Pending> pendingApprs = new HashMap<>(); - Map<String,Pending> pendingTemp = new HashMap<>(); - - String approver; - - tt = trans.start("Analyze Good Tickets",Trans.SUB); - try { - for(Ticket ticket : goodTickets.values()) { - try { - pendingTemp.clear(); - switch(ticket.f.target()) { - case "user_role": - int state[][] = new int[3][3]; - int type; - - for(Approval appr : ticket.approvals) { - switch(appr.getType()) { - case "owner": - type=owner; - break; - case "supervisor": - type=supervisor; - break; - default: - type=0; - } - ++state[type][total]; // count per type - switch(appr.getStatus()) { - case "pending": - ++state[type][pending]; - approver = appr.getApprover(); - Pending n = pendingTemp.get(approver); - if(n==null) { - Date lastNotified = ln.lastNotified(approver,"pending",null); - pendingTemp.put(approver,new Pending(lastNotified)); - } else { - n.inc(); - } - break; - case "approved": - ++state[type][approved]; - break; - default: - ++state[type][unknown]; - } - } - - // To Approve: - // Always must have at least 1 owner - if((state[owner][total]>0 && state[owner][approved]>0) && - // If there are no Supervisors, that's ok - (state[supervisor][total]==0 || - // But if there is a Supervisor, they must have approved - (state[supervisor][approved]>0))) { - UserRoleDAO.Data urdd = new UserRoleDAO.Data(); - try { - urdd.reconstitute(ticket.f.fdd.construct); - if(urdd.expires.before(ticket.f.expires())) { - extendCW.row("extend_ur",urdd.user,urdd.role,ticket.f.expires()); - } - } catch (IOException e) { - trans.error().log("Could not reconstitute UserRole"); - } - } else { // Load all the Pending. - for(Entry<String, Pending> es : pendingTemp.entrySet()) { - Pending p = pendingApprs.get(es.getKey()); - if(p==null) { - pendingApprs.put(es.getKey(), es.getValue()); - } else { - p.inc(es.getValue()); - } - } - } - break; - } - } finally { - if("user_role".equals(ticket.f.fdd.target)) { - String key = ticket.f.fdd.target_key; - if(key!=null) { - mur.put(key, ticket); - } - } - } - } - } finally { - tt.done(); - } - // Good Tickets no longer needed - goodTickets.clear(); - - /** - * Decide to Notify about Approvals, based on activity/last Notified - */ - tt = trans.start("Analyze Approval Reminders", Trans.SUB); - try { - GregorianCalendar gc = new GregorianCalendar(); - gc.add(GregorianCalendar.DAY_OF_WEEK, 5); - Date remind = gc.getTime(); - - for(Entry<String, Pending> es : pendingApprs.entrySet()) { - Pending p = es.getValue(); - if(p.newApprovals() - || p.earliest() == LastNotified.NEVER // yes, equals. - || p.earliest().after(remind)) { - p.row(needApproveCW,es.getKey()); - } - } - } finally { - tt.done(); - } - - // clear out Approval Intermediates - pendingTemp = null; - pendingApprs = null; - } finally { - } - - /** - Run through User Roles. - Owners are treated specially in next section. - Regular roles are checked against Date Ranges. If match Date Range, write out to appropriate file. - */ - - try { - Role.load(trans, session); - - try { - tt = trans.start("Analyze UserRoles, storing Owners",Trans.SUB); - Set<String> specialCommented = new HashSet<>(); - Map<String, Set<UserRole>> owners = new TreeMap<>(); - try { - UserRole.load(noAvg, session, UserRole.v2_0_11, ur -> { - Identity identity; - try { - identity = trans.org().getIdentity(noAvg,ur.user()); - if(identity==null) { - // Candidate for Delete, but not Users if Special - String id = ur.user(); - for(String s : specialDomains) { - if(id.endsWith(s)) { - if(!specialCommented.contains(id)) { - deleteCW.comment("ID %s is part of special Domain %s (UR Org Check)", id,s); - specialCommented.add(id); - } - return; - } - } - if(specialNames.contains(id)) { - if(!specialCommented.contains(id)) { - deleteCW.comment("ID %s is a special ID (UR Org Check)", id); - specialCommented.add(id); - } - return; - } - ur.row(deleteCW, UserRole.UR,"Not in Organization"); - return; - } else if(Role.byName.get(ur.role())==null) { - ur.row(deleteCW, UserRole.UR,String.format("Role %s does not exist", ur.role())); - return; - } - // Just let expired UserRoles sit until deleted - if(futureRange.inRange(ur.expires())) { - if(!mur.containsKey(ur.user() + '|' + ur.role())) { - // Cannot just delete owners, unless there is at least one left. Process later - if ("owner".equals(ur.rname())) { - Set<UserRole> urs = owners.get(ur.role()); - if (urs == null) { - urs = new HashSet<UserRole>(); - owners.put(ur.role(), urs); - } - urs.add(ur); - } else { - Range r = writeAnalysis(noAvg,ur); - if(r!=null) { - Approval existing = findApproval(ur); - if(existing==null) { - ur.row(needApproveCW,UserRole.APPROVE_UR); - } - } - } - } - } - } catch (OrganizationException e) { - noAvg.error().log(e); - } - }); - } finally { - tt.done(); - } - mur.clear(); - - /** - Now Process Owners, one owner Role at a time, ensuring one is left, - preferably a good one. If so, process the others as normal. - - Otherwise, write to ExpiredOwners Report - */ - tt = trans.start("Analyze Owners Separately",Trans.SUB); - try { - if (!owners.values().isEmpty()) { - File file = new File(logDir(), EXPIRED_OWNERS + sdate + CSV); - final CSV ownerCSV = new CSV(env.access(),file); - CSV.Writer expOwner = ownerCSV.writer(); - expOwner.row(INFO,EXPIRED_OWNERS,sdate,2); - - try { - for (Set<UserRole> sur : owners.values()) { - int goodOwners = 0; - for (UserRole ur : sur) { - if (ur.expires().after(now)) { - ++goodOwners; - } - } - - for (UserRole ur : sur) { - if (goodOwners >= minOwners) { - Range r = writeAnalysis(noAvg, ur); - if(r!=null) { - Approval existing = findApproval(ur); - if(existing==null) { - ur.row(needApproveCW,UserRole.APPROVE_UR); - } - } - } else { - expOwner.row("owner",ur.role(), ur.user(), Chrono.dateOnlyStamp(ur.expires())); - Approval existing = findApproval(ur); - if(existing==null) { - ur.row(needApproveCW,UserRole.APPROVE_UR); - } - } - } - } - } finally { - if(expOwner!=null) { - expOwner.close(); - } - } - } - } finally { - tt.done(); - } - } finally { - Role.clear(); - UserRole.clear(); - } - - /** - * Check for Expired Credentials - */ - try { - // Load Cred. We don't follow Visitor, because we have to gather up everything into Identity Anyway - Cred.load(trans, session); - - tt = trans.start("Analyze Expired Credentials",Trans.SUB); - try { - for (Cred cred : Cred.data.values()) { - List<Instance> linst = cred.instances; - if(linst!=null) { - Instance lastBath = null; - for(Instance inst : linst) { - // All Creds go through Life Cycle - if(deleteDate!=null && inst.expires.before(deleteDate)) { - writeAnalysis(noAvg, cred, inst); // will go to Delete - // Basic Auth has Pre-EOL notifications IF there is no Newer Credential - } else if (inst.type == CredDAO.BASIC_AUTH || inst.type == CredDAO.BASIC_AUTH_SHA256) { - if(lastBath==null || lastBath.expires.before(inst.expires)) { - lastBath = inst; - } - } - } - if(lastBath!=null) { - writeAnalysis(noAvg, cred, lastBath); - } - } - } - } finally { - tt.done(); - } - } finally { - Cred.clear(); - } - - //////////////////// - tt = trans.start("Analyze Expired X509s",Trans.SUB); - try { - X509.load(noAvg, session, x509 -> { - try { - for(Certificate cert : Factory.toX509Certificate(x509.x509)) { - writeAnalysis(noAvg, x509, (X509Certificate)cert); - } - } catch (CertificateException | IOException e) { - noAvg.error().log(e, "Error Decrypting X509"); - } - }); - } finally { - tt.done(); - } - } catch (FileNotFoundException e) { - noAvg.info().log(e); - } - } + try { + Approval.load(trans, session, Approval.v2_0_17); + + //////////////////// + final Map<UUID,Ticket> goodTickets = new TreeMap<>(); + tt = trans.start("Analyze Expired Futures",Trans.SUB); + try { + Future.load(noAvg, session, Future.withConstruct, fut -> { + List<Approval> appls = Approval.byTicket.get(fut.id()); + if(!futureRange.inRange(fut.expires())) { + deleteCW.comment("Future %s expired", fut.id()); + Future.row(deleteCW,fut); + if(appls!=null) { + for(Approval a : appls) { + Approval.row(deleteCW, a); + } + } + } else if(appls==null) { // Orphaned Future (no Approvals) + deleteCW.comment("Future is Orphaned"); + Future.row(deleteCW,fut); + } else { + goodTickets.put(fut.fdd.id, new Ticket(fut)); + } + }); + } finally { + tt.done(); + } + + Set<String> approvers = new TreeSet<>(); + tt = trans.start("Connect Approvals with Futures",Trans.SUB); + try { + for(Approval appr : Approval.list) { + Ticket ticket=null; + UUID ticketID = appr.getTicket(); + if(ticketID!=null) { + ticket = goodTickets.get(appr.getTicket()); + } + if(ticket == null) { // Orphaned Approvals, no Futures + deleteCW.comment("Approval is Orphaned"); + Approval.row(deleteCW, appr); + } else { + // for users and approvers still valid + String user = appr.getUser(); + + if(org.isRevoked(noAvg, appr.getApprover())) { + deleteCW.comment("Approver ID is revoked"); + Approval.row(deleteCW, appr); + } else if(user!=null && !user.isEmpty() && org.isRevoked(noAvg, user)) { + deleteCW.comment("USER ID is revoked"); + Approval.row(deleteCW, appr); + } else { + ticket.approvals.add(appr); // add to found Ticket + approvers.add(appr.getApprover()); + } + } + } + } finally { + tt.done(); + } + + /* Run through all Futures, and see if + * 1) they have been executed (no longer valid) + * 2) The current Approvals indicate they can proceed + */ + Map<String,Pending> pendingApprs = new HashMap<>(); + Map<String,Pending> pendingTemp = new HashMap<>(); + + String approver; + + tt = trans.start("Analyze Good Tickets",Trans.SUB); + try { + for(Ticket ticket : goodTickets.values()) { + try { + pendingTemp.clear(); + switch(ticket.f.target()) { + case "user_role": + int state[][] = new int[3][3]; + int type; + + for(Approval appr : ticket.approvals) { + switch(appr.getType()) { + case "owner": + type=owner; + break; + case "supervisor": + type=supervisor; + break; + default: + type=0; + } + ++state[type][total]; // count per type + switch(appr.getStatus()) { + case "pending": + ++state[type][pending]; + approver = appr.getApprover(); + Pending n = pendingTemp.get(approver); + if(n==null) { + Date lastNotified = ln.lastNotified(approver,"pending",null); + pendingTemp.put(approver,new Pending(lastNotified)); + } else { + n.inc(); + } + break; + case "approved": + ++state[type][approved]; + break; + default: + ++state[type][unknown]; + } + } + + // To Approve: + // Always must have at least 1 owner + if((state[owner][total]>0 && state[owner][approved]>0) && + // If there are no Supervisors, that's ok + (state[supervisor][total]==0 || + // But if there is a Supervisor, they must have approved + (state[supervisor][approved]>0))) { + UserRoleDAO.Data urdd = new UserRoleDAO.Data(); + try { + urdd.reconstitute(ticket.f.fdd.construct); + if(urdd.expires.before(ticket.f.expires())) { + extendCW.row("extend_ur",urdd.user,urdd.role,ticket.f.expires()); + } + } catch (IOException e) { + trans.error().log("Could not reconstitute UserRole"); + } + } else { // Load all the Pending. + for(Entry<String, Pending> es : pendingTemp.entrySet()) { + Pending p = pendingApprs.get(es.getKey()); + if(p==null) { + pendingApprs.put(es.getKey(), es.getValue()); + } else { + p.inc(es.getValue()); + } + } + } + break; + } + } finally { + if("user_role".equals(ticket.f.fdd.target)) { + String key = ticket.f.fdd.target_key; + if(key!=null) { + mur.put(key, ticket); + } + } + } + } + } finally { + tt.done(); + } + // Good Tickets no longer needed + goodTickets.clear(); + + /** + * Decide to Notify about Approvals, based on activity/last Notified + */ + tt = trans.start("Analyze Approval Reminders", Trans.SUB); + try { + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.DAY_OF_WEEK, 5); + Date remind = gc.getTime(); + + for(Entry<String, Pending> es : pendingApprs.entrySet()) { + Pending p = es.getValue(); + if(p.newApprovals() + || p.earliest() == LastNotified.NEVER // yes, equals. + || p.earliest().after(remind)) { + p.row(needApproveCW,es.getKey()); + } + } + } finally { + tt.done(); + } + + // clear out Approval Intermediates + pendingTemp = null; + pendingApprs = null; + } finally { + } + + /** + Run through User Roles. + Owners are treated specially in next section. + Regular roles are checked against Date Ranges. If match Date Range, write out to appropriate file. + */ + + try { + Role.load(trans, session); + + try { + tt = trans.start("Analyze UserRoles, storing Owners",Trans.SUB); + Set<String> specialCommented = new HashSet<>(); + Map<String, Set<UserRole>> owners = new TreeMap<>(); + try { + UserRole.load(noAvg, session, UserRole.v2_0_11, ur -> { + Identity identity; + try { + identity = trans.org().getIdentity(noAvg,ur.user()); + if(identity==null) { + // Candidate for Delete, but not Users if Special + String id = ur.user(); + for(String s : specialDomains) { + if(id.endsWith(s)) { + if(!specialCommented.contains(id)) { + deleteCW.comment("ID %s is part of special Domain %s (UR Org Check)", id,s); + specialCommented.add(id); + } + return; + } + } + if(specialNames.contains(id)) { + if(!specialCommented.contains(id)) { + deleteCW.comment("ID %s is a special ID (UR Org Check)", id); + specialCommented.add(id); + } + return; + } + ur.row(deleteCW, UserRole.UR,"Not in Organization"); + return; + } else if(Role.byName.get(ur.role())==null) { + ur.row(deleteCW, UserRole.UR,String.format("Role %s does not exist", ur.role())); + return; + } + // Just let expired UserRoles sit until deleted + if(futureRange.inRange(ur.expires())) { + if(!mur.containsKey(ur.user() + '|' + ur.role())) { + // Cannot just delete owners, unless there is at least one left. Process later + if ("owner".equals(ur.rname())) { + Set<UserRole> urs = owners.get(ur.role()); + if (urs == null) { + urs = new HashSet<UserRole>(); + owners.put(ur.role(), urs); + } + urs.add(ur); + } else { + Range r = writeAnalysis(noAvg,ur); + if(r!=null) { + Approval existing = findApproval(ur); + if(existing==null) { + ur.row(needApproveCW,UserRole.APPROVE_UR); + } + } + } + } + } + } catch (OrganizationException e) { + noAvg.error().log(e); + } + }); + } finally { + tt.done(); + } + mur.clear(); + + /** + Now Process Owners, one owner Role at a time, ensuring one is left, + preferably a good one. If so, process the others as normal. + + Otherwise, write to ExpiredOwners Report + */ + tt = trans.start("Analyze Owners Separately",Trans.SUB); + try { + if (!owners.values().isEmpty()) { + File file = new File(logDir(), EXPIRED_OWNERS + sdate + CSV); + final CSV ownerCSV = new CSV(env.access(),file); + CSV.Writer expOwner = ownerCSV.writer(); + expOwner.row(INFO,EXPIRED_OWNERS,sdate,2); + + try { + for (Set<UserRole> sur : owners.values()) { + int goodOwners = 0; + for (UserRole ur : sur) { + if (ur.expires().after(now)) { + ++goodOwners; + } + } + + for (UserRole ur : sur) { + if (goodOwners >= minOwners) { + Range r = writeAnalysis(noAvg, ur); + if(r!=null) { + Approval existing = findApproval(ur); + if(existing==null) { + ur.row(needApproveCW,UserRole.APPROVE_UR); + } + } + } else { + expOwner.row("owner",ur.role(), ur.user(), Chrono.dateOnlyStamp(ur.expires())); + Approval existing = findApproval(ur); + if(existing==null) { + ur.row(needApproveCW,UserRole.APPROVE_UR); + } + } + } + } + } finally { + if(expOwner!=null) { + expOwner.close(); + } + } + } + } finally { + tt.done(); + } + } finally { + Role.clear(); + UserRole.clear(); + } + + /** + * Check for Expired Credentials + */ + try { + // Load Cred. We don't follow Visitor, because we have to gather up everything into Identity Anyway + Cred.load(trans, session); + + tt = trans.start("Analyze Expired Credentials",Trans.SUB); + try { + for (Cred cred : Cred.data.values()) { + List<Instance> linst = cred.instances; + if(linst!=null) { + Instance lastBath = null; + for(Instance inst : linst) { + // All Creds go through Life Cycle + if(deleteDate!=null && inst.expires.before(deleteDate)) { + writeAnalysis(noAvg, cred, inst); // will go to Delete + // Basic Auth has Pre-EOL notifications IF there is no Newer Credential + } else if (inst.type == CredDAO.BASIC_AUTH || inst.type == CredDAO.BASIC_AUTH_SHA256) { + if(lastBath==null || lastBath.expires.before(inst.expires)) { + lastBath = inst; + } + } + } + if(lastBath!=null) { + writeAnalysis(noAvg, cred, lastBath); + } + } + } + } finally { + tt.done(); + } + } finally { + Cred.clear(); + } + + //////////////////// + tt = trans.start("Analyze Expired X509s",Trans.SUB); + try { + X509.load(noAvg, session, x509 -> { + try { + for(Certificate cert : Factory.toX509Certificate(x509.x509)) { + writeAnalysis(noAvg, x509, (X509Certificate)cert); + } + } catch (CertificateException | IOException e) { + noAvg.error().log(e, "Error Decrypting X509"); + } + }); + } finally { + tt.done(); + } + } catch (FileNotFoundException e) { + noAvg.info().log(e); + } + } - private Approval findApproval(UserRole ur) { - Approval existing = null; - List<Approval> apprs = Approval.byUser.get(ur.user()); - if(apprs!=null) { - for(Approval appr : apprs) { - if(ur.role().equals(appr.getRole()) && - appr.getMemo().contains(Chrono.dateOnlyStamp(ur.expires()))) { - existing = appr; - } - } - } - return existing; - } + private Approval findApproval(UserRole ur) { + Approval existing = null; + List<Approval> apprs = Approval.byUser.get(ur.user()); + if(apprs!=null) { + for(Approval appr : apprs) { + if(ur.role().equals(appr.getRole()) && + appr.getMemo().contains(Chrono.dateOnlyStamp(ur.expires()))) { + existing = appr; + } + } + } + return existing; + } - private Range writeAnalysis(AuthzTrans noAvg, UserRole ur) { - Range r = expireRange.getRange("ur", ur.expires()); - if(r!=null) { - Date lnd = ln.lastNotified(LastNotified.newKey(ur)); - // Note: lnd is NEVER null - Identity i; - try { - i = org.getIdentity(noAvg, ur.user()); - } catch (OrganizationException e) { - i=null; - } - if(r.needsContact(lnd,i)) { - CSV.Writer cw = writerList.get(r.name()); - if(cw!=null) { - ur.row(cw,UserRole.UR); - } - } - } - return r; - } + private Range writeAnalysis(AuthzTrans noAvg, UserRole ur) { + Range r = expireRange.getRange("ur", ur.expires()); + if(r!=null) { + Date lnd = ln.lastNotified(LastNotified.newKey(ur)); + // Note: lnd is NEVER null + Identity i; + try { + i = org.getIdentity(noAvg, ur.user()); + } catch (OrganizationException e) { + i=null; + } + if(r.needsContact(lnd,i)) { + CSV.Writer cw = writerList.get(r.name()); + if(cw!=null) { + ur.row(cw,UserRole.UR); + } + } + } + return r; + } private void writeAnalysis(AuthzTrans noAvg, Cred cred, Instance inst) { - if(cred!=null && inst!=null) { - Range r = expireRange.getRange("cred", inst.expires); - if(r!=null) { - Date lnd = ln.lastNotified(LastNotified.newKey(cred,inst)); - // Note: lnd is NEVER null - Identity i; - try { - i = org.getIdentity(noAvg, cred.id); - } catch (OrganizationException e) { - i=null; - } - if(r.needsContact(lnd,i)) { - CSV.Writer cw = writerList.get(r.name()); - if(cw!=null) { - cred.row(cw,inst); - } - } - } - } - } + if(cred!=null && inst!=null) { + Range r = expireRange.getRange("cred", inst.expires); + if(r!=null) { + Date lnd = ln.lastNotified(LastNotified.newKey(cred,inst)); + // Note: lnd is NEVER null + Identity i; + try { + i = org.getIdentity(noAvg, cred.id); + } catch (OrganizationException e) { + i=null; + } + if(r.needsContact(lnd,i)) { + CSV.Writer cw = writerList.get(r.name()); + if(cw!=null) { + cred.row(cw,inst); + } + } + } + } + } private void writeAnalysis(AuthzTrans noAvg, X509 x509, X509Certificate x509Cert) throws IOException { - Range r = expireRange.getRange("x509", x509Cert.getNotAfter()); - if(r!=null) { - Date lnd = ln.lastNotified(LastNotified.newKey(x509,x509Cert)); - // Note: lnd is NEVER null - Identity i; - try { - i = org.getIdentity(noAvg, x509.id); - } catch (OrganizationException e) { - i=null; - } - if(r.needsContact(lnd,i)) { - CSV.Writer cw = writerList.get(r.name()); - if(cw!=null) { - x509.row(cw,x509Cert); - } - } - } - } + Range r = expireRange.getRange("x509", x509Cert.getNotAfter()); + if(r!=null) { + Date lnd = ln.lastNotified(LastNotified.newKey(x509,x509Cert)); + // Note: lnd is NEVER null + Identity i; + try { + i = org.getIdentity(noAvg, x509.id); + } catch (OrganizationException e) { + i=null; + } + if(r.needsContact(lnd,i)) { + CSV.Writer cw = writerList.get(r.name()); + if(cw!=null) { + x509.row(cw,x509Cert); + } + } + } + } @Override protected void _close(AuthzTrans trans) { session.close(); - for(CSV.Writer cw : writerList.values()) { - cw.close(); - } + for(CSV.Writer cw : writerList.values()) { + cw.close(); + } } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/ApprovedRpt.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/ApprovedRpt.java index a943cbc2..c7f0c5a2 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/ApprovedRpt.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/ApprovedRpt.java @@ -49,15 +49,15 @@ import com.datastax.driver.core.Statement; public class ApprovedRpt extends Batch { - private static final String APPR_RPT = "ApprovedRpt"; - private static final String CSV = ".csv"; - private static final String INFO = "info"; - private Date now; - private Writer approvedW; - private CSV historyR; - private static String yr_mon; - - public ApprovedRpt(AuthzTrans trans) throws APIException, IOException, OrganizationException { + private static final String APPR_RPT = "ApprovedRpt"; + private static final String CSV = ".csv"; + private static final String INFO = "info"; + private Date now; + private Writer approvedW; + private CSV historyR; + private static String yr_mon; + + public ApprovedRpt(AuthzTrans trans) throws APIException, IOException, OrganizationException { super(trans.env()); trans.info().log("Starting Connection Process"); @@ -72,7 +72,7 @@ public class ApprovedRpt extends Batch { now = new Date(); String sdate = Chrono.dateOnlyStamp(now); - File file = new File(logDir(),APPR_RPT + sdate +CSV); + File file = new File(logDir(),APPR_RPT + sdate +CSV); CSV csv = new CSV(env.access(),file); approvedW = csv.writer(false); @@ -86,33 +86,33 @@ public class ApprovedRpt extends Batch { @Override protected void run(AuthzTrans trans) { - try { - Map<String,Boolean> checked = new TreeMap<String, Boolean>(); - - final AuthzTrans transNoAvg = trans.env().newTransNoAvg(); -// ResultSet results; + try { + Map<String,Boolean> checked = new TreeMap<String, Boolean>(); + + final AuthzTrans transNoAvg = trans.env().newTransNoAvg(); +// ResultSet results; // Statement stmt = new SimpleStatement( "select dateof(id), approver, status, user, type, memo from authz.approved;" ); // results = session.execute(stmt); // Iterator<Row> iter = results.iterator(); // Row row; - /* - * while (iter.hasNext()) { + /* + * while (iter.hasNext()) { ++totalLoaded; row = iter.next(); d = row.getTimestamp(0); if(d.after(begin)) { - approvedW.row("aprvd", - Chrono.dateOnlyStamp(d), - row.getString(1), - row.getString(2), - row.getString(3), - row.getString(4), - row.getString(5) - ); + approvedW.row("aprvd", + Chrono.dateOnlyStamp(d), + row.getString(1), + row.getString(2), + row.getString(3), + row.getString(4), + row.getString(5) + ); } } - */ + */ int totalLoaded = 0; Date d; GregorianCalendar gc = new GregorianCalendar(); @@ -123,58 +123,58 @@ public class ApprovedRpt extends Batch { historyR.visit(row -> { String s = row.get(7); if(s.equals(yr_mon)) { - String target = row.get(5); - if("user_role".equals(target)) { - String action = row.get(1); - switch(action) { - case "create": - write("created",row); - break; - case "update": - write("approved",row); - break; - case "delete": - write("denied",row); - break; - } - } + String target = row.get(5); + if("user_role".equals(target)) { + String action = row.get(1); + switch(action) { + case "create": + write("created",row); + break; + case "update": + write("approved",row); + break; + case "delete": + write("denied",row); + break; + } + } } }); - } catch (Exception e) { - trans.info().log(e); - } - } + } catch (Exception e) { + trans.info().log(e); + } + } - private void write(String a_or_d, List<String> row) { - String[] target = Split.splitTrim('|', row.get(4)); - - if(target.length>1) { - UUID id = UUID.fromString(row.get(0)); - Date date = Chrono.uuidToDate(id); - String status; - String memo; - String approver = row.get(6); - if("batch:JobChange".equals(approver)) { - status = "reduced"; - memo = "existing role membership reduced to invoke reapproval"; - } else { - status = a_or_d; - memo = row.get(2); - } - if(!approver.equals(target[0])) { - approvedW.row( - Chrono.niceDateStamp(date), - approver, - status, - target[0], - target[1], - memo - ); - } - } + private void write(String a_or_d, List<String> row) { + String[] target = Split.splitTrim('|', row.get(4)); + + if(target.length>1) { + UUID id = UUID.fromString(row.get(0)); + Date date = Chrono.uuidToDate(id); + String status; + String memo; + String approver = row.get(6); + if("batch:JobChange".equals(approver)) { + status = "reduced"; + memo = "existing role membership reduced to invoke reapproval"; + } else { + status = a_or_d; + memo = row.get(2); + } + if(!approver.equals(target[0])) { + approvedW.row( + Chrono.niceDateStamp(date), + approver, + status, + target[0], + target[1], + memo + ); + } + } - - } + + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/NotInOrg.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/NotInOrg.java index fb562b24..bd56fc2e 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/NotInOrg.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/NotInOrg.java @@ -46,16 +46,16 @@ import org.onap.aaf.misc.env.util.Chrono; public class NotInOrg extends Batch { - private static final String NOT_IN_ORG = "NotInOrg"; - private static final String CSV = ".csv"; - private static final String INFO = "info"; - private Map<String, CSV.Writer> writerList; - private Map<String, CSV.Writer> whichWriter; - private Date now; - private Writer notInOrgW; - private Writer notInOrgDeleteW; - - public NotInOrg(AuthzTrans trans) throws APIException, IOException, OrganizationException { + private static final String NOT_IN_ORG = "NotInOrg"; + private static final String CSV = ".csv"; + private static final String INFO = "info"; + private Map<String, CSV.Writer> writerList; + private Map<String, CSV.Writer> whichWriter; + private Date now; + private Writer notInOrgW; + private Writer notInOrgDeleteW; + + public NotInOrg(AuthzTrans trans) throws APIException, IOException, OrganizationException { super(trans.env()); trans.info().log("Starting Connection Process"); @@ -77,7 +77,7 @@ public class NotInOrg extends Batch { now = new Date(); String sdate = Chrono.dateOnlyStamp(now); - File file = new File(logDir(),NOT_IN_ORG + sdate +CSV); + File file = new File(logDir(),NOT_IN_ORG + sdate +CSV); CSV csv = new CSV(env.access(),file); notInOrgW = csv.writer(false); notInOrgW.row(INFO,NOT_IN_ORG,Chrono.dateOnlyStamp(now),0); @@ -98,75 +98,75 @@ public class NotInOrg extends Batch { @Override protected void run(AuthzTrans trans) { - try { - Map<String,Boolean> checked = new TreeMap<String, Boolean>(); - trans.info().log("Process Organization Identities"); - trans.info().log("User Roles"); - - final AuthzTrans transNoAvg = trans.env().newTransNoAvg(); - UserRole.load(trans, session, UserRole.v2_0_11, ur -> { - try { - if(!check(transNoAvg, checked, ur.user())) { - ur.row(whichWriter(transNoAvg,ur.user()),UserRole.UR); - } - } catch (OrganizationException e) { - trans.error().log(e, "Error Decrypting X509"); - } - }); - - trans.info().log("Checking for Creds without IDs"); - - for (Cred cred : Cred.data.values()) { - if(!check(transNoAvg,checked, cred.id)) { - CSV.Writer cw = whichWriter(transNoAvg, cred.id); - for(Instance inst : cred.instances) { - cred.row(cw, inst); - } - } - } - - } catch (OrganizationException e) { - trans.info().log(e); - } - } + try { + Map<String,Boolean> checked = new TreeMap<String, Boolean>(); + trans.info().log("Process Organization Identities"); + trans.info().log("User Roles"); + + final AuthzTrans transNoAvg = trans.env().newTransNoAvg(); + UserRole.load(trans, session, UserRole.v2_0_11, ur -> { + try { + if(!check(transNoAvg, checked, ur.user())) { + ur.row(whichWriter(transNoAvg,ur.user()),UserRole.UR); + } + } catch (OrganizationException e) { + trans.error().log(e, "Error Decrypting X509"); + } + }); + + trans.info().log("Checking for Creds without IDs"); + + for (Cred cred : Cred.data.values()) { + if(!check(transNoAvg,checked, cred.id)) { + CSV.Writer cw = whichWriter(transNoAvg, cred.id); + for(Instance inst : cred.instances) { + cred.row(cw, inst); + } + } + } + + } catch (OrganizationException e) { + trans.info().log(e); + } + } - private Writer whichWriter(AuthzTrans transNoAvg, String id) { - Writer w = whichWriter.get(id); - if(w==null) { - w = org.isRevoked(transNoAvg, id)? - notInOrgDeleteW: - notInOrgW; - whichWriter.put(id,w); - } - return w; - } + private Writer whichWriter(AuthzTrans transNoAvg, String id) { + Writer w = whichWriter.get(id); + if(w==null) { + w = org.isRevoked(transNoAvg, id)? + notInOrgDeleteW: + notInOrgW; + whichWriter.put(id,w); + } + return w; + } - private boolean check(AuthzTrans trans, Map<String, Boolean> checked, String id) throws OrganizationException { - Boolean rv = checked.get(id); - if(rv==null) { - if(isSpecial(id)) { // do not check against org... too important to delete. - return true; - } - Organization org = trans.org(); - if(org != null) { - Identity identity = org.getIdentity(trans, id); - rv = identity!=null; - checked.put(id, rv); - } else { - throw new OrganizationException("No Organization Found for " + id + ": required for processing"); - } - } - return rv; - } + private boolean check(AuthzTrans trans, Map<String, Boolean> checked, String id) throws OrganizationException { + Boolean rv = checked.get(id); + if(rv==null) { + if(isSpecial(id)) { // do not check against org... too important to delete. + return true; + } + Organization org = trans.org(); + if(org != null) { + Identity identity = org.getIdentity(trans, id); + rv = identity!=null; + checked.put(id, rv); + } else { + throw new OrganizationException("No Organization Found for " + id + ": required for processing"); + } + } + return rv; + } - @Override + @Override protected void _close(AuthzTrans trans) { session.close(); - for(CSV.Writer cw : writerList.values()) { - cw.close(); - } + for(CSV.Writer cw : writerList.values()) { + cw.close(); + } } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Notify.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Notify.java index 7cb8c1bd..a040804d 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Notify.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/Notify.java @@ -58,340 +58,340 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.env.util.Chrono; public class Notify extends Batch { - private static final String HTML_CSS = "HTML_CSS"; - private final Mailer mailer; - private final String header; - private final String footer; - private final int maxEmails; - private final int indent; - private final boolean urgent; - public final String guiURL; - private PropAccess access; - private AuthzTrans noAvg; - private CQLBatch cqlBatch; - private LastNotified lastN; - private CQLBatchLoop cbl; + private static final String HTML_CSS = "HTML_CSS"; + private final Mailer mailer; + private final String header; + private final String footer; + private final int maxEmails; + private final int indent; + private final boolean urgent; + public final String guiURL; + private PropAccess access; + private AuthzTrans noAvg; + private CQLBatch cqlBatch; + private LastNotified lastN; + private CQLBatchLoop cbl; - public Notify(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - access = env.access(); - session = cluster.connect(); + public Notify(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + access = env.access(); + session = cluster.connect(); - String mailerCls = env.getProperty("MAILER"); - String mailFrom = env.getProperty("MAIL_FROM"); - String header_html = env.getProperty("HEADER_HTML"); - String footer_html = env.getProperty("FOOTER_HTML"); - String str = env.getProperty("MAX_EMAIL"); - guiURL = env.getProperty("GUI_URL"); - maxEmails = str==null||str.isEmpty()?Integer.MAX_VALUE:Integer.parseInt(str); - if(mailerCls==null || mailFrom==null || guiURL==null || header_html==null || footer_html==null) { - throw new APIException("Notify requires MAILER, MAILER_FROM, GUI_URL, HEADER_HTML and FOOTER_HTML properties"); - } - try { - Class<?> mailc = Class.forName(mailerCls); - Constructor<?> mailcst = mailc.getConstructor(Access.class); - mailer = (Mailer)mailcst.newInstance(env.access()); - } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new APIException("Unable to construct " + mailerCls,e); - } + String mailerCls = env.getProperty("MAILER"); + String mailFrom = env.getProperty("MAIL_FROM"); + String header_html = env.getProperty("HEADER_HTML"); + String footer_html = env.getProperty("FOOTER_HTML"); + String str = env.getProperty("MAX_EMAIL"); + guiURL = env.getProperty("GUI_URL"); + maxEmails = str==null||str.isEmpty()?Integer.MAX_VALUE:Integer.parseInt(str); + if(mailerCls==null || mailFrom==null || guiURL==null || header_html==null || footer_html==null) { + throw new APIException("Notify requires MAILER, MAILER_FROM, GUI_URL, HEADER_HTML and FOOTER_HTML properties"); + } + try { + Class<?> mailc = Class.forName(mailerCls); + Constructor<?> mailcst = mailc.getConstructor(Access.class); + mailer = (Mailer)mailcst.newInstance(env.access()); + } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new APIException("Unable to construct " + mailerCls,e); + } - String line; - StringBuilder sb = new StringBuilder(); - File fhh = new File(header_html); - if(!fhh.exists()) { - throw new APIException(header_html + " does not exist"); - } - BufferedReader br = new BufferedReader(new FileReader(fhh)); - try { - while((line=br.readLine())!=null) { - sb.append(line); - sb.append('\n'); - } - String html_css = env.getProperty(HTML_CSS); - String temp; - int hc = sb.indexOf(HTML_CSS); - if(hc!=0 && html_css!=null) { - temp = sb.replace(hc,hc+HTML_CSS.length(), html_css).toString(); - } else { - temp = sb.toString(); - } - header = temp.replace("AAF:ENV", batchEnv); - } finally { - br.close(); - } + String line; + StringBuilder sb = new StringBuilder(); + File fhh = new File(header_html); + if(!fhh.exists()) { + throw new APIException(header_html + " does not exist"); + } + BufferedReader br = new BufferedReader(new FileReader(fhh)); + try { + while((line=br.readLine())!=null) { + sb.append(line); + sb.append('\n'); + } + String html_css = env.getProperty(HTML_CSS); + String temp; + int hc = sb.indexOf(HTML_CSS); + if(hc!=0 && html_css!=null) { + temp = sb.replace(hc,hc+HTML_CSS.length(), html_css).toString(); + } else { + temp = sb.toString(); + } + header = temp.replace("AAF:ENV", batchEnv); + } finally { + br.close(); + } - // Establish index from header - int lastTag = header.lastIndexOf('<'); - if(lastTag>0) { - int prevCR = header.lastIndexOf('\n',lastTag); - if(prevCR>0) { - indent = lastTag-prevCR; - } else { - indent = 6; //arbitrary - } - } else { - indent = 6; - } + // Establish index from header + int lastTag = header.lastIndexOf('<'); + if(lastTag>0) { + int prevCR = header.lastIndexOf('\n',lastTag); + if(prevCR>0) { + indent = lastTag-prevCR; + } else { + indent = 6; //arbitrary + } + } else { + indent = 6; + } - urgent = false; - - sb.setLength(0); - fhh = new File(footer_html); - if(!fhh.exists()) { - throw new APIException(footer_html + " does not exist"); - } + urgent = false; + + sb.setLength(0); + fhh = new File(footer_html); + if(!fhh.exists()) { + throw new APIException(footer_html + " does not exist"); + } - br = new BufferedReader(new FileReader(fhh)); - try { - while((line=br.readLine())!=null) { - sb.append(line); - sb.append('\n'); - } - footer = sb.toString(); - } finally { - br.close(); - } + br = new BufferedReader(new FileReader(fhh)); + try { + while((line=br.readLine())!=null) { + sb.append(line); + sb.append('\n'); + } + footer = sb.toString(); + } finally { + br.close(); + } - noAvg = trans.env().newTransNoAvg(); - cqlBatch = new CQLBatch(noAvg.debug(),session); - cbl = new CQLBatchLoop(cqlBatch,50,dryRun); - - lastN = new LastNotified(session); - } + noAvg = trans.env().newTransNoAvg(); + cqlBatch = new CQLBatch(noAvg.debug(),session); + cbl = new CQLBatchLoop(cqlBatch,50,dryRun); + + lastN = new LastNotified(session); + } - /* - * Note: We try to put things related to Notify as Main Class in Run, where we might have put in - * Constructor, so that we can have other Classes call just the "notify" method. - */ - @Override - protected void run(AuthzTrans trans) { + /* + * Note: We try to put things related to Notify as Main Class in Run, where we might have put in + * Constructor, so that we can have other Classes call just the "notify" method. + */ + @Override + protected void run(AuthzTrans trans) { - final Holder<List<String>> info = new Holder<>(null); - final Set<String> errorSet = new HashSet<>(); - String fmt = "%s"+Chrono.dateOnlyStamp()+".csv"; + final Holder<List<String>> info = new Holder<>(null); + final Set<String> errorSet = new HashSet<>(); + String fmt = "%s"+Chrono.dateOnlyStamp()+".csv"; - try { - // Class Load possible data - NotifyBody.load(env.access()); + try { + // Class Load possible data + NotifyBody.load(env.access()); - // Create Intermediate Output - File logDir = logDir(); - Set<File> notifyFile = new HashSet<>(); - if(args().length>0) { - for(int i=0;i<args().length;++i) { - notifyFile.add(new File(logDir, args()[i])); - } - } else { - File file; - for(NotifyBody nb : NotifyBody.getAll()) { - file = new File(logDir,String.format(fmt, nb.name())); - if(file.exists()) { - trans.info().printf("Processing '%s' in %s",nb.type(),file.getCanonicalPath()); - notifyFile.add(file); - } else { - trans.info().printf("No Files found for %s",nb.name()); - } - } - } + // Create Intermediate Output + File logDir = logDir(); + Set<File> notifyFile = new HashSet<>(); + if(args().length>0) { + for(int i=0;i<args().length;++i) { + notifyFile.add(new File(logDir, args()[i])); + } + } else { + File file; + for(NotifyBody nb : NotifyBody.getAll()) { + file = new File(logDir,String.format(fmt, nb.name())); + if(file.exists()) { + trans.info().printf("Processing '%s' in %s",nb.type(),file.getCanonicalPath()); + notifyFile.add(file); + } else { + trans.info().printf("No Files found for %s",nb.name()); + } + } + } - for(File f : notifyFile) { - CSV csv = new CSV(env.access(),f); - try { - csv.visit(new CSV.Visitor() { - @Override - public void visit(List<String> row) throws IOException, CadiException { - if("info".equals(row.get(0))) { - info.set(row); - } - if(info.get()==null) { - throw new CadiException("First line of Feed MUST contain 'info' record"); - } String key = row.get(0)+'|'+info.get().get(1); - NotifyBody body = NotifyBody.get(key); - if(body==null) { - errorSet.add("No NotifyBody defined for " + key); - } else { - body.store(row); - } - } - }); - } catch (IOException | CadiException e) { - e.printStackTrace(); - } + for(File f : notifyFile) { + CSV csv = new CSV(env.access(),f); + try { + csv.visit(new CSV.Visitor() { + @Override + public void visit(List<String> row) throws IOException, CadiException { + if("info".equals(row.get(0))) { + info.set(row); + } + if(info.get()==null) { + throw new CadiException("First line of Feed MUST contain 'info' record"); + } String key = row.get(0)+'|'+info.get().get(1); + NotifyBody body = NotifyBody.get(key); + if(body==null) { + errorSet.add("No NotifyBody defined for " + key); + } else { + body.store(row); + } + } + }); + } catch (IOException | CadiException e) { + e.printStackTrace(); + } - } + } - // now create Notification - for(NotifyBody nb : NotifyBody.getAll()) { - int count = notify(noAvg, nb); - trans.info().printf("Emailed %d for %s",count,nb.name()); - } - - // - // Do Pending Approval Notifies. We do this separately, because we are consolidating - // all the new entries, etc. - // - List<CSV> csvList = new ArrayList<>(); - for(String s : new String[] {"Approvals","ApprovalsNew"}) { - File f = new File(logDir(),String.format(fmt, s)); - if(f.exists()) { - csvList.add(new CSV(access,f)); - } - } - - Map<String,Pending> mpending = new TreeMap<>(); - Holder<Integer> count = new Holder<>(0); - for(CSV approveCSV : csvList) { - TimeTaken tt = trans.start("Load Analyzed Reminders",Trans.SUB,approveCSV.name()); - try { - approveCSV.visit(row -> { - switch(row.get(0)) { -// case "info": -// break; - case Pending.REMIND: - try { - String user = row.get(1); - Pending p = new Pending(row); - Pending mp = mpending.get(user); - if(mp==null) { - mpending.put(user, p); - } else { - mp.inc(p); // FYI, unlikely - } - count.set(count.get()+1); - } catch (ParseException e) { - trans.error().log(e); - } - break; - } - }); - } catch (IOException | CadiException e) { - trans.error().log(e); - } finally { - tt.done(); - } - } - trans.info().printf("Read %d Reminder Rows", count.get()); - - NotifyPendingApprBody npab = new NotifyPendingApprBody(access); + // now create Notification + for(NotifyBody nb : NotifyBody.getAll()) { + int count = notify(noAvg, nb); + trans.info().printf("Emailed %d for %s",count,nb.name()); + } + + // + // Do Pending Approval Notifies. We do this separately, because we are consolidating + // all the new entries, etc. + // + List<CSV> csvList = new ArrayList<>(); + for(String s : new String[] {"Approvals","ApprovalsNew"}) { + File f = new File(logDir(),String.format(fmt, s)); + if(f.exists()) { + csvList.add(new CSV(access,f)); + } + } + + Map<String,Pending> mpending = new TreeMap<>(); + Holder<Integer> count = new Holder<>(0); + for(CSV approveCSV : csvList) { + TimeTaken tt = trans.start("Load Analyzed Reminders",Trans.SUB,approveCSV.name()); + try { + approveCSV.visit(row -> { + switch(row.get(0)) { +// case "info": +// break; + case Pending.REMIND: + try { + String user = row.get(1); + Pending p = new Pending(row); + Pending mp = mpending.get(user); + if(mp==null) { + mpending.put(user, p); + } else { + mp.inc(p); // FYI, unlikely + } + count.set(count.get()+1); + } catch (ParseException e) { + trans.error().log(e); + } + break; + } + }); + } catch (IOException | CadiException e) { + trans.error().log(e); + } finally { + tt.done(); + } + } + trans.info().printf("Read %d Reminder Rows", count.get()); + + NotifyPendingApprBody npab = new NotifyPendingApprBody(access); - GregorianCalendar gc = new GregorianCalendar(); - gc.add(GregorianCalendar.DAY_OF_MONTH, 7); // Get from INFO? - Date oneWeek = gc.getTime(); - CSV.Saver rs = new CSV.Saver(); - - TimeTaken tt = trans.start("Obtain Last Notifications for Approvers", Trans.SUB); - try { - lastN.add(mpending.keySet()); - } finally { - tt.done(); - } - - Pending p; - - tt = trans.start("Notify for Pending", Trans.SUB); - List<String> idList = new ArrayList<String>(); - String id; - try { - for(Entry<String, Pending> es : mpending.entrySet()) { - id = es.getKey(); - idList.clear(); - idList.add(id); - p = es.getValue(); - boolean nap = p.newApprovals(); - if(!nap) { - Date dateLastNotified = lastN.lastNotified(id,"pending",""); - if(dateLastNotified==null || dateLastNotified.after(oneWeek) ) { - nap=true; - } - } - if(nap) { - rs.row("appr", id,p.qty(),batchEnv); - npab.store(rs.asList()); - if(notify(noAvg, npab)>0) { - // Update -// lastN.update(cbl.inc(),key,"pending",""); - npab.record(trans,cbl.inc(), id, idList, lastN); - npab.inc(); - } - } - } - } finally { - cbl.flush(); - tt.done(); + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.DAY_OF_MONTH, 7); // Get from INFO? + Date oneWeek = gc.getTime(); + CSV.Saver rs = new CSV.Saver(); + + TimeTaken tt = trans.start("Obtain Last Notifications for Approvers", Trans.SUB); + try { + lastN.add(mpending.keySet()); + } finally { + tt.done(); + } + + Pending p; + + tt = trans.start("Notify for Pending", Trans.SUB); + List<String> idList = new ArrayList<String>(); + String id; + try { + for(Entry<String, Pending> es : mpending.entrySet()) { + id = es.getKey(); + idList.clear(); + idList.add(id); + p = es.getValue(); + boolean nap = p.newApprovals(); + if(!nap) { + Date dateLastNotified = lastN.lastNotified(id,"pending",""); + if(dateLastNotified==null || dateLastNotified.after(oneWeek) ) { + nap=true; + } + } + if(nap) { + rs.row("appr", id,p.qty(),batchEnv); + npab.store(rs.asList()); + if(notify(noAvg, npab)>0) { + // Update +// lastN.update(cbl.inc(),key,"pending",""); + npab.record(trans,cbl.inc(), id, idList, lastN); + npab.inc(); + } + } + } + } finally { + cbl.flush(); + tt.done(); trans.info().printf("Notified %d persons of Pending Approvals", npab.count()); - } + } - } catch (APIException | IOException e1) { - trans.error().log(e1); - } finally { - for(String s : errorSet) { - trans.audit().log(s); - } - } - } + } catch (APIException | IOException e1) { + trans.error().log(e1); + } finally { + for(String s : errorSet) { + trans.audit().log(s); + } + } + } - private int notify(AuthzTrans trans, NotifyBody nb) { - List<String> toList = new ArrayList<>(); - List<String> ccList = new ArrayList<>(); - List<String> idList = new ArrayList<>(); + private int notify(AuthzTrans trans, NotifyBody nb) { + List<String> toList = new ArrayList<>(); + List<String> ccList = new ArrayList<>(); + List<String> idList = new ArrayList<>(); - String run = nb.type()+nb.name(); - String test = dryRun?run:null; - - ONE_EMAIL: - for(String id : nb.users()) { - toList.clear(); - ccList.clear(); - idList.clear(); - try { - List<Identity> identities = trans.org().getIDs(trans, id, nb.escalation()); - if(identities.isEmpty()) { - trans.warn().printf("%s is invalid for this Organization. Skipping notification.",id); - } else { - Identity identity = null; - for(Identity ident : identities) { - if(identity==null) { - identity = ident; - toList.add(ident.email()); - } else { - ccList.add(ident.email()); - } - idList.add(ident.fullID()); - } - if(identity==null) { // Actually, identity can't be null here, because - break; // if(identities.isEmpty() {..} else {... <here> - } // So this is here to avoid Sonar false positive only - StringBuilder content = new StringBuilder(); - content.append(String.format(header,version,Identity.mixedCase(identity.firstName()))); + String run = nb.type()+nb.name(); + String test = dryRun?run:null; + + ONE_EMAIL: + for(String id : nb.users()) { + toList.clear(); + ccList.clear(); + idList.clear(); + try { + List<Identity> identities = trans.org().getIDs(trans, id, nb.escalation()); + if(identities.isEmpty()) { + trans.warn().printf("%s is invalid for this Organization. Skipping notification.",id); + } else { + Identity identity = null; + for(Identity ident : identities) { + if(identity==null) { + identity = ident; + toList.add(ident.email()); + } else { + ccList.add(ident.email()); + } + idList.add(ident.fullID()); + } + if(identity==null) { // Actually, identity can't be null here, because + break; // if(identities.isEmpty() {..} else {... <here> + } // So this is here to avoid Sonar false positive only + StringBuilder content = new StringBuilder(); + content.append(String.format(header,version,Identity.mixedCase(identity.firstName()))); - nb.body(trans, content, indent, this, id); - content.append(footer); + nb.body(trans, content, indent, this, id); + content.append(footer); - if(mailer.sendEmail(trans, test, toList, ccList, nb.subject(),content.toString(), urgent)) { - nb.record(trans,cbl.inc(), id, idList, lastN); - nb.inc(); - } else { - trans.error().log("Mailer failed to send Mail"); - } - if(maxEmails>0 && nb.count()>=maxEmails) { - break ONE_EMAIL; - } - } - } catch (OrganizationException e) { - trans.error().log(e); - } - } - cbl.flush(); - return nb.count(); - } + if(mailer.sendEmail(trans, test, toList, ccList, nb.subject(),content.toString(), urgent)) { + nb.record(trans,cbl.inc(), id, idList, lastN); + nb.inc(); + } else { + trans.error().log("Mailer failed to send Mail"); + } + if(maxEmails>0 && nb.count()>=maxEmails) { + break ONE_EMAIL; + } + } + } catch (OrganizationException e) { + trans.error().log(e); + } + } + cbl.flush(); + return nb.count(); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.batch.Batch#_close(org.onap.aaf.auth.env.AuthzTrans) - */ - @Override - protected void _close(AuthzTrans trans) { - cbl.flush(); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.batch.Batch#_close(org.onap.aaf.auth.env.AuthzTrans) + */ + @Override + protected void _close(AuthzTrans trans) { + cbl.flush(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/PrepExtend.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/PrepExtend.java index 47a1b600..bcdd4401 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/PrepExtend.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/PrepExtend.java @@ -44,141 +44,141 @@ import org.onap.aaf.misc.env.util.Chrono; public class PrepExtend extends Batch { - public static final String PREP_EXTEND = "PrepExtend"; - private static final String CSV = ".csv"; - private static final String INFO = "info"; + public static final String PREP_EXTEND = "PrepExtend"; + private static final String CSV = ".csv"; + private static final String INFO = "info"; - /** - * Create a list of Creds and UserRoles to extend - * Note: Certificates cannot be renewed in this way. - * - * Arguments From (0 = today, -2 = 2 weeks back) and To (weeks from today) - * - * @param trans - * @throws APIException - * @throws IOException - * @throws OrganizationException - */ - public PrepExtend(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); + /** + * Create a list of Creds and UserRoles to extend + * Note: Certificates cannot be renewed in this way. + * + * Arguments From (0 = today, -2 = 2 weeks back) and To (weeks from today) + * + * @param trans + * @throws APIException + * @throws IOException + * @throws OrganizationException + */ + public PrepExtend(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cluster.connect(); - } finally { - tt.done(); - } - } finally { - tt0.done(); - } - } + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cluster.connect(); + } finally { + tt.done(); + } + } finally { + tt0.done(); + } + } - @Override - protected void run(AuthzTrans trans) { - GregorianCalendar gc = new GregorianCalendar(); - Date now = gc.getTime(); - - int ifrom = 0; - int ito = 4; - - for(int i=0; i< args().length;++i) { - switch(args()[i]) { - case "-from": - if(args().length>i+1) { - ifrom = Integer.parseInt(args()[i++ +1]); - } - break; - case "-to": - if(args().length>i+1) { - ito = Integer.parseInt(args()[i++ +1]); - } - break; - } - } - if(ifrom < -4) { - System.err.println("Invalid -from param"); - return; - } - - if(ito<=0 || ito>24 || ifrom>ito) { - System.err.println("Invalid -to param"); - return; - } - - // Make sure to is Zero based from today. - if(ifrom<0) { - ito+= ifrom*-1; - } - - gc.add(GregorianCalendar.WEEK_OF_MONTH, ifrom); - Date from = gc.getTime(); - - gc.add(GregorianCalendar.WEEK_OF_MONTH, ito /* with From calculated in */); - Date to = gc.getTime(); - - try { - File file = new File(logDir(), PREP_EXTEND + Chrono.dateOnlyStamp(now) + CSV); - final CSV puntCSV = new CSV(env.access(),file); - final Writer cw = puntCSV.writer(); - cw.row(INFO,PREP_EXTEND,Chrono.dateOnlyStamp(now),0); + @Override + protected void run(AuthzTrans trans) { + GregorianCalendar gc = new GregorianCalendar(); + Date now = gc.getTime(); + + int ifrom = 0; + int ito = 4; + + for(int i=0; i< args().length;++i) { + switch(args()[i]) { + case "-from": + if(args().length>i+1) { + ifrom = Integer.parseInt(args()[i++ +1]); + } + break; + case "-to": + if(args().length>i+1) { + ito = Integer.parseInt(args()[i++ +1]); + } + break; + } + } + if(ifrom < -4) { + System.err.println("Invalid -from param"); + return; + } + + if(ito<=0 || ito>24 || ifrom>ito) { + System.err.println("Invalid -to param"); + return; + } + + // Make sure to is Zero based from today. + if(ifrom<0) { + ito+= ifrom*-1; + } + + gc.add(GregorianCalendar.WEEK_OF_MONTH, ifrom); + Date from = gc.getTime(); + + gc.add(GregorianCalendar.WEEK_OF_MONTH, ito /* with From calculated in */); + Date to = gc.getTime(); + + try { + File file = new File(logDir(), PREP_EXTEND + Chrono.dateOnlyStamp(now) + CSV); + final CSV puntCSV = new CSV(env.access(),file); + final Writer cw = puntCSV.writer(); + cw.row(INFO,PREP_EXTEND,Chrono.dateOnlyStamp(now),0); - try { - trans.info().log("Process UserRoles for Extending"); - /** - Run through User Roles. - If match Date Range, write out to appropriate file. - */ - UserRole.load(trans, session, UserRole.v2_0_11, ur -> { - if(from.before(ur.expires()) && to.after(ur.expires())) { - ur.row(cw,UserRole.UR); - } - }); - - trans.info().log("Process BasicAuth for Extending"); - TimeTaken tt0 = trans.start("Load Credentials", Env.REMOTE); - try { - // Load only Valid Basic Auth - Cred.load(trans, session, CredDAO.BASIC_AUTH_SHA256); - } finally { - tt0.done(); - } + try { + trans.info().log("Process UserRoles for Extending"); + /** + Run through User Roles. + If match Date Range, write out to appropriate file. + */ + UserRole.load(trans, session, UserRole.v2_0_11, ur -> { + if(from.before(ur.expires()) && to.after(ur.expires())) { + ur.row(cw,UserRole.UR); + } + }); + + trans.info().log("Process BasicAuth for Extending"); + TimeTaken tt0 = trans.start("Load Credentials", Env.REMOTE); + try { + // Load only Valid Basic Auth + Cred.load(trans, session, CredDAO.BASIC_AUTH_SHA256); + } finally { + tt0.done(); + } - /** - Run through Creds. - If match Date Range, write out to appropriate file. - */ - Map<Integer,Instance> imap = new HashMap<>(); - Instance prev; - for(Cred cred : Cred.data.values()) { - imap.clear(); - for(Instance i : cred.instances) { - if(from.before(i.expires) && to.after(i.expires)) { - prev = imap.get(i.other); - // Only do LATEST instance of same cred (accounts for previously extended creds) - if(prev==null || prev.expires.before(i.expires)) { - imap.put(i.other,i); - } - } - }; - for(Instance i: imap.values()) { - cred.row(cw,i); - } - } - } finally { - cw.close(); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - } - @Override - protected void _close(AuthzTrans trans) { - session.close(); - } + /** + Run through Creds. + If match Date Range, write out to appropriate file. + */ + Map<Integer,Instance> imap = new HashMap<>(); + Instance prev; + for(Cred cred : Cred.data.values()) { + imap.clear(); + for(Instance i : cred.instances) { + if(from.before(i.expires) && to.after(i.expires)) { + prev = imap.get(i.other); + // Only do LATEST instance of same cred (accounts for previously extended creds) + if(prev==null || prev.expires.before(i.expires)) { + imap.put(i.other,i); + } + } + }; + for(Instance i: imap.values()) { + cred.row(cw,i); + } + } + } finally { + cw.close(); + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + @Override + protected void _close(AuthzTrans trans) { + session.close(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyBody.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyBody.java index ae7daa09..ec8d1451 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyBody.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyBody.java @@ -46,217 +46,217 @@ import org.onap.aaf.cadi.Access; import org.onap.aaf.misc.env.APIException; public abstract class NotifyBody { - private static final String DUPL = "<td style=\"text-indent: 4em;\">''</td>"; - private static final Map<String,NotifyBody> bodyMap = new HashMap<>(); + private static final String DUPL = "<td style=\"text-indent: 4em;\">''</td>"; + private static final Map<String,NotifyBody> bodyMap = new HashMap<>(); - protected Map<String,List<List<String>>> rows; - protected final String env; - protected final String gui_url; - - private final String name; - private final String type; - private String date; - private int escalation; - private int count; - - public NotifyBody(Access access, final String type, final String name) { - rows = new TreeMap<>(); - this.name = name; - this.type = type; - date=""; - escalation = 1; - count = 0; - env = access.getProperty("CASS_ENV","DEVL"); - gui_url = access.getProperty("GUI_URL", ""); - } - - public void store(List<String> row) { - if(!row.isEmpty()) { - if("info".equals(row.get(0))) { - if(row.size()>2) { - date = row.get(2); - } - if(row.size()>3) { - escalation = Integer.parseInt(row.get(3)); - } - return; - } else if(type.equals(row.get(0))) { - String user = user(row); - if(user!=null) { - List<List<String>> lss = rows.get(user); - if(lss == null) { - lss = new ArrayList<>(); - rows.put(user,lss); - } - lss.add(row); - } - } - } - } + protected Map<String,List<List<String>>> rows; + protected final String env; + protected final String gui_url; + + private final String name; + private final String type; + private String date; + private int escalation; + private int count; + + public NotifyBody(Access access, final String type, final String name) { + rows = new TreeMap<>(); + this.name = name; + this.type = type; + date=""; + escalation = 1; + count = 0; + env = access.getProperty("CASS_ENV","DEVL"); + gui_url = access.getProperty("GUI_URL", ""); + } + + public void store(List<String> row) { + if(!row.isEmpty()) { + if("info".equals(row.get(0))) { + if(row.size()>2) { + date = row.get(2); + } + if(row.size()>3) { + escalation = Integer.parseInt(row.get(3)); + } + return; + } else if(type.equals(row.get(0))) { + String user = user(row); + if(user!=null) { + List<List<String>> lss = rows.get(user); + if(lss == null) { + lss = new ArrayList<>(); + rows.put(user,lss); + } + lss.add(row); + } + } + } + } - public String name() { - return name; - } - - public String type() { - return type; - } - - public String date() { - return date; - } - public int escalation() { - return escalation; - } - - public Set<String> users() { - return rows.keySet(); - } - - /** - * ID must be set from Row for Email lookup - * - * @param trans - * @param n - * @param id - * @param row - * @return - */ - public abstract boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id); - - /** - * Return "null" if user not found in row... Code will handle. - * @param row - * @return - */ - protected abstract String user(List<String> row); - - /** - * Provide a context-sensitive Subject, which includes ENV as well as details - * - * @return - */ - public abstract String subject(); + public String name() { + return name; + } + + public String type() { + return type; + } + + public String date() { + return date; + } + public int escalation() { + return escalation; + } + + public Set<String> users() { + return rows.keySet(); + } + + /** + * ID must be set from Row for Email lookup + * + * @param trans + * @param n + * @param id + * @param row + * @return + */ + public abstract boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id); + + /** + * Return "null" if user not found in row... Code will handle. + * @param row + * @return + */ + protected abstract String user(List<String> row); + + /** + * Provide a context-sensitive Subject, which includes ENV as well as details + * + * @return + */ + public abstract String subject(); - /** - * Record the fact that a particular Notification was marked as "sent" by Emailer. - * - * @param trans - * @param approver - * @param ln - */ - public abstract void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified ln); - - /** - * Get Notify Body based on key of - * type|name - */ - public static NotifyBody get(String key) { - return bodyMap.get(key); - } - - /** - * Return set of loaded NotifyBodies - * - */ - public static Collection<NotifyBody> getAll() { - // Note: The same Notify Body is entered several times with different keys. - // Therefore, need a Set of Values, not all the Values. - Set<NotifyBody> set = new HashSet<>(); - set.addAll(bodyMap.values()); - return set; - } - - /** - * @param propAccess - * @throws URISyntaxException - * - */ - public static void load(Access access) throws APIException, IOException { - // class load available NotifyBodies - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - Package pkg = NotifyBody.class.getPackage(); - String path = pkg.getName().replace('.', '/'); - URL url = cl.getResource(path); - List<String> classNames = new ArrayList<>(); - String urlString = url.toString(); - if(urlString.startsWith("jar:file:")) { - int exclam = urlString.lastIndexOf('!'); - JarFile jf = new JarFile(urlString.substring(9,exclam)); - try { - Enumeration<JarEntry> jfe = jf.entries(); - while(jfe.hasMoreElements()) { - String name = jfe.nextElement().getName(); - if(name.startsWith(path) && name.endsWith(".class")) { - classNames.add(name.substring(0,name.length()-6).replace('/', '.')); - } - } - } finally { - jf.close(); - } - } else { - File dir = new File(url.getFile()); - for( String f : dir.list()) { - if(f.endsWith(".class")) { - classNames.add(pkg.getName()+'.'+f.substring(0,f.length()-6)); - } - } - } - for(String cls : classNames) { - try { - Class<?> c = cl.loadClass(cls); - if(c!=null) { - if(!Modifier.isAbstract(c.getModifiers())) { - Constructor<?> cst = c.getConstructor(Access.class); - NotifyBody nb = (NotifyBody)cst.newInstance(access); - if(nb!=null) { - bodyMap.put("info|"+nb.name, nb); - bodyMap.put(nb.type+'|'+nb.name, nb); - } - } - } - } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - e.printStackTrace(); - } - } - } + /** + * Record the fact that a particular Notification was marked as "sent" by Emailer. + * + * @param trans + * @param approver + * @param ln + */ + public abstract void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified ln); + + /** + * Get Notify Body based on key of + * type|name + */ + public static NotifyBody get(String key) { + return bodyMap.get(key); + } + + /** + * Return set of loaded NotifyBodies + * + */ + public static Collection<NotifyBody> getAll() { + // Note: The same Notify Body is entered several times with different keys. + // Therefore, need a Set of Values, not all the Values. + Set<NotifyBody> set = new HashSet<>(); + set.addAll(bodyMap.values()); + return set; + } + + /** + * @param propAccess + * @throws URISyntaxException + * + */ + public static void load(Access access) throws APIException, IOException { + // class load available NotifyBodies + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + Package pkg = NotifyBody.class.getPackage(); + String path = pkg.getName().replace('.', '/'); + URL url = cl.getResource(path); + List<String> classNames = new ArrayList<>(); + String urlString = url.toString(); + if(urlString.startsWith("jar:file:")) { + int exclam = urlString.lastIndexOf('!'); + JarFile jf = new JarFile(urlString.substring(9,exclam)); + try { + Enumeration<JarEntry> jfe = jf.entries(); + while(jfe.hasMoreElements()) { + String name = jfe.nextElement().getName(); + if(name.startsWith(path) && name.endsWith(".class")) { + classNames.add(name.substring(0,name.length()-6).replace('/', '.')); + } + } + } finally { + jf.close(); + } + } else { + File dir = new File(url.getFile()); + for( String f : dir.list()) { + if(f.endsWith(".class")) { + classNames.add(pkg.getName()+'.'+f.substring(0,f.length()-6)); + } + } + } + for(String cls : classNames) { + try { + Class<?> c = cl.loadClass(cls); + if(c!=null) { + if(!Modifier.isAbstract(c.getModifiers())) { + Constructor<?> cst = c.getConstructor(Access.class); + NotifyBody nb = (NotifyBody)cst.newInstance(access); + if(nb!=null) { + bodyMap.put("info|"+nb.name, nb); + bodyMap.put(nb.type+'|'+nb.name, nb); + } + } + } + } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + e.printStackTrace(); + } + } + } - protected void print(StringBuilder sb, int indent, Object ... objs) { - for(int i=0;i<indent;++i) { - sb.append(' '); - } - for(Object o : objs) { - sb.append(o.toString()); - } - } - - protected void println(StringBuilder sb, int indent, Object ... objs) { - print(sb,indent,objs); - sb.append('\n'); - } + protected void print(StringBuilder sb, int indent, Object ... objs) { + for(int i=0;i<indent;++i) { + sb.append(' '); + } + for(Object o : objs) { + sb.append(o.toString()); + } + } + + protected void println(StringBuilder sb, int indent, Object ... objs) { + print(sb,indent,objs); + sb.append('\n'); + } - protected void printf(StringBuilder sb, int indent, String fmt, Object ... objs) { - print(sb,indent,String.format(fmt, objs)); - } + protected void printf(StringBuilder sb, int indent, String fmt, Object ... objs) { + print(sb,indent,String.format(fmt, objs)); + } - protected String printCell(StringBuilder sb, int indent, String current, String prev) { - if(current.equals(prev)) { - println(sb,indent,DUPL); - } else { - printCell(sb,indent,current); - } - return current; // use to set prev... - } - - protected void printCell(StringBuilder sb, int indent, String current) { - println(sb,indent,"<td>",current,"</td>"); - } - - public synchronized void inc() { - ++count; - } - - public int count() { - return count; - } + protected String printCell(StringBuilder sb, int indent, String current, String prev) { + if(current.equals(prev)) { + println(sb,indent,DUPL); + } else { + printCell(sb,indent,current); + } + return current; // use to set prev... + } + + protected void printCell(StringBuilder sb, int indent, String current) { + println(sb,indent,"<td>",current,"</td>"); + } + + public synchronized void inc() { + ++count; + } + + public int count() { + return count; + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyCredBody.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyCredBody.java index 72fed8ab..7001c024 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyCredBody.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyCredBody.java @@ -34,110 +34,110 @@ import org.onap.aaf.misc.env.util.Chrono; public abstract class NotifyCredBody extends NotifyBody { - private final String explanation; - private final String instruction; - - public NotifyCredBody(Access access, String name) { - super(access,"cred",name); - - // Default - explanation = "The following Credentials that you are responsible for " - + "are expiring on the dates shown. <br><br>" - ; - + private final String explanation; + private final String instruction; + + public NotifyCredBody(Access access, String name) { + super(access,"cred",name); + + // Default + explanation = "The following Credentials that you are responsible for " + + "are expiring on the dates shown. <br><br>" + ; + instruction = "<br><h3>Instructions for 'Password':</h3><ul>" - + "<li><b><i>Click</i></b> on the Fully Qualified ID to ADD a new Password</li>" - + "<li><b>REMEMBER!</b> You are not finished until you <ol>" - + "<li><b>CHANGE <i>ALL</i></b> the configurations on <b><i>ALL</i></b> your processes!!</li>" - + "<li><b>BOUNCE</b> them</li></ol>" - + "<li>IF there is a WARNING, click the link for more information</li>" - + "</ul>"; - } - - /** - * Default Dynamic Text. Override is expected - * @return - */ - protected String dynamic() { - return "Failure to act before the expiration date will cause your App's Authentications to fail."; - } + + "<li><b><i>Click</i></b> on the Fully Qualified ID to ADD a new Password</li>" + + "<li><b>REMEMBER!</b> You are not finished until you <ol>" + + "<li><b>CHANGE <i>ALL</i></b> the configurations on <b><i>ALL</i></b> your processes!!</li>" + + "<li><b>BOUNCE</b> them</li></ol>" + + "<li>IF there is a WARNING, click the link for more information</li>" + + "</ul>"; + } + + /** + * Default Dynamic Text. Override is expected + * @return + */ + protected String dynamic() { + return "Failure to act before the expiration date will cause your App's Authentications to fail."; + } - @Override - public boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id) { - print(sb,indent,explanation); - print(sb,indent,dynamic()); - println(sb,indent,instruction); - println(sb,indent,"<table>"); - indent+=2; - println(sb,indent,"<tr>"); - indent+=2; - println(sb,indent,"<th>Fully Qualified ID</th>"); - println(sb,indent,"<th>Unique ID</th>"); - println(sb,indent,"<th>Type</th>"); - println(sb,indent,"<th>Expires</th>"); - println(sb,indent,"<th>Warnings</th>"); - indent-=2; - println(sb,indent,"</tr>"); - String theid; - String type; - String info; - String expires; - String warnings; - GregorianCalendar gc = new GregorianCalendar(); - for(List<String> row : rows.get(id)) { - theid=row.get(1); - switch(row.get(3)) { - case "1": - case "2": - type = "Password"; - break; - case "200": - type = "x509 (Certificate)"; - break; - default: - type = "Unknown, see AAF GUI"; - break; - } - theid = "<a href=\""+n.guiURL+"/creddetail?ns="+row.get(2)+"\">"+theid+"</a>"; - gc.setTimeInMillis(Long.parseLong(row.get(5))); - expires = Chrono.niceUTCStamp(gc); - info = row.get(6); - //TODO get Warnings - warnings = ""; - - println(sb,indent,"<tr>"); - indent+=2; - printCell(sb,indent,theid); - printCell(sb,indent,info); - printCell(sb,indent,type); - printCell(sb,indent,expires); - printCell(sb,indent,warnings); - indent-=2; - println(sb,indent,"</tr>"); - } - indent-=2; - println(sb,indent,"</table>"); - - return true; - } - - @Override - public void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified ln) { - for(List<String> row : rows.get(id)) { - for(String n : notified) { - // Need to match LastNotified Key ... cred.id + '|' + inst.type + '|' + inst.tag; - ln.update(query, n, row.get(0), row.get(1)+'|'+row.get(3)+'|'+row.get(6)); - } - } - } + @Override + public boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id) { + print(sb,indent,explanation); + print(sb,indent,dynamic()); + println(sb,indent,instruction); + println(sb,indent,"<table>"); + indent+=2; + println(sb,indent,"<tr>"); + indent+=2; + println(sb,indent,"<th>Fully Qualified ID</th>"); + println(sb,indent,"<th>Unique ID</th>"); + println(sb,indent,"<th>Type</th>"); + println(sb,indent,"<th>Expires</th>"); + println(sb,indent,"<th>Warnings</th>"); + indent-=2; + println(sb,indent,"</tr>"); + String theid; + String type; + String info; + String expires; + String warnings; + GregorianCalendar gc = new GregorianCalendar(); + for(List<String> row : rows.get(id)) { + theid=row.get(1); + switch(row.get(3)) { + case "1": + case "2": + type = "Password"; + break; + case "200": + type = "x509 (Certificate)"; + break; + default: + type = "Unknown, see AAF GUI"; + break; + } + theid = "<a href=\""+n.guiURL+"/creddetail?ns="+row.get(2)+"\">"+theid+"</a>"; + gc.setTimeInMillis(Long.parseLong(row.get(5))); + expires = Chrono.niceUTCStamp(gc); + info = row.get(6); + //TODO get Warnings + warnings = ""; + + println(sb,indent,"<tr>"); + indent+=2; + printCell(sb,indent,theid); + printCell(sb,indent,info); + printCell(sb,indent,type); + printCell(sb,indent,expires); + printCell(sb,indent,warnings); + indent-=2; + println(sb,indent,"</tr>"); + } + indent-=2; + println(sb,indent,"</table>"); + + return true; + } + + @Override + public void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified ln) { + for(List<String> row : rows.get(id)) { + for(String n : notified) { + // Need to match LastNotified Key ... cred.id + '|' + inst.type + '|' + inst.tag; + ln.update(query, n, row.get(0), row.get(1)+'|'+row.get(3)+'|'+row.get(6)); + } + } + } - @Override - public String user(List<String> row) { - if( (row != null) && row.size()>1) { - return row.get(1); - } - return null; - } + @Override + public String user(List<String> row) { + if( (row != null) && row.size()>1) { + return row.get(1); + } + return null; + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyPendingApprBody.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyPendingApprBody.java index 8019e446..76a44166 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyPendingApprBody.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/NotifyPendingApprBody.java @@ -29,58 +29,58 @@ import org.onap.aaf.cadi.Access; public class NotifyPendingApprBody extends NotifyBody { - public NotifyPendingApprBody(Access access) { - super(access,"appr","PendingApproval"); - } + public NotifyPendingApprBody(Access access) { + super(access,"appr","PendingApproval"); + } - @Override - public boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id) { - boolean rv = false; - for(List<String> row : rows.get(id)) { - String qty = row.get(2); - if("1".equals(qty)) { - printf(sb,indent,"You have an Approval in the AAF %s Environment awaiting your decision.\n",row.get(3)); - } else { - printf(sb,indent,"You have %s Approvals in the AAF %s Environment awaiting your decision.\n",qty,row.get(3)); - } - printf(sb,indent,"<br><br><b>ACTION:</b> <i>Click on</i> <a href=\"%s/approve\">AAF Approval Page</a>",n.guiURL); - rv = true; - break; // only one - } - - return rv; - } + @Override + public boolean body(AuthzTrans trans, StringBuilder sb, int indent, Notify n, String id) { + boolean rv = false; + for(List<String> row : rows.get(id)) { + String qty = row.get(2); + if("1".equals(qty)) { + printf(sb,indent,"You have an Approval in the AAF %s Environment awaiting your decision.\n",row.get(3)); + } else { + printf(sb,indent,"You have %s Approvals in the AAF %s Environment awaiting your decision.\n",qty,row.get(3)); + } + printf(sb,indent,"<br><br><b>ACTION:</b> <i>Click on</i> <a href=\"%s/approve\">AAF Approval Page</a>",n.guiURL); + rv = true; + break; // only one + } + + return rv; + } - @Override - public String user(List<String> row) { - if( (row != null) && row.size()>1) { - return row.get(1); - } - return null; - } + @Override + public String user(List<String> row) { + if( (row != null) && row.size()>1) { + return row.get(1); + } + return null; + } - @Override - public String subject() { - return String.format("AAF Pending Approval Notification (ENV: %s)",env); - } + @Override + public String subject() { + return String.format("AAF Pending Approval Notification (ENV: %s)",env); + } - - @Override - public void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified lastN) { - for(String n : notified) { - // No special key for Pending Requests. - lastN.update(query,n,"pending",""); - } - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.batch.reports.bodies.NotifyBody#store(java.util.List) - */ - @Override - public void store(List<String> row) { - // Notify Pending is setup for 1 Notification at a time - super.rows.clear(); - super.store(row); - } + + @Override + public void record(AuthzTrans trans, StringBuilder query, String id, List<String> notified, LastNotified lastN) { + for(String n : notified) { + // No special key for Pending Requests. + lastN.update(query,n,"pending",""); + } + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.batch.reports.bodies.NotifyBody#store(java.util.List) + */ + @Override + public void store(List<String> row) { + // Notify Pending is setup for 1 Notification at a time + super.rows.clear(); + super.store(row); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneMonthNotifyCredBody.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneMonthNotifyCredBody.java index 866dc23c..8747ebf8 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneMonthNotifyCredBody.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneMonthNotifyCredBody.java @@ -26,20 +26,20 @@ import org.onap.aaf.auth.batch.helpers.ExpireRange; import org.onap.aaf.cadi.Access; public class OneMonthNotifyCredBody extends NotifyCredBody { - public OneMonthNotifyCredBody(Access access) throws IOException { - super(access, ExpireRange.ONE_MONTH); - } - - @Override - public String subject() { - return String.format("AAF One Month Credential Notification (ENV: %s)",env); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() - */ - @Override - protected String dynamic() { - return "This is your <b>one month</b> notification. " + super.dynamic(); - } + public OneMonthNotifyCredBody(Access access) throws IOException { + super(access, ExpireRange.ONE_MONTH); + } + + @Override + public String subject() { + return String.format("AAF One Month Credential Notification (ENV: %s)",env); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() + */ + @Override + protected String dynamic() { + return "This is your <b>one month</b> notification. " + super.dynamic(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneWeekNotifyCredBody.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneWeekNotifyCredBody.java index e28388d5..a1277d55 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneWeekNotifyCredBody.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/OneWeekNotifyCredBody.java @@ -26,20 +26,20 @@ import org.onap.aaf.auth.batch.helpers.ExpireRange; import org.onap.aaf.cadi.Access; public class OneWeekNotifyCredBody extends NotifyCredBody { - public OneWeekNotifyCredBody(Access access) throws IOException { - super(access, ExpireRange.ONE_WEEK); - } + public OneWeekNotifyCredBody(Access access) throws IOException { + super(access, ExpireRange.ONE_WEEK); + } - @Override - public String subject() { - return String.format("AAF Final Week Credential Notification (ENV: %s)",env); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() - */ - @Override - protected String dynamic() { - return "Failure for your App is <b><i>IMMINENT</i></b>. This email is escalated to your superior and General Manager. " + super.dynamic(); - } + @Override + public String subject() { + return String.format("AAF Final Week Credential Notification (ENV: %s)",env); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() + */ + @Override + protected String dynamic() { + return "Failure for your App is <b><i>IMMINENT</i></b>. This email is escalated to your superior and General Manager. " + super.dynamic(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoMonthNotifyCredBody.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoMonthNotifyCredBody.java index 98ee47d9..9d699cc3 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoMonthNotifyCredBody.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoMonthNotifyCredBody.java @@ -26,22 +26,22 @@ import org.onap.aaf.auth.batch.helpers.ExpireRange; import org.onap.aaf.cadi.Access; public class TwoMonthNotifyCredBody extends NotifyCredBody { - public TwoMonthNotifyCredBody(Access access) throws IOException { - super(access, ExpireRange.TWO_MONTH); - } - - @Override - public String subject() { - return String.format("AAF Two Month Credential Notification (ENV: %s)",env); - } + public TwoMonthNotifyCredBody(Access access) throws IOException { + super(access, ExpireRange.TWO_MONTH); + } + + @Override + public String subject() { + return String.format("AAF Two Month Credential Notification (ENV: %s)",env); + } - /* (non-Javadoc) - * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() - */ - @Override - protected String dynamic() { - return "This is a friendly, <b>2 month reminder</b> to schedule appropriate creation and deployment " - + "of your credentials, and modification of your configurations on a per instance basis. " - + " Use the following text to help create your Ticket."; - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() + */ + @Override + protected String dynamic() { + return "This is a friendly, <b>2 month reminder</b> to schedule appropriate creation and deployment " + + "of your credentials, and modification of your configurations on a per instance basis. " + + " Use the following text to help create your Ticket."; + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoWeeksNotifyCredBody.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoWeeksNotifyCredBody.java index 46188568..77062f38 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoWeeksNotifyCredBody.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/reports/bodies/TwoWeeksNotifyCredBody.java @@ -26,20 +26,20 @@ import org.onap.aaf.auth.batch.helpers.ExpireRange; import org.onap.aaf.cadi.Access; public class TwoWeeksNotifyCredBody extends NotifyCredBody { - public TwoWeeksNotifyCredBody(Access access) throws IOException { - super(access, ExpireRange.TWO_WEEK); - } + public TwoWeeksNotifyCredBody(Access access) throws IOException { + super(access, ExpireRange.TWO_WEEK); + } - @Override - public String subject() { - return String.format("AAF Two Week Credential Notification (ENV: %s)",env); - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() - */ - @Override - protected String dynamic() { - return "You have now reached critical stage. This email is escalated to your superiors. " + super.dynamic(); - } + @Override + public String subject() { + return String.format("AAF Two Week Credential Notification (ENV: %s)",env); + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.batch.reports.bodies.NotifyCredBody#dynamic() + */ + @Override + protected String dynamic() { + return "You have now reached critical stage. This email is escalated to your superiors. " + super.dynamic(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/temp/DataMigrateDublin.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/temp/DataMigrateDublin.java index 35970f50..e2d052ac 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/temp/DataMigrateDublin.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/temp/DataMigrateDublin.java @@ -50,11 +50,11 @@ import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Row; public class DataMigrateDublin extends Batch { - private final SecureRandom sr; - private final AuthzTrans noAvg; - - public DataMigrateDublin(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); + private final SecureRandom sr; + private final AuthzTrans noAvg; + + public DataMigrateDublin(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); trans.info().log("Starting Connection Process"); noAvg = env.newTransNoAvg(); @@ -62,152 +62,152 @@ public class DataMigrateDublin extends Batch { TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); try { - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cluster.connect(); - } finally { - tt.done(); - } + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cluster.connect(); + } finally { + tt.done(); + } } finally { tt0.done(); } sr = new SecureRandom(); - } + } - @Override - protected void run(AuthzTrans trans) { + @Override + protected void run(AuthzTrans trans) { /////////////////////////// trans.info().log("Add UniqueTag to Passwords"); CQLBatchLoop cbl = new CQLBatchLoop(new CQLBatch(noAvg.info(),session), 50, dryRun); try { - ResultSet rs = session.execute("SELECT id,type,expires,cred,tag FROM authz.cred"); - Iterator<Row> iter = rs.iterator(); - Row row; - int count = 0; - byte[] babytes = new byte[6]; - Map<String, List<CredInfo>> mlci = new TreeMap<>(); - Map<String, String> ba_tag = new TreeMap<>(); - while(iter.hasNext()) { - ++count; - row = iter.next(); - String tag = row.getString(4); - int type = row.getInt(1); - switch(type) { - case CredDAO.BASIC_AUTH: - case CredDAO.BASIC_AUTH_SHA256: - String key = row.getString(0) + '|' + type + '|' + Hash.toHex(row.getBytesUnsafe(3).array()); - String btag = ba_tag.get(key); - if(btag == null) { - if(tag==null || tag.isEmpty()) { - sr.nextBytes(babytes); - btag = Hash.toHexNo0x(babytes); - } else { - btag = tag; - } - ba_tag.put(key, btag); - } - - if(!btag.equals(tag)) { - update(cbl,row,btag); - } - break; - case CredDAO.CERT_SHA256_RSA: - if(tag==null || tag.isEmpty()) { - String id = row.getString(0); - List<CredInfo> ld = mlci.get(id); - if(ld==null) { - ld = new ArrayList<>(); - mlci.put(id,ld); - } - ld.add(new CredInfo(id,row.getInt(1),row.getTimestamp(2))); - } - break; - } - } - cbl.flush(); - trans.info().printf("Processes %d cred records, updated %d records in %d batches.", count, cbl.total(), cbl.batches()); - count = 0; - - cbl.reset(); - + ResultSet rs = session.execute("SELECT id,type,expires,cred,tag FROM authz.cred"); + Iterator<Row> iter = rs.iterator(); + Row row; + int count = 0; + byte[] babytes = new byte[6]; + Map<String, List<CredInfo>> mlci = new TreeMap<>(); + Map<String, String> ba_tag = new TreeMap<>(); + while(iter.hasNext()) { + ++count; + row = iter.next(); + String tag = row.getString(4); + int type = row.getInt(1); + switch(type) { + case CredDAO.BASIC_AUTH: + case CredDAO.BASIC_AUTH_SHA256: + String key = row.getString(0) + '|' + type + '|' + Hash.toHex(row.getBytesUnsafe(3).array()); + String btag = ba_tag.get(key); + if(btag == null) { + if(tag==null || tag.isEmpty()) { + sr.nextBytes(babytes); + btag = Hash.toHexNo0x(babytes); + } else { + btag = tag; + } + ba_tag.put(key, btag); + } + + if(!btag.equals(tag)) { + update(cbl,row,btag); + } + break; + case CredDAO.CERT_SHA256_RSA: + if(tag==null || tag.isEmpty()) { + String id = row.getString(0); + List<CredInfo> ld = mlci.get(id); + if(ld==null) { + ld = new ArrayList<>(); + mlci.put(id,ld); + } + ld.add(new CredInfo(id,row.getInt(1),row.getTimestamp(2))); + } + break; + } + } + cbl.flush(); + trans.info().printf("Processes %d cred records, updated %d records in %d batches.", count, cbl.total(), cbl.batches()); + count = 0; + + cbl.reset(); + trans.info().log("Add Serial to X509 Creds"); rs = session.execute("SELECT ca, id, x509 FROM authz.x509"); iter = rs.iterator(); - while(iter.hasNext()) { - ++count; - row = iter.next(); - String ca = row.getString(0); - String id = row.getString(1); - List<CredInfo> list = mlci.get(id); - if(list!=null) { - ByteBuffer bb = row.getBytesUnsafe(2); - if(bb!=null) { - Collection<? extends Certificate> x509s = Factory.toX509Certificate(bb.array()); - for(Certificate c : x509s) { - X509Certificate xc = (X509Certificate)c; - for(CredInfo ci : list) { - if(xc.getNotAfter().equals(ci.expires)) { - ci.update(cbl, ca + '|' + xc.getSerialNumber()); - break; - } - } - } - } - } - } - cbl.flush(); - trans.info().printf("Processed %d x509 records, updated %d records in %d batches.", count, cbl.total(), cbl.batches()); - count = 0; + while(iter.hasNext()) { + ++count; + row = iter.next(); + String ca = row.getString(0); + String id = row.getString(1); + List<CredInfo> list = mlci.get(id); + if(list!=null) { + ByteBuffer bb = row.getBytesUnsafe(2); + if(bb!=null) { + Collection<? extends Certificate> x509s = Factory.toX509Certificate(bb.array()); + for(Certificate c : x509s) { + X509Certificate xc = (X509Certificate)c; + for(CredInfo ci : list) { + if(xc.getNotAfter().equals(ci.expires)) { + ci.update(cbl, ca + '|' + xc.getSerialNumber()); + break; + } + } + } + } + } + } + cbl.flush(); + trans.info().printf("Processed %d x509 records, updated %d records in %d batches.", count, cbl.total(), cbl.batches()); + count = 0; } catch (Exception e) { - trans.error().log(e); + trans.error().log(e); } - } - - private static class CredInfo { - public final String id; - public final int type; - public final Date expires; - - public CredInfo(String id, int type, Date expires) { - this.id = id; - this.type = type; - this.expires = expires; - } - - public void update(CQLBatchLoop cbl, String newtag) { - StringBuilder sb = cbl.inc(); - sb.append("UPDATE authz.cred SET tag='"); - sb.append(newtag); - sb.append("' WHERE id='"); - sb.append(id); - sb.append("' AND type="); - sb.append(type); - sb.append(" AND expires=dateof(maxtimeuuid("); - sb.append(expires.getTime()); - sb.append("));"); - } - } - - private void update(CQLBatchLoop cbl, Row row, String newtag) { - StringBuilder sb = cbl.inc(); - sb.append("UPDATE authz.cred SET tag='"); - sb.append(newtag); - sb.append("' WHERE id='"); - sb.append(row.getString(0)); - sb.append("' AND type="); - sb.append(row.getInt(1)); - sb.append(" AND expires=dateof(maxtimeuuid("); - Date lc = row.getTimestamp(2); - sb.append(lc.getTime()); - sb.append("));"); - } + } + + private static class CredInfo { + public final String id; + public final int type; + public final Date expires; + + public CredInfo(String id, int type, Date expires) { + this.id = id; + this.type = type; + this.expires = expires; + } + + public void update(CQLBatchLoop cbl, String newtag) { + StringBuilder sb = cbl.inc(); + sb.append("UPDATE authz.cred SET tag='"); + sb.append(newtag); + sb.append("' WHERE id='"); + sb.append(id); + sb.append("' AND type="); + sb.append(type); + sb.append(" AND expires=dateof(maxtimeuuid("); + sb.append(expires.getTime()); + sb.append("));"); + } + } + + private void update(CQLBatchLoop cbl, Row row, String newtag) { + StringBuilder sb = cbl.inc(); + sb.append("UPDATE authz.cred SET tag='"); + sb.append(newtag); + sb.append("' WHERE id='"); + sb.append(row.getString(0)); + sb.append("' AND type="); + sb.append(row.getInt(1)); + sb.append(" AND expires=dateof(maxtimeuuid("); + Date lc = row.getTimestamp(2); + sb.append(lc.getTime()); + sb.append("));"); + } - @Override - protected void _close(AuthzTrans trans) { + @Override + protected void _close(AuthzTrans trans) { trans.info().log("End " + this.getClass().getSimpleName() + " processing" ); session.close(); - } + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Approvals.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Approvals.java index 57def168..43e234b2 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Approvals.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Approvals.java @@ -55,19 +55,19 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.env.util.Chrono; public class Approvals extends Batch { - private final AuthzTrans noAvg; - private BatchDataView dataview; - private List<CSV> csvList; - private Writer napproveCW; - private final GregorianCalendar now; - private final String sdate; - private static final String CSV = ".csv"; - private static final String APPROVALS_NEW = "ApprovalsNew"; - + private final AuthzTrans noAvg; + private BatchDataView dataview; + private List<CSV> csvList; + private Writer napproveCW; + private final GregorianCalendar now; + private final String sdate; + private static final String CSV = ".csv"; + private static final String APPROVALS_NEW = "ApprovalsNew"; + public Approvals(AuthzTrans trans) throws APIException, IOException, OrganizationException { super(trans.env()); - now = new GregorianCalendar(); - sdate = Chrono.dateOnlyStamp(now); + now = new GregorianCalendar(); + sdate = Chrono.dateOnlyStamp(now); noAvg = env.newTransNoAvg(); noAvg.setUser(new BatchPrincipal("batch:Approvals")); session = cluster.connect(); @@ -79,21 +79,21 @@ public class Approvals extends Batch { csvList = new ArrayList<>(); File f; if(args().length>0) { - for(int i=0;i<args().length;++i) { - f = new File(logDir(), args()[i]); - if(f.exists()) { - csvList.add(new CSV(env.access(),f).processAll()); - } else { - trans.error().printf("CSV File %s does not exist",f.getAbsolutePath()); - } - } + for(int i=0;i<args().length;++i) { + f = new File(logDir(), args()[i]); + if(f.exists()) { + csvList.add(new CSV(env.access(),f).processAll()); + } else { + trans.error().printf("CSV File %s does not exist",f.getAbsolutePath()); + } + } } else { - f = new File(logDir(), Analyze.NEED_APPROVALS+Chrono.dateOnlyStamp()+".csv"); - if(f.exists()) { - csvList.add(new CSV(env.access(),f).processAll()); - } else { - trans.error().printf("CSV File %s does not exist",f.getAbsolutePath()); - } + f = new File(logDir(), Analyze.NEED_APPROVALS+Chrono.dateOnlyStamp()+".csv"); + if(f.exists()) { + csvList.add(new CSV(env.access(),f).processAll()); + } else { + trans.error().printf("CSV File %s does not exist",f.getAbsolutePath()); + } } @@ -106,71 +106,71 @@ public class Approvals extends Batch { @Override protected void run(AuthzTrans trans) { - Map<String,Pending> mpending = new TreeMap<>(); - Pending p = Pending.create(); + Map<String,Pending> mpending = new TreeMap<>(); + Pending p = Pending.create(); - Holder<Integer> count = new Holder<>(0); + Holder<Integer> count = new Holder<>(0); for(CSV neeedApproveCSV : csvList) { - TimeTaken tt = trans.start("Processing %s's UserRoles",Trans.SUB,neeedApproveCSV.name()); - try { - neeedApproveCSV.visit(row -> { - switch(row.get(0)) { - case UserRole.APPROVE_UR: - UserRoleDAO.Data urdd = UserRole.row(row); - // Create an Approval - ApprovalSet uras = new URApprovalSet(noAvg, now, dataview, () -> { - return urdd; - }); - Result<Void> rw = uras.write(noAvg); - if(rw.isOK()) { - Set<String> approvers = uras.approvers(); - if(approvers.isEmpty()) { - trans.error().printf("No Approvers found for %s-%s (probably no owner)",urdd.user,urdd.role); - } else { - for(String approver : approvers) { - Pending mp = mpending.get(approver); - if(mp==null) { - mpending.put(approver, Pending.create()); - } else { - mp.inc(p); // FYI, unlikely - } - } - count.set(count.get()+1); - } - } else { - trans.error().log(rw.errorString()); - } - break; - } - }); - dataview.flush(); - } catch (IOException | CadiException e) { - e.printStackTrace(); - // .... but continue with next row - } finally { - tt.done(); - } + TimeTaken tt = trans.start("Processing %s's UserRoles",Trans.SUB,neeedApproveCSV.name()); + try { + neeedApproveCSV.visit(row -> { + switch(row.get(0)) { + case UserRole.APPROVE_UR: + UserRoleDAO.Data urdd = UserRole.row(row); + // Create an Approval + ApprovalSet uras = new URApprovalSet(noAvg, now, dataview, () -> { + return urdd; + }); + Result<Void> rw = uras.write(noAvg); + if(rw.isOK()) { + Set<String> approvers = uras.approvers(); + if(approvers.isEmpty()) { + trans.error().printf("No Approvers found for %s-%s (probably no owner)",urdd.user,urdd.role); + } else { + for(String approver : approvers) { + Pending mp = mpending.get(approver); + if(mp==null) { + mpending.put(approver, Pending.create()); + } else { + mp.inc(p); // FYI, unlikely + } + } + count.set(count.get()+1); + } + } else { + trans.error().log(rw.errorString()); + } + break; + } + }); + dataview.flush(); + } catch (IOException | CadiException e) { + e.printStackTrace(); + // .... but continue with next row + } finally { + tt.done(); + } trans.info().printf("Processed %d UserRoles", count.get()); - tt = trans.start("Writing Approvals to %s",Trans.SUB,neeedApproveCSV.name()); - int cnt = 0; - try { - for(Entry<String, Pending> es : mpending.entrySet()) { - p.row(napproveCW,es.getKey()); - ++cnt; - } + tt = trans.start("Writing Approvals to %s",Trans.SUB,neeedApproveCSV.name()); + int cnt = 0; + try { + for(Entry<String, Pending> es : mpending.entrySet()) { + p.row(napproveCW,es.getKey()); + ++cnt; + } } finally { - tt.done(); - trans.info().printf("Processed %d Reminders", cnt); + tt.done(); + trans.info().printf("Processed %d Reminders", cnt); } - } + } } - @Override + @Override protected void _close(AuthzTrans trans) { - if(napproveCW!=null) { - napproveCW.flush(); - napproveCW.close(); - } + if(napproveCW!=null) { + napproveCW.flush(); + napproveCW.close(); + } } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Extend.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Extend.java index 3a0f7b9e..98a01d76 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Extend.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Extend.java @@ -49,15 +49,15 @@ import org.onap.aaf.misc.env.TimeTaken; import org.onap.aaf.misc.env.util.Chrono; public class Extend extends Batch { - private final CQLBatch cqlBatch; - private final CredDAO credDAO; - private final AuthzTrans noAvg; - private List<File> extFiles; - private final int extendBy; - private int gcType; - - public Extend(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); + private final CQLBatch cqlBatch; + private final CredDAO credDAO; + private final AuthzTrans noAvg; + private List<File> extFiles; + private final int extendBy; + private int gcType; + + public Extend(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); trans.info().log("Starting Connection Process"); noAvg = env.newTransNoAvg(); @@ -65,13 +65,13 @@ public class Extend extends Batch { TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); try { - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - credDAO = new CredDAO(trans, cluster, CassAccess.KEYSPACE); - try { - session = credDAO.getSession(trans); - } finally { - tt.done(); - } + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + credDAO = new CredDAO(trans, cluster, CassAccess.KEYSPACE); + try { + session = credDAO.getSession(trans); + } finally { + tt.done(); + } cqlBatch = new CQLBatch(noAvg.info(),session); } finally { tt0.done(); @@ -79,133 +79,133 @@ public class Extend extends Batch { gcType = GregorianCalendar.WEEK_OF_YEAR; int weeks = 4; - + Set<String> cmd = new HashSet<>(); - for(int i=0; i< args().length;++i) { - if("-weeks".equals(args()[i])) { - if(args().length>i+1) { - weeks = Integer.parseInt(args()[++i]); - } - } else { - cmd.add(args()[i]); - } - } - - if(weeks<1 || weeks > 24) { - throw new APIException("Invalid --weeks"); - } - extendBy = weeks; + for(int i=0; i< args().length;++i) { + if("-weeks".equals(args()[i])) { + if(args().length>i+1) { + weeks = Integer.parseInt(args()[++i]); + } + } else { + cmd.add(args()[i]); + } + } + + if(weeks<1 || weeks > 24) { + throw new APIException("Invalid --weeks"); + } + extendBy = weeks; // Create Intermediate Output File logDir = logDir(); extFiles = new ArrayList<>(); if(cmd.isEmpty()) { - extFiles.add(new File(logDir,PrepExtend.PREP_EXTEND+Chrono.dateOnlyStamp()+".csv")); + extFiles.add(new File(logDir,PrepExtend.PREP_EXTEND+Chrono.dateOnlyStamp()+".csv")); } else { - for(String fn : cmd) { - extFiles.add(new File(logDir, fn)); - } + for(String fn : cmd) { + extFiles.add(new File(logDir, fn)); + } } // Load Cred. We don't follow Visitor, because we have to gather up everything into Identity Anyway // to find the last one. - } + } - @Override - protected void run(AuthzTrans trans) { + @Override + protected void run(AuthzTrans trans) { final int maxBatch = 50; - // Setup Date boundaries + // Setup Date boundaries final Holder<GregorianCalendar> hgc = new Holder<>(new GregorianCalendar()); final GregorianCalendar now = new GregorianCalendar(); /////////////////////////// trans.info().log("Bulk Extend Expiring User-Roles and Creds"); - final Holder<List<String>> info = new Holder<>(null); - final Holder<StringBuilder> hsb = new Holder<>(null); + final Holder<List<String>> info = new Holder<>(null); + final Holder<StringBuilder> hsb = new Holder<>(null); - for(File f : extFiles) { - CSV csv = new CSV(env.access(),f); - try { - csv.visit(new CSV.Visitor() { - final Holder<Integer> hi = new Holder<>(0); + for(File f : extFiles) { + CSV csv = new CSV(env.access(),f); + try { + csv.visit(new CSV.Visitor() { + final Holder<Integer> hi = new Holder<>(0); - @Override - public void visit(List<String> row) throws IOException, CadiException { - GregorianCalendar gc; - int i = hi.get(); - StringBuilder sb = hsb.get(); - if(sb==null) { - hsb.set(sb=cqlBatch.begin()); - } - switch(row.get(0)) { - case "info": - info.set(row); - break; - case "ur": - hi.set(++i); - gc = hgc.get(); - gc.setTime(new Date(Long.parseLong(row.get(6)))); - if(gc.before(now)) { - gc.setTime(now.getTime()); - } - gc.add(gcType, extendBy); - UserRole.batchExtend(sb,row,gc.getTime()); - break; - case "cred": - int ctype = Integer.parseInt(row.get(3)); - if(ctype == CredDAO.BASIC_AUTH_SHA256 || ctype == CredDAO.BASIC_AUTH) { - Result<List<Data>> result = credDAO.readID(noAvg, row.get(1)); - if(result.isOKhasData()) { - for(CredDAO.Data cd : result.value) { - if(cd.type == CredDAO.BASIC_AUTH_SHA256 || cd.type == CredDAO.BASIC_AUTH) { - String prev; - if(row.get(4).equals(prev=Chrono.dateOnlyStamp(cd.expires))) { - gc = hgc.get(); - gc.setTime(new Date(Long.parseLong(row.get(5)))); - if(gc.before(now)) { - gc.setTime(now.getTime()); - } - gc.add(gcType, extendBy); - cd.expires = gc.getTime(); - if(dryRun) { - noAvg.info().printf("Would extend %s, %d - %s to %s",cd.id,cd.type,prev, Chrono.dateOnlyStamp(cd.expires)); - } else { - Result<Void> r = credDAO.update(noAvg, cd, true); - noAvg.info().printf("%s %s, %d - %s to %s", - r.isOK()?"Extended":"Failed to Extend", - cd.id,cd.type,prev, Chrono.dateOnlyStamp(cd.expires)); - } - } - } - } - } - } - break; - } - if(i%maxBatch==0 && sb!=null) { - cqlBatch.execute(dryRun); - hi.set(1); - hsb.set(sb=null); - } - } - }); - } catch (IOException | CadiException e) { - e.printStackTrace(); - } - } - - // Cleanup, if required. - cqlBatch.execute(dryRun); + @Override + public void visit(List<String> row) throws IOException, CadiException { + GregorianCalendar gc; + int i = hi.get(); + StringBuilder sb = hsb.get(); + if(sb==null) { + hsb.set(sb=cqlBatch.begin()); + } + switch(row.get(0)) { + case "info": + info.set(row); + break; + case "ur": + hi.set(++i); + gc = hgc.get(); + gc.setTime(new Date(Long.parseLong(row.get(6)))); + if(gc.before(now)) { + gc.setTime(now.getTime()); + } + gc.add(gcType, extendBy); + UserRole.batchExtend(sb,row,gc.getTime()); + break; + case "cred": + int ctype = Integer.parseInt(row.get(3)); + if(ctype == CredDAO.BASIC_AUTH_SHA256 || ctype == CredDAO.BASIC_AUTH) { + Result<List<Data>> result = credDAO.readID(noAvg, row.get(1)); + if(result.isOKhasData()) { + for(CredDAO.Data cd : result.value) { + if(cd.type == CredDAO.BASIC_AUTH_SHA256 || cd.type == CredDAO.BASIC_AUTH) { + String prev; + if(row.get(4).equals(prev=Chrono.dateOnlyStamp(cd.expires))) { + gc = hgc.get(); + gc.setTime(new Date(Long.parseLong(row.get(5)))); + if(gc.before(now)) { + gc.setTime(now.getTime()); + } + gc.add(gcType, extendBy); + cd.expires = gc.getTime(); + if(dryRun) { + noAvg.info().printf("Would extend %s, %d - %s to %s",cd.id,cd.type,prev, Chrono.dateOnlyStamp(cd.expires)); + } else { + Result<Void> r = credDAO.update(noAvg, cd, true); + noAvg.info().printf("%s %s, %d - %s to %s", + r.isOK()?"Extended":"Failed to Extend", + cd.id,cd.type,prev, Chrono.dateOnlyStamp(cd.expires)); + } + } + } + } + } + } + break; + } + if(i%maxBatch==0 && sb!=null) { + cqlBatch.execute(dryRun); + hi.set(1); + hsb.set(sb=null); + } + } + }); + } catch (IOException | CadiException e) { + e.printStackTrace(); + } + } + + // Cleanup, if required. + cqlBatch.execute(dryRun); - } - - @Override - protected void _close(AuthzTrans trans) { + } + + @Override + protected void _close(AuthzTrans trans) { trans.info().log("End " + this.getClass().getSimpleName() + " processing" ); credDAO.close(trans); session.close(); - } + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java index b6b16fe3..89fbfacc 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Remove.java @@ -56,159 +56,159 @@ import org.onap.aaf.misc.env.Trans; import org.onap.aaf.misc.env.util.Chrono; public class Remove extends Batch { - private final AuthzTrans noAvg; - private HistoryDAO historyDAO; - private CQLBatch cqlBatch; - - public Remove(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); - - noAvg = env.newTransNoAvg(); - noAvg.setUser(new BatchPrincipal("Remove")); - - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - historyDAO = new HistoryDAO(trans, cluster, CassAccess.KEYSPACE); - TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = historyDAO.getSession(trans); - } finally { - tt2.done(); - } - cqlBatch = new CQLBatch(noAvg.info(),session); - - - } finally { - tt0.done(); - } - } - - @Override - protected void run(AuthzTrans trans) { - - // Create Intermediate Output - File logDir = logDir(); - - List<File> remove = new ArrayList<>(); - if(args().length>0) { - for(int i=0;i<args().length;++i) { - remove.add(new File(logDir, args()[i])); - } - } else { - remove.add(new File(logDir,"Delete"+Chrono.dateOnlyStamp()+".csv")); - } - - for(File f : remove) { - trans.init().log("Processing File:",f.getAbsolutePath()); - } - - final Holder<Boolean> ur = new Holder<>(false); - final Holder<Boolean> cred = new Holder<>(false); - final Holder<Boolean> x509 = new Holder<>(false); - final Holder<String> memoFmt = new Holder<String>(""); - final HistoryDAO.Data hdd = new HistoryDAO.Data(); - final String orgName = trans.org().getName(); - - hdd.action="delete"; - hdd.reconstruct = ByteBuffer.allocate(0); - hdd.user = noAvg.user(); - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); - hdd.yr_mon = Integer.parseInt(sdf.format(new Date())); - - try { - final CQLBatchLoop cbl = new CQLBatchLoop(cqlBatch,50,dryRun); - for(File f : remove) { - trans.info().log("Processing ",f.getAbsolutePath(),"for Deletions"); - if(f.exists()) { - CSV removeCSV = new CSV(env.access(),f); - try { - removeCSV.visit( row -> { - switch(row.get(0)) { - case "info": - switch(row.get(1)) { - case "Delete": - memoFmt.set("%s expired from %s on %s"); - break; - case "NotInOrgDelete": - memoFmt.set("Identity %s was removed from %s on %s"); - break; - } - break; - case "ur": - if(!ur.get()) { - ur.set(true); - } - //TODO If deleted because Role is no longer there, double check... - - UserRole.batchDelete(cbl.inc(),row); - hdd.target=UserRoleDAO.TABLE; - hdd.subject=UserRole.histSubject(row); - hdd.memo=UserRole.histMemo(memoFmt.get(), row); - historyDAO.createBatch(cbl.inc(), hdd); - break; - case "cred": - if(!cred.get()) { - cred.set(true); - } - Cred.batchDelete(cbl.inc(),row); - hdd.target=CredDAO.TABLE; - hdd.subject=Cred.histSubject(row); - hdd.memo=Cred.histMemo(memoFmt.get(), orgName,row); - historyDAO.createBatch(cbl.inc(), hdd); - break; - case "x509": - if(!x509.get()) { - x509.set(true); - } - X509.batchDelete(cbl.inc(),row); - hdd.target="x509"; - hdd.subject=X509.histSubject(row); - hdd.memo=X509.histMemo(memoFmt.get(),row); - historyDAO.createBatch(cbl.inc(), hdd); - break; - case "future": - // Not cached - Future.deleteByIDBatch(cbl.inc(),row.get(1)); - break; - case "approval": - // Not cached - Approval.deleteByIDBatch(cbl.inc(),row.get(1)); - break; - case "notified": - LastNotified.delete(cbl.inc(),row); - break; - } - }); - cbl.flush(); - } catch (IOException | CadiException e) { - e.printStackTrace(); - } - } else { - trans.error().log("File",f.getAbsolutePath(),"does not exist."); - } - } - } finally { - TimeTaken tt = trans.start("Touch UR,Cred and Cert Caches",Trans.REMOTE); - try { - if(ur.get()) { - cqlBatch.touch(UserRoleDAO.TABLE, 0, UserRoleDAO.CACHE_SEG, dryRun); - } - if(cred.get()) { - cqlBatch.touch(CredDAO.TABLE, 0, CredDAO.CACHE_SEG, dryRun); - } - if(x509.get()) { - cqlBatch.touch(CertDAO.TABLE, 0, CertDAO.CACHE_SEG, dryRun); - } - } finally { - tt.done(); - } - } - } - - @Override - protected void _close(AuthzTrans trans) { - session.close(); - } + private final AuthzTrans noAvg; + private HistoryDAO historyDAO; + private CQLBatch cqlBatch; + + public Remove(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); + + noAvg = env.newTransNoAvg(); + noAvg.setUser(new BatchPrincipal("Remove")); + + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + historyDAO = new HistoryDAO(trans, cluster, CassAccess.KEYSPACE); + TimeTaken tt2 = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = historyDAO.getSession(trans); + } finally { + tt2.done(); + } + cqlBatch = new CQLBatch(noAvg.info(),session); + + + } finally { + tt0.done(); + } + } + + @Override + protected void run(AuthzTrans trans) { + + // Create Intermediate Output + File logDir = logDir(); + + List<File> remove = new ArrayList<>(); + if(args().length>0) { + for(int i=0;i<args().length;++i) { + remove.add(new File(logDir, args()[i])); + } + } else { + remove.add(new File(logDir,"Delete"+Chrono.dateOnlyStamp()+".csv")); + } + + for(File f : remove) { + trans.init().log("Processing File:",f.getAbsolutePath()); + } + + final Holder<Boolean> ur = new Holder<>(false); + final Holder<Boolean> cred = new Holder<>(false); + final Holder<Boolean> x509 = new Holder<>(false); + final Holder<String> memoFmt = new Holder<String>(""); + final HistoryDAO.Data hdd = new HistoryDAO.Data(); + final String orgName = trans.org().getName(); + + hdd.action="delete"; + hdd.reconstruct = ByteBuffer.allocate(0); + hdd.user = noAvg.user(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM"); + hdd.yr_mon = Integer.parseInt(sdf.format(new Date())); + + try { + final CQLBatchLoop cbl = new CQLBatchLoop(cqlBatch,50,dryRun); + for(File f : remove) { + trans.info().log("Processing ",f.getAbsolutePath(),"for Deletions"); + if(f.exists()) { + CSV removeCSV = new CSV(env.access(),f); + try { + removeCSV.visit( row -> { + switch(row.get(0)) { + case "info": + switch(row.get(1)) { + case "Delete": + memoFmt.set("%s expired from %s on %s"); + break; + case "NotInOrgDelete": + memoFmt.set("Identity %s was removed from %s on %s"); + break; + } + break; + case "ur": + if(!ur.get()) { + ur.set(true); + } + //TODO If deleted because Role is no longer there, double check... + + UserRole.batchDelete(cbl.inc(),row); + hdd.target=UserRoleDAO.TABLE; + hdd.subject=UserRole.histSubject(row); + hdd.memo=UserRole.histMemo(memoFmt.get(), row); + historyDAO.createBatch(cbl.inc(), hdd); + break; + case "cred": + if(!cred.get()) { + cred.set(true); + } + Cred.batchDelete(cbl.inc(),row); + hdd.target=CredDAO.TABLE; + hdd.subject=Cred.histSubject(row); + hdd.memo=Cred.histMemo(memoFmt.get(), orgName,row); + historyDAO.createBatch(cbl.inc(), hdd); + break; + case "x509": + if(!x509.get()) { + x509.set(true); + } + X509.batchDelete(cbl.inc(),row); + hdd.target="x509"; + hdd.subject=X509.histSubject(row); + hdd.memo=X509.histMemo(memoFmt.get(),row); + historyDAO.createBatch(cbl.inc(), hdd); + break; + case "future": + // Not cached + Future.deleteByIDBatch(cbl.inc(),row.get(1)); + break; + case "approval": + // Not cached + Approval.deleteByIDBatch(cbl.inc(),row.get(1)); + break; + case "notified": + LastNotified.delete(cbl.inc(),row); + break; + } + }); + cbl.flush(); + } catch (IOException | CadiException e) { + e.printStackTrace(); + } + } else { + trans.error().log("File",f.getAbsolutePath(),"does not exist."); + } + } + } finally { + TimeTaken tt = trans.start("Touch UR,Cred and Cert Caches",Trans.REMOTE); + try { + if(ur.get()) { + cqlBatch.touch(UserRoleDAO.TABLE, 0, UserRoleDAO.CACHE_SEG, dryRun); + } + if(cred.get()) { + cqlBatch.touch(CredDAO.TABLE, 0, CredDAO.CACHE_SEG, dryRun); + } + if(x509.get()) { + cqlBatch.touch(CertDAO.TABLE, 0, CertDAO.CACHE_SEG, dryRun); + } + } finally { + tt.done(); + } + } + } + + @Override + protected void _close(AuthzTrans trans) { + session.close(); + } } diff --git a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java index 537cd932..e2580ae8 100644 --- a/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java +++ b/auth/auth-batch/src/main/java/org/onap/aaf/auth/batch/update/Upload.java @@ -43,180 +43,180 @@ import org.onap.aaf.misc.env.util.Split; public class Upload extends Batch { - private static final String DAT = ".dat"; + private static final String DAT = ".dat"; - private CQLBatch cqlBatch; + private CQLBatch cqlBatch; - private Map<String,Feed> feeds; + private Map<String,Feed> feeds; - public Upload(AuthzTrans trans) throws APIException, IOException, OrganizationException { - super(trans.env()); - trans.info().log("Starting Connection Process"); - - TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); - try { - TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); - try { - session = cluster.connect(); - } finally { - tt.done(); - } - - cqlBatch = new CQLBatch(LogTarget.NULL,session); - - feeds=new HashMap<>(); - new Feed(feeds,"ns",1,"name,description,parent,scope=int,type=int",300); - new Feed(feeds,"notified",3,"user,target,key,last",300); - new Feed(feeds,"approval",1,"id=UUID,approver,last_notified,memo,operation,status,ticket=UUID,type,user",200); - new Feed(feeds,"artifact",2,"mechid,machine,ca,dir,expires,notify,ns,os_user,renewdays=int,sans=set,sponsor,type=set",200); - new Feed(feeds,"cred",1,"id,type=int,expires,cred=blob,notes,ns,other=int,prev=blob,tag",200); - new Feed(feeds,"x509",2,"ca,serial=blob,id,x500,x509=C/R",200); - new Feed(feeds,"role",2,"ns,name,description,perms=set",200); - new Feed(feeds,"perm",4,"ns,type,instance,action,description,roles=set",200); - new Feed(feeds,"history",1,"id=UUID,action,memo,reconstruct=blob,subject,target,user,yr_mon=int",300); + public Upload(AuthzTrans trans) throws APIException, IOException, OrganizationException { + super(trans.env()); + trans.info().log("Starting Connection Process"); + + TimeTaken tt0 = trans.start("Cassandra Initialization", Env.SUB); + try { + TimeTaken tt = trans.start("Connect to Cluster", Env.REMOTE); + try { + session = cluster.connect(); + } finally { + tt.done(); + } + + cqlBatch = new CQLBatch(LogTarget.NULL,session); + + feeds=new HashMap<>(); + new Feed(feeds,"ns",1,"name,description,parent,scope=int,type=int",300); + new Feed(feeds,"notified",3,"user,target,key,last",300); + new Feed(feeds,"approval",1,"id=UUID,approver,last_notified,memo,operation,status,ticket=UUID,type,user",200); + new Feed(feeds,"artifact",2,"mechid,machine,ca,dir,expires,notify,ns,os_user,renewdays=int,sans=set,sponsor,type=set",200); + new Feed(feeds,"cred",1,"id,type=int,expires,cred=blob,notes,ns,other=int,prev=blob,tag",200); + new Feed(feeds,"x509",2,"ca,serial=blob,id,x500,x509=C/R",200); + new Feed(feeds,"role",2,"ns,name,description,perms=set",200); + new Feed(feeds,"perm",4,"ns,type,instance,action,description,roles=set",200); + new Feed(feeds,"history",1,"id=UUID,action,memo,reconstruct=blob,subject,target,user,yr_mon=int",300); - } finally { - tt0.done(); - } - } + } finally { + tt0.done(); + } + } - @Override - protected void run(AuthzTrans trans) { - List<File> files = new ArrayList<>(); - if(args().length>0) { - File dir = new File(args()[0]); - if(dir.isDirectory()) { - for(File f : dir.listFiles(pathname -> { - return pathname.getName().endsWith(DAT); - })) { - files.add(f); - } - } else { - File f; - for(String arg : args()) { - if(arg.endsWith(DAT)) { - f=new File(arg); - } else { - f=new File(arg+DAT); - } - files.add(f); - } - } - } - for(File file : files) { - String f = file.getName(); - final Feed feed = feeds.get(f.substring(0,f.length()-4)); - if(feed!=null) { - TimeTaken tt = trans.start(file.getAbsolutePath(), Env.SUB); - String msg = String.format("#### Running %s.dat Feed ####",feed.getName()); - trans.info().log(msg); - System.out.println(msg); - CQLBatchLoop cbl = new CQLBatchLoop(cqlBatch,feed.batchSize,dryRun).showProgress(); - - try { - if(file.exists()) { - CSV csv = new CSV(trans.env().access(),file).setDelimiter('|'); - csv.visit( row -> { - feed.insert(cbl.inc(),row); - }); - } - cbl.flush(); - } catch (Throwable e) { - e.printStackTrace(); - } finally { - tt.done(); - System.err.flush(); - msg = String.format("\n%d applied in %d batches\n",cbl.total(), cbl.batches()); - trans.info().log(msg); - System.out.println(msg); - } - } - } - } - - @Override - protected void _close(AuthzTrans trans) { + @Override + protected void run(AuthzTrans trans) { + List<File> files = new ArrayList<>(); + if(args().length>0) { + File dir = new File(args()[0]); + if(dir.isDirectory()) { + for(File f : dir.listFiles(pathname -> { + return pathname.getName().endsWith(DAT); + })) { + files.add(f); + } + } else { + File f; + for(String arg : args()) { + if(arg.endsWith(DAT)) { + f=new File(arg); + } else { + f=new File(arg+DAT); + } + files.add(f); + } + } + } + for(File file : files) { + String f = file.getName(); + final Feed feed = feeds.get(f.substring(0,f.length()-4)); + if(feed!=null) { + TimeTaken tt = trans.start(file.getAbsolutePath(), Env.SUB); + String msg = String.format("#### Running %s.dat Feed ####",feed.getName()); + trans.info().log(msg); + System.out.println(msg); + CQLBatchLoop cbl = new CQLBatchLoop(cqlBatch,feed.batchSize,dryRun).showProgress(); + + try { + if(file.exists()) { + CSV csv = new CSV(trans.env().access(),file).setDelimiter('|'); + csv.visit( row -> { + feed.insert(cbl.inc(),row); + }); + } + cbl.flush(); + } catch (Throwable e) { + e.printStackTrace(); + } finally { + tt.done(); + System.err.flush(); + msg = String.format("\n%d applied in %d batches\n",cbl.total(), cbl.batches()); + trans.info().log(msg); + System.out.println(msg); + } + } + } + } + + @Override + protected void _close(AuthzTrans trans) { session.close(); - } + } - private class Feed { - private final String name; - private final String[] flds; - private final String[] types; - private final int key; - private final int batchSize; - public Feed(Map<String, Feed> feeds, String feed, int keyLength, String fields,int batchSize) { - name=feed; - key = keyLength; - flds = Split.splitTrim(',', fields); - types = new String[flds.length]; - this.batchSize = batchSize; - int equals; - for(int i=0;i<flds.length;++i) { - if((equals = flds[i].indexOf('='))>0) { - types[i]=flds[i].substring(equals+1); - flds[i]=flds[i].substring(0, equals); - } - } - feeds.put(feed,this); - } - - public String getName() { - return name; - } + private class Feed { + private final String name; + private final String[] flds; + private final String[] types; + private final int key; + private final int batchSize; + public Feed(Map<String, Feed> feeds, String feed, int keyLength, String fields,int batchSize) { + name=feed; + key = keyLength; + flds = Split.splitTrim(',', fields); + types = new String[flds.length]; + this.batchSize = batchSize; + int equals; + for(int i=0;i<flds.length;++i) { + if((equals = flds[i].indexOf('='))>0) { + types[i]=flds[i].substring(equals+1); + flds[i]=flds[i].substring(0, equals); + } + } + feeds.put(feed,this); + } + + public String getName() { + return name; + } - public void insert(StringBuilder sb,List<String> row) { - sb.append("INSERT INTO authz."); - sb.append(name); - sb.append(" ("); - boolean first = true; - StringBuilder values = new StringBuilder(") VALUES ("); - String value; - String type; - for(int idx=0;idx<row.size();++idx) { - value = row.get(idx).trim(); - if(idx<key || !(value.isEmpty() || "null".equals(value))) { - if(first) { - first = false; - } else { - sb.append(','); - values.append(','); - } - sb.append(flds[idx]); - type=types[idx]; - if(type==null) { // String is default. - switch(value) { - case "": - if(idx<key) { - // Key value has to be something, but can't be actual null - values.append("''"); - } else { - values.append("null"); - } - break; - default: - values.append('\''); - values.append(value.replaceAll("'","''")); - values.append('\''); - } - } else switch(type) { - case "C/R": - values.append('\''); - values.append(value.replaceAll("\\\\n", "\n")); - values.append('\''); - break; - default: - values.append(value); - break; - - } - } - } - sb.append(values); - sb.append(");\n"); - } - } + public void insert(StringBuilder sb,List<String> row) { + sb.append("INSERT INTO authz."); + sb.append(name); + sb.append(" ("); + boolean first = true; + StringBuilder values = new StringBuilder(") VALUES ("); + String value; + String type; + for(int idx=0;idx<row.size();++idx) { + value = row.get(idx).trim(); + if(idx<key || !(value.isEmpty() || "null".equals(value))) { + if(first) { + first = false; + } else { + sb.append(','); + values.append(','); + } + sb.append(flds[idx]); + type=types[idx]; + if(type==null) { // String is default. + switch(value) { + case "": + if(idx<key) { + // Key value has to be something, but can't be actual null + values.append("''"); + } else { + values.append("null"); + } + break; + default: + values.append('\''); + values.append(value.replaceAll("'","''")); + values.append('\''); + } + } else switch(type) { + case "C/R": + values.append('\''); + values.append(value.replaceAll("\\\\n", "\n")); + values.append('\''); + break; + default: + values.append(value); + break; + + } + } + } + sb.append(values); + sb.append(");\n"); + } + } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/approvalsets/JU_ApprovalSetTest.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/approvalsets/JU_ApprovalSetTest.java index fe7bd6c5..10f7a2be 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/approvalsets/JU_ApprovalSetTest.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/approvalsets/JU_ApprovalSetTest.java @@ -56,95 +56,95 @@ import com.datastax.driver.core.Session; public class JU_ApprovalSetTest { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - PropAccess access; - - @Mock - ApprovalSet actionObj; + @Mock + Cluster cluster; + @Mock + PropAccess access; + + @Mock + ApprovalSet actionObj; - @Mock - DataView dv; + @Mock + DataView dv; @Before public void setUp() throws APIException, IOException { - initMocks(this); - Session sessionObj=Mockito.mock(Session.class); - PreparedStatement psObj =Mockito.mock(PreparedStatement.class); - try { - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn("10").when(trans).getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF); - Mockito.doReturn(Mockito.mock(TimeTaken.class)).when(trans).start(Mockito.anyString(),Mockito.anyInt()); - Mockito.doReturn(sessionObj).when(cluster).connect("authz"); - Mockito.doReturn(psObj).when(sessionObj).prepare(Mockito.anyString()); - - Mockito.doReturn(Mockito.mock(ColumnDefinitions.class)).when(psObj).getVariables(); - Mockito.doReturn(Mockito.mock(PreparedId.class)).when(psObj).getPreparedId(); - Mockito.doReturn(Mockito.mock(Properties.class)).when(access).getProperties(); - Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); - Define.set(access); - GregorianCalendar start= new GregorianCalendar(); - actionObj = new ApprovalSet(start, "test", dv); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + initMocks(this); + Session sessionObj=Mockito.mock(Session.class); + PreparedStatement psObj =Mockito.mock(PreparedStatement.class); + try { + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn("10").when(trans).getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF); + Mockito.doReturn(Mockito.mock(TimeTaken.class)).when(trans).start(Mockito.anyString(),Mockito.anyInt()); + Mockito.doReturn(sessionObj).when(cluster).connect("authz"); + Mockito.doReturn(psObj).when(sessionObj).prepare(Mockito.anyString()); + + Mockito.doReturn(Mockito.mock(ColumnDefinitions.class)).when(psObj).getVariables(); + Mockito.doReturn(Mockito.mock(PreparedId.class)).when(psObj).getPreparedId(); + Mockito.doReturn(Mockito.mock(Properties.class)).when(access).getProperties(); + Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); + Define.set(access); + GregorianCalendar start= new GregorianCalendar(); + actionObj = new ApprovalSet(start, "test", dv); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test - public void testPuntDate() { - actionObj.write(trans); - ApprovalDAO.Data dataObj = new ApprovalDAO.Data(); - - Result<FutureDAO.Data> rs1 = new Result<FutureDAO.Data>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(FutureDAO.Data.class)); - Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(ApprovalDAO.Data.class)); - actionObj.ladd.add(dataObj); - Result<Void> retVal = actionObj.write(trans); - - rs1 = new Result<FutureDAO.Data>(null,1,"test",new Object[0]); - Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(ApprovalDAO.Data.class)); - retVal = actionObj.write(trans); - assertTrue("Security - test".equals(retVal.details)); - - actionObj.ladd.add(dataObj); - retVal = actionObj.write(trans); - assertTrue(retVal.details.contains("Security - test")); + public void testPuntDate() { + actionObj.write(trans); + ApprovalDAO.Data dataObj = new ApprovalDAO.Data(); + + Result<FutureDAO.Data> rs1 = new Result<FutureDAO.Data>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(FutureDAO.Data.class)); + Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(ApprovalDAO.Data.class)); + actionObj.ladd.add(dataObj); + Result<Void> retVal = actionObj.write(trans); + + rs1 = new Result<FutureDAO.Data>(null,1,"test",new Object[0]); + Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(ApprovalDAO.Data.class)); + retVal = actionObj.write(trans); + assertTrue("Security - test".equals(retVal.details)); + + actionObj.ladd.add(dataObj); + retVal = actionObj.write(trans); + assertTrue(retVal.details.contains("Security - test")); - Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(FutureDAO.Data.class)); - retVal = actionObj.write(trans); - assertTrue(retVal.details.contains("Security - test")); - - actionObj.setConstruct(null); - actionObj.setExpires(new GregorianCalendar()); - actionObj.setMemo(""); - actionObj.ladd = null; - actionObj.write(trans); - } + Mockito.doReturn(rs1).when(dv).insert(Mockito.any(AuthzTrans.class), Mockito.any(FutureDAO.Data.class)); + retVal = actionObj.write(trans); + assertTrue(retVal.details.contains("Security - test")); + + actionObj.setConstruct(null); + actionObj.setExpires(new GregorianCalendar()); + actionObj.setMemo(""); + actionObj.ladd = null; + actionObj.write(trans); + } @Test - public void testHasApprovals() { - assertFalse(actionObj.hasApprovals()); - - ApprovalDAO.Data dataObj = new ApprovalDAO.Data(); - actionObj.ladd.add(dataObj); - assertTrue(actionObj.hasApprovals()); + public void testHasApprovals() { + assertFalse(actionObj.hasApprovals()); + + ApprovalDAO.Data dataObj = new ApprovalDAO.Data(); + actionObj.ladd.add(dataObj); + assertTrue(actionObj.hasApprovals()); } @Test - public void testApprovers() { - Set<String> retVal = actionObj.approvers(); - assertTrue(retVal.size() == 0); - - ApprovalDAO.Data dataObj = new ApprovalDAO.Data(); - actionObj.ladd.add(dataObj); - retVal = actionObj.approvers(); - assertTrue(retVal.size() == 1); - + public void testApprovers() { + Set<String> retVal = actionObj.approvers(); + assertTrue(retVal.size() == 0); + + ApprovalDAO.Data dataObj = new ApprovalDAO.Data(); + actionObj.ladd.add(dataObj); + retVal = actionObj.approvers(); + assertTrue(retVal.size() == 1); + } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java index 6902a426..96ac3844 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/creators/RowCreator.java @@ -41,395 +41,395 @@ import com.google.common.reflect.TypeToken; public class RowCreator { - public static Row getRow() { - Row row = new Row() { - - @Override - public boolean isNull(int i) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean getBool(int i) { - // TODO Auto-generated method stub - return false; - } - - @Override - public byte getByte(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public short getShort(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public int getInt(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public long getLong(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public Date getTimestamp(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public LocalDate getDate(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getTime(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public float getFloat(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public double getDouble(int i) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public ByteBuffer getBytesUnsafe(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ByteBuffer getBytes(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getString(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public BigInteger getVarint(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public BigDecimal getDecimal(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UUID getUUID(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public InetAddress getInet(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> List<T> getList(int i, Class<T> elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> List<T> getList(int i, TypeToken<T> elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> Set<T> getSet(int i, Class<T> elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> Set<T> getSet(int i, TypeToken<T> elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UDTValue getUDTValue(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TupleValue getTupleValue(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Object getObject(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> T get(int i, Class<T> targetClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> T get(int i, TypeToken<T> targetType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> T get(int i, TypeCodec<T> codec) { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean isNull(String name) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean getBool(String name) { - // TODO Auto-generated method stub - return false; - } - - @Override - public byte getByte(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public short getShort(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public int getInt(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public long getLong(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public Date getTimestamp(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public LocalDate getDate(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public long getTime(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public float getFloat(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public double getDouble(String name) { - // TODO Auto-generated method stub - return 0; - } - - @Override - public ByteBuffer getBytesUnsafe(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ByteBuffer getBytes(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getString(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public BigInteger getVarint(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public BigDecimal getDecimal(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UUID getUUID(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public InetAddress getInet(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> List<T> getList(String name, Class<T> elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> List<T> getList(String name, TypeToken<T> elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> Set<T> getSet(String name, Class<T> elementsClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> Set<T> getSet(String name, TypeToken<T> elementsType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UDTValue getUDTValue(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public TupleValue getTupleValue(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Object getObject(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> T get(String name, Class<T> targetClass) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> T get(String name, TypeToken<T> targetType) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> T get(String name, TypeCodec<T> codec) { - // TODO Auto-generated method stub - return null; - } - - @Override - public ColumnDefinitions getColumnDefinitions() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Token getToken(int i) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Token getToken(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Token getPartitionKeyToken() { - // TODO Auto-generated method stub - return null; - } - - }; - return row; - } + public static Row getRow() { + Row row = new Row() { + + @Override + public boolean isNull(int i) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean getBool(int i) { + // TODO Auto-generated method stub + return false; + } + + @Override + public byte getByte(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public short getShort(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getInt(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public long getLong(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public Date getTimestamp(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public LocalDate getDate(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getTime(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public float getFloat(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public double getDouble(int i) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public ByteBuffer getBytesUnsafe(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ByteBuffer getBytes(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getString(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public BigInteger getVarint(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public BigDecimal getDecimal(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UUID getUUID(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public InetAddress getInet(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> List<T> getList(int i, Class<T> elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> List<T> getList(int i, TypeToken<T> elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Set<T> getSet(int i, Class<T> elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Set<T> getSet(int i, TypeToken<T> elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <K, V> Map<K, V> getMap(int i, Class<K> keysClass, Class<V> valuesClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <K, V> Map<K, V> getMap(int i, TypeToken<K> keysType, TypeToken<V> valuesType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UDTValue getUDTValue(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public TupleValue getTupleValue(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getObject(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> T get(int i, Class<T> targetClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> T get(int i, TypeToken<T> targetType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> T get(int i, TypeCodec<T> codec) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isNull(String name) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean getBool(String name) { + // TODO Auto-generated method stub + return false; + } + + @Override + public byte getByte(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public short getShort(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getInt(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public long getLong(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public Date getTimestamp(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public LocalDate getDate(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public long getTime(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public float getFloat(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public double getDouble(String name) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public ByteBuffer getBytesUnsafe(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ByteBuffer getBytes(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getString(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public BigInteger getVarint(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public BigDecimal getDecimal(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UUID getUUID(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public InetAddress getInet(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> List<T> getList(String name, Class<T> elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> List<T> getList(String name, TypeToken<T> elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Set<T> getSet(String name, Class<T> elementsClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> Set<T> getSet(String name, TypeToken<T> elementsType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <K, V> Map<K, V> getMap(String name, Class<K> keysClass, Class<V> valuesClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <K, V> Map<K, V> getMap(String name, TypeToken<K> keysType, TypeToken<V> valuesType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UDTValue getUDTValue(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public TupleValue getTupleValue(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getObject(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> T get(String name, Class<T> targetClass) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> T get(String name, TypeToken<T> targetType) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> T get(String name, TypeCodec<T> codec) { + // TODO Auto-generated method stub + return null; + } + + @Override + public ColumnDefinitions getColumnDefinitions() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Token getToken(int i) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Token getToken(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Token getPartitionKeyToken() { + // TODO Auto-generated method stub + return null; + } + + }; + return row; + } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java index 8fa20ef1..1b41f9ee 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Approval.java @@ -42,173 +42,173 @@ import junit.framework.Assert; public class JU_Approval { - Approval approval; - UUID id; - UUID ticket; - - - @Before - public void setUp() { - id = new UUID(0, 0); - ticket = new UUID(0, 0); - - approval = new Approval(id, ticket, "approver","user", "memo", "operation", "status", "type", 100l); - } - - @Test - public void testRoleFromMemo() { - Assert.assertNull(Approval.roleFromMemo(null)); - Assert.assertEquals("org.onap.ns.admin", - Approval.roleFromMemo(Approval.RE_VALIDATE_ADMIN + "org.onap.ns]")); - Assert.assertEquals("org.onap.ns.owner", Approval.roleFromMemo(Approval.RE_VALIDATE_OWNER + "org.onap.ns]")); - Assert.assertEquals("org.onap.ns.member", Approval.roleFromMemo(Approval.RE_APPROVAL_IN_ROLE - + "bob] + [org.onap.ns.member] - Expires 2018-12-25")); - } - - @Test - public void testExpunge() { - approval.expunge(); - } - -// @Test -// public void testGetLast_notified() { -// Assert.assertTrue(approval.getLast_notified() instanceof Date); -// } + Approval approval; + UUID id; + UUID ticket; + + + @Before + public void setUp() { + id = new UUID(0, 0); + ticket = new UUID(0, 0); + + approval = new Approval(id, ticket, "approver","user", "memo", "operation", "status", "type", 100l); + } + + @Test + public void testRoleFromMemo() { + Assert.assertNull(Approval.roleFromMemo(null)); + Assert.assertEquals("org.onap.ns.admin", + Approval.roleFromMemo(Approval.RE_VALIDATE_ADMIN + "org.onap.ns]")); + Assert.assertEquals("org.onap.ns.owner", Approval.roleFromMemo(Approval.RE_VALIDATE_OWNER + "org.onap.ns]")); + Assert.assertEquals("org.onap.ns.member", Approval.roleFromMemo(Approval.RE_APPROVAL_IN_ROLE + + "bob] + [org.onap.ns.member] - Expires 2018-12-25")); + } + + @Test + public void testExpunge() { + approval.expunge(); + } + +// @Test +// public void testGetLast_notified() { +// Assert.assertTrue(approval.getLast_notified() instanceof Date); +// } // -// @Test -// public void testSetLastNotified() { -// approval.setLastNotified(date); -// } - - @Test - public void testGetStatus() { - Assert.assertEquals("status", approval.getStatus()); - } - - @Test - public void testSetStatus() { - approval.setStatus("status"); - } - - @Test - public void testGetId() { - Assert.assertTrue(approval.getId() instanceof UUID); - } - - @Test - public void testGetTicket() { - Assert.assertTrue(approval.getTicket() instanceof UUID); - } - - @Test - public void testGetMemo() { - Assert.assertEquals("memo", approval.getMemo()); - } - - @Test - public void testGetOperation() { - Assert.assertEquals("operation", approval.getOperation()); - } - - @Test - public void testGetType() { - Assert.assertEquals("type", approval.getType()); - } - - @Test - public void testLapsed() { - approval.lapsed(); - } - - @Test - public void testGetRole() { - Assert.assertNull(approval.getRole()); - } - - @Test - public void testToString() { - Assert.assertEquals("user memo", approval.toString()); - } - - @Test - public void testResetLocalData() { - approval.resetLocalData(); - } - - @Test - public void testPendingDelete() { - Assert.assertFalse(approval.pendingDelete(approval)); - } - - @Test - public void testUpdateNonDryRun() { - approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - -// approval.update(trans, dao, false); - } - - @Test - public void testUpdateDryRun() { - approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - -// approval.update(trans, dao, true); - } - - @Test - public void testDelayDeleteDryRun() { - approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - - List<Approval> list = new ArrayList<Approval>(); - list.add(approval); - Approval.delayDelete(trans, dao, true, list, "text"); - } - - @Test - public void testDelayDeleteNonDryRun() { - approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - Result<Void> rv = Result.ok(); - when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); - - List<Approval> list = new ArrayList<Approval>(); - list.add(approval); - Approval.delayDelete(trans, dao, false, list, "text"); - } - - @Test - public void testDelayDeleteResultNotOk() { - approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); - AuthzTrans trans = mock(AuthzTrans.class); - ApprovalDAO dao = mock(ApprovalDAO.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - Result<Void> rv = Result.err(new Exception()); - when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); - - List<Approval> list = new ArrayList<Approval>(); - list.add(approval); - Approval.delayDelete(trans, dao, false, list, "text"); - } +// @Test +// public void testSetLastNotified() { +// approval.setLastNotified(date); +// } + + @Test + public void testGetStatus() { + Assert.assertEquals("status", approval.getStatus()); + } + + @Test + public void testSetStatus() { + approval.setStatus("status"); + } + + @Test + public void testGetId() { + Assert.assertTrue(approval.getId() instanceof UUID); + } + + @Test + public void testGetTicket() { + Assert.assertTrue(approval.getTicket() instanceof UUID); + } + + @Test + public void testGetMemo() { + Assert.assertEquals("memo", approval.getMemo()); + } + + @Test + public void testGetOperation() { + Assert.assertEquals("operation", approval.getOperation()); + } + + @Test + public void testGetType() { + Assert.assertEquals("type", approval.getType()); + } + + @Test + public void testLapsed() { + approval.lapsed(); + } + + @Test + public void testGetRole() { + Assert.assertNull(approval.getRole()); + } + + @Test + public void testToString() { + Assert.assertEquals("user memo", approval.toString()); + } + + @Test + public void testResetLocalData() { + approval.resetLocalData(); + } + + @Test + public void testPendingDelete() { + Assert.assertFalse(approval.pendingDelete(approval)); + } + + @Test + public void testUpdateNonDryRun() { + approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + +// approval.update(trans, dao, false); + } + + @Test + public void testUpdateDryRun() { + approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + +// approval.update(trans, dao, true); + } + + @Test + public void testDelayDeleteDryRun() { + approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + + List<Approval> list = new ArrayList<Approval>(); + list.add(approval); + Approval.delayDelete(trans, dao, true, list, "text"); + } + + @Test + public void testDelayDeleteNonDryRun() { + approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + Result<Void> rv = Result.ok(); + when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); + + List<Approval> list = new ArrayList<Approval>(); + list.add(approval); + Approval.delayDelete(trans, dao, false, list, "text"); + } + + @Test + public void testDelayDeleteResultNotOk() { + approval = new Approval(id, ticket, "approver", "user", "memo", "operation", "status", "type", 100l); + AuthzTrans trans = mock(AuthzTrans.class); + ApprovalDAO dao = mock(ApprovalDAO.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + Result<Void> rv = Result.err(new Exception()); + when(dao.delete(any(AuthzTrans.class), any(ApprovalDAO.Data.class), any(Boolean.class))).thenReturn(rv); + + List<Approval> list = new ArrayList<Approval>(); + list.add(approval); + Approval.delayDelete(trans, dao, false, list, "text"); + } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java index 20d0dcba..81b7c965 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_ExpireRange.java @@ -31,42 +31,42 @@ import org.onap.aaf.auth.batch.helpers.ExpireRange; import org.onap.aaf.cadi.PropAccess; public class JU_ExpireRange { - @Test - public void test() { - ExpireRange expRange = new ExpireRange(new PropAccess()); - Date now = expRange.now(); - - Set<String> names=expRange.names(); - assertTrue(names.contains("OneMonth")); - assertTrue(names.contains("OneWeek")); - assertTrue(names.contains("Delete")); - assertFalse(names.contains(null)); - assertFalse(names.contains("bogus")); - - ExpireRange.Range r; - GregorianCalendar gc = new GregorianCalendar(); - String[] all = new String[] {"ur","cred"}; - - // Test 3 weeks prior - gc.setTime(now); - gc.add(GregorianCalendar.WEEK_OF_MONTH,-3); - for(String rs : all) { - r = expRange.getRange(rs, gc.getTime()); - assertNotNull(r); - assertEquals("Delete",r.name()); - } - - // Test 1 week prior - gc.setTime(now); - gc.add(GregorianCalendar.WEEK_OF_MONTH,-1); - for(String rs : all) { - r = expRange.getRange(rs, gc.getTime()); - assertNull(r); - } - - // Test Today - r = expRange.getRange("cred", now); - assertNotNull(r); - } + @Test + public void test() { + ExpireRange expRange = new ExpireRange(new PropAccess()); + Date now = expRange.now(); + + Set<String> names=expRange.names(); + assertTrue(names.contains("OneMonth")); + assertTrue(names.contains("OneWeek")); + assertTrue(names.contains("Delete")); + assertFalse(names.contains(null)); + assertFalse(names.contains("bogus")); + + ExpireRange.Range r; + GregorianCalendar gc = new GregorianCalendar(); + String[] all = new String[] {"ur","cred"}; + + // Test 3 weeks prior + gc.setTime(now); + gc.add(GregorianCalendar.WEEK_OF_MONTH,-3); + for(String rs : all) { + r = expRange.getRange(rs, gc.getTime()); + assertNotNull(r); + assertEquals("Delete",r.name()); + } + + // Test 1 week prior + gc.setTime(now); + gc.add(GregorianCalendar.WEEK_OF_MONTH,-1); + for(String rs : all) { + r = expRange.getRange(rs, gc.getTime()); + assertNull(r); + } + + // Test Today + r = expRange.getRange("cred", now); + assertNotNull(r); + } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java index e551ce2b..7a94b9f8 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_Future.java @@ -51,84 +51,84 @@ import com.datastax.driver.core.SimpleStatement; public class JU_Future { - Future future; - Date start; - Date expires; - ByteBuffer bBuff; - - @Before - public void setUp() { - UUID id = new UUID(0, 0); - start = new Date(); - expires = new Date(); - future = new Future(id, "Re-Validate Ownership for AAF Namespace '\'test\'test", "target", start, expires, - bBuff); - } - - @Test - public void testId() { - Assert.assertTrue(future.id() instanceof UUID); - } - - @Test - public void testMemo() { - Assert.assertEquals("Re-Validate Ownership for AAF Namespace '\'test\'test", future.memo()); - } - - @Test - public void testStart() { - Assert.assertTrue(future.start() instanceof Date); - } - - @Test - public void testExpires() { - Assert.assertTrue(future.expires() instanceof Date); - } - - @Test - public void testTarget() { - Assert.assertEquals("target", future.target()); - } - - @Test - public void testExpunge() { - future.expunge(); - } - - @Test - public void testCompareTo() { - future.compareTo(null); - future.compareTo(future); - } - - @Test - public void testResetLocalData() { - Future.resetLocalData(); - Assert.assertEquals(0, Future.sizeForDeletion()); - Assert.assertEquals(false, Future.pendingDelete(future)); - } - - - @Test - public void testDelayedDeleteWithDryRun() { - AuthzTrans trans = mock(AuthzTrans.class); - LogTarget target = mock(LogTarget.class); - - when(trans.info()).thenReturn(target); - - assertEquals(Result.ok().status, future.delayedDelete(trans, null, true, "text").status); - } - - @Test - public void testDelayedDeleteNonDryRun() { - AuthzTrans trans = mock(AuthzTrans.class); - LogTarget target = mock(LogTarget.class); - FutureDAO fd = mock(FutureDAO.class); - - when(trans.info()).thenReturn(target); - when(fd.delete(any(AuthzTrans.class), any(FutureDAO.Data.class), any(Boolean.class))).thenReturn(Result.ok()); - - assertEquals(Result.ok().status, future.delayedDelete(trans, fd, false, "text").status); - } + Future future; + Date start; + Date expires; + ByteBuffer bBuff; + + @Before + public void setUp() { + UUID id = new UUID(0, 0); + start = new Date(); + expires = new Date(); + future = new Future(id, "Re-Validate Ownership for AAF Namespace '\'test\'test", "target", start, expires, + bBuff); + } + + @Test + public void testId() { + Assert.assertTrue(future.id() instanceof UUID); + } + + @Test + public void testMemo() { + Assert.assertEquals("Re-Validate Ownership for AAF Namespace '\'test\'test", future.memo()); + } + + @Test + public void testStart() { + Assert.assertTrue(future.start() instanceof Date); + } + + @Test + public void testExpires() { + Assert.assertTrue(future.expires() instanceof Date); + } + + @Test + public void testTarget() { + Assert.assertEquals("target", future.target()); + } + + @Test + public void testExpunge() { + future.expunge(); + } + + @Test + public void testCompareTo() { + future.compareTo(null); + future.compareTo(future); + } + + @Test + public void testResetLocalData() { + Future.resetLocalData(); + Assert.assertEquals(0, Future.sizeForDeletion()); + Assert.assertEquals(false, Future.pendingDelete(future)); + } + + + @Test + public void testDelayedDeleteWithDryRun() { + AuthzTrans trans = mock(AuthzTrans.class); + LogTarget target = mock(LogTarget.class); + + when(trans.info()).thenReturn(target); + + assertEquals(Result.ok().status, future.delayedDelete(trans, null, true, "text").status); + } + + @Test + public void testDelayedDeleteNonDryRun() { + AuthzTrans trans = mock(AuthzTrans.class); + LogTarget target = mock(LogTarget.class); + FutureDAO fd = mock(FutureDAO.class); + + when(trans.info()).thenReturn(target); + when(fd.delete(any(AuthzTrans.class), any(FutureDAO.Data.class), any(Boolean.class))).thenReturn(Result.ok()); + + assertEquals(Result.ok().status, future.delayedDelete(trans, fd, false, "text").status); + } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java index 1208ba92..3d71614b 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_NS.java @@ -48,112 +48,112 @@ import junit.framework.Assert; public class JU_NS { - NS ns; - NSSplit nSSplit; - - @Before - public void setUp() { - ns = new NS("name", "description", "parent", 1, 1); - nSSplit = new NSSplit("string", 1); - } - - @Test - public void testToString() { - Assert.assertEquals("name", ns.toString()); - } - - @Test - public void testHashCode() { - Assert.assertEquals(3373707, ns.hashCode()); - } - - @Test - public void testEquals() { - Assert.assertEquals(true, ns.equals("name")); - Assert.assertEquals(false, ns.equals("name1")); - } - - @Test - public void testCompareTo() { - NS nsValid = new NS("name", "description", "parent", 1, 1); - Assert.assertEquals(0, ns.compareTo(nsValid)); - - NS nsInvalid = new NS("name1", "description", "parent", 1, 1); - Assert.assertEquals(-1, ns.compareTo(nsInvalid)); - } - - @Test - public void testDeriveParent() { - ns.deriveParent("d.ot.te.d"); - } - - @Test - public void testLoadWithoutNS() { - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - Creator<NS> creator = mock(Creator.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - ArrayList<Row> rows = new ArrayList<Row>(); - Row row = RowCreator.getRow(); - rows.add(row); - - when(trans.info()).thenReturn(target); - when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); - when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.iterator()).thenReturn(rows.iterator()); - when(creator.create(row)).thenReturn(ns); - - NS.load(trans, session, creator); - } - - @Test - public void testLoadOne() { - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - Creator<NS> creator = mock(Creator.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - ArrayList<Row> rows = new ArrayList<Row>(); - Row row = RowCreator.getRow(); - rows.add(row); - - when(trans.info()).thenReturn(target); - when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); - when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.iterator()).thenReturn(rows.iterator()); - when(creator.create(row)).thenReturn(ns); - - NS.loadOne(trans, session, creator, "text"); - } - - @Test - public void testCount() { - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - ArrayList<Row> rows = new ArrayList<Row>(); - Row row = RowCreator.getRow(); - rows.add(row); - - when(trans.info()).thenReturn(target); - when(trans.start("Count Namespaces", Env.REMOTE)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.one()).thenReturn(row); - - assertEquals(0, NS.count(trans, session)); - } - - @Test - public void testV2() { - NS.v2_0_11.create(RowCreator.getRow()); - assertEquals(NS.v2_0_11.select(), "SELECT name, description, parent, type, scope FROM authz.ns "); - } + NS ns; + NSSplit nSSplit; + + @Before + public void setUp() { + ns = new NS("name", "description", "parent", 1, 1); + nSSplit = new NSSplit("string", 1); + } + + @Test + public void testToString() { + Assert.assertEquals("name", ns.toString()); + } + + @Test + public void testHashCode() { + Assert.assertEquals(3373707, ns.hashCode()); + } + + @Test + public void testEquals() { + Assert.assertEquals(true, ns.equals("name")); + Assert.assertEquals(false, ns.equals("name1")); + } + + @Test + public void testCompareTo() { + NS nsValid = new NS("name", "description", "parent", 1, 1); + Assert.assertEquals(0, ns.compareTo(nsValid)); + + NS nsInvalid = new NS("name1", "description", "parent", 1, 1); + Assert.assertEquals(-1, ns.compareTo(nsInvalid)); + } + + @Test + public void testDeriveParent() { + ns.deriveParent("d.ot.te.d"); + } + + @Test + public void testLoadWithoutNS() { + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + Creator<NS> creator = mock(Creator.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + ArrayList<Row> rows = new ArrayList<Row>(); + Row row = RowCreator.getRow(); + rows.add(row); + + when(trans.info()).thenReturn(target); + when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); + when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.iterator()).thenReturn(rows.iterator()); + when(creator.create(row)).thenReturn(ns); + + NS.load(trans, session, creator); + } + + @Test + public void testLoadOne() { + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + Creator<NS> creator = mock(Creator.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + ArrayList<Row> rows = new ArrayList<Row>(); + Row row = RowCreator.getRow(); + rows.add(row); + + when(trans.info()).thenReturn(target); + when(trans.start("Read Namespaces", Env.REMOTE)).thenReturn(tt); + when(trans.start("Load Namespaces", Env.SUB)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.iterator()).thenReturn(rows.iterator()); + when(creator.create(row)).thenReturn(ns); + + NS.loadOne(trans, session, creator, "text"); + } + + @Test + public void testCount() { + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + ArrayList<Row> rows = new ArrayList<Row>(); + Row row = RowCreator.getRow(); + rows.add(row); + + when(trans.info()).thenReturn(target); + when(trans.start("Count Namespaces", Env.REMOTE)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.one()).thenReturn(row); + + assertEquals(0, NS.count(trans, session)); + } + + @Test + public void testV2() { + NS.v2_0_11.create(RowCreator.getRow()); + assertEquals(NS.v2_0_11.select(), "SELECT name, description, parent, type, scope FROM authz.ns "); + } } diff --git a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java index ab531e90..50833d0f 100644 --- a/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java +++ b/auth/auth-batch/src/test/java/org/onap/aaf/auth/batch/helpers/test/JU_UserRole.java @@ -49,106 +49,106 @@ import junit.framework.Assert; public class JU_UserRole { - UserRole userRole; - UserRole userRole1; - Date date; - PrintStream ds; - - @Before - public void setUp() { - date = new Date(); - userRole = new UserRole("user", "ns", "rname", date); - userRole = new UserRole("user", "role", "ns", "rname", date); - } - - @Test - public void testTotalLoaded() { - Assert.assertEquals(0, userRole.totalLoaded()); - } - - @Test - public void testDeleted() { - Assert.assertEquals(0, userRole.deleted()); - } - - @Test - public void testExpunge() { - userRole.expunge(); - } - - @Test - public void testSetDeleteStream() { - userRole.setDeleteStream(ds); - } - - @Test - public void testSetRecoverStream() { - userRole.setRecoverStream(ds); - } - - @Test - public void testUrdd() { - Assert.assertTrue(userRole.urdd() instanceof UserRoleDAO.Data); - } - - @Test - public void testUser() { - Assert.assertEquals("user", userRole.user()); - } - - @Test - public void testRole() { - Assert.assertEquals("role", userRole.role()); - } - - @Test - public void testNs() { - Assert.assertEquals("ns", userRole.ns()); - } - - @Test - public void testRName() { - Assert.assertEquals("rname", userRole.rname()); - } - - @Test - public void testExpires() { - Assert.assertEquals(date, userRole.expires()); - userRole.expires(date); - } - - @Test - public void testToString() { - Assert.assertTrue(userRole.toString() instanceof String); - } - - @Test - public void testGet() { - userRole.get("u", "r"); - } - - @Test - public void testResetLocalData() { - userRole.resetLocalData(); - } - - @Test - public void testLoad() { - Creator<UserRole> creator = mock(Creator.class); - Trans trans = mock(Trans.class); - Session session = mock(Session.class); - LogTarget target = mock(LogTarget.class); - TimeTaken tt = mock(TimeTaken.class); - ResultSet results = mock(ResultSet.class); - - List<Row> rows = new ArrayList<Row>(); - - when(trans.info()).thenReturn(target); - when(trans.start("Read UserRoles", Env.REMOTE)).thenReturn(tt); - when(trans.start("Load UserRole", Env.SUB)).thenReturn(tt); - when(session.execute(any(SimpleStatement.class))).thenReturn(results); - when(results.iterator()).thenReturn(rows.iterator()); - - } + UserRole userRole; + UserRole userRole1; + Date date; + PrintStream ds; + + @Before + public void setUp() { + date = new Date(); + userRole = new UserRole("user", "ns", "rname", date); + userRole = new UserRole("user", "role", "ns", "rname", date); + } + + @Test + public void testTotalLoaded() { + Assert.assertEquals(0, userRole.totalLoaded()); + } + + @Test + public void testDeleted() { + Assert.assertEquals(0, userRole.deleted()); + } + + @Test + public void testExpunge() { + userRole.expunge(); + } + + @Test + public void testSetDeleteStream() { + userRole.setDeleteStream(ds); + } + + @Test + public void testSetRecoverStream() { + userRole.setRecoverStream(ds); + } + + @Test + public void testUrdd() { + Assert.assertTrue(userRole.urdd() instanceof UserRoleDAO.Data); + } + + @Test + public void testUser() { + Assert.assertEquals("user", userRole.user()); + } + + @Test + public void testRole() { + Assert.assertEquals("role", userRole.role()); + } + + @Test + public void testNs() { + Assert.assertEquals("ns", userRole.ns()); + } + + @Test + public void testRName() { + Assert.assertEquals("rname", userRole.rname()); + } + + @Test + public void testExpires() { + Assert.assertEquals(date, userRole.expires()); + userRole.expires(date); + } + + @Test + public void testToString() { + Assert.assertTrue(userRole.toString() instanceof String); + } + + @Test + public void testGet() { + userRole.get("u", "r"); + } + + @Test + public void testResetLocalData() { + userRole.resetLocalData(); + } + + @Test + public void testLoad() { + Creator<UserRole> creator = mock(Creator.class); + Trans trans = mock(Trans.class); + Session session = mock(Session.class); + LogTarget target = mock(LogTarget.class); + TimeTaken tt = mock(TimeTaken.class); + ResultSet results = mock(ResultSet.class); + + List<Row> rows = new ArrayList<Row>(); + + when(trans.info()).thenReturn(target); + when(trans.start("Read UserRoles", Env.REMOTE)).thenReturn(tt); + when(trans.start("Load UserRole", Env.SUB)).thenReturn(tt); + when(session.execute(any(SimpleStatement.class))).thenReturn(results); + when(results.iterator()).thenReturn(rows.iterator()); + + } } 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 9672199b..eea3c4c2 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 @@ -72,7 +72,7 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl // Hold current time stamps from Tables private final Date startTime; - private final boolean cacheNotify; + private final boolean cacheNotify; private PreparedStatement psCheck; ////////////////////////////////////////// @@ -87,22 +87,22 @@ public class CacheInfoDAO extends CassDAOImpl<AuthzTrans,CacheInfoDAO.Data> impl init(trans); } - public CacheInfoDAO(AuthzTrans trans, AbsCassDAO<AuthzTrans,?> aDao) throws APIException, IOException { + public CacheInfoDAO(AuthzTrans trans, AbsCassDAO<AuthzTrans,?> aDao) throws APIException, IOException { super(trans, CacheInfoDAO.class.getSimpleName(),aDao,Data.class,TABLE,readConsistency(trans,TABLE), writeConsistency(trans,TABLE)); startTime = new Date(); init(trans); cacheNotify = noK8s(trans); } - /** - * Need a different point to point cache clear strategy for K8s... - * @param trans - * @return - */ + /** + * Need a different point to point cache clear strategy for K8s... + * @param trans + * @return + */ private boolean noK8s(AuthzTrans trans) { - String container = trans.getProperty(Config.AAF_LOCATOR_CONTAINER); - return ! ("helm".equals(container) || "oom".equals(container)); - } + String container = trans.getProperty(Config.AAF_LOCATOR_CONTAINER); + return ! ("helm".equals(container) || "oom".equals(container)); + } /** * @author Jonathan */ 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 d64cff29..9a2511d2 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 @@ -85,8 +85,8 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { public Date expires; public Integer other; public String ns; - public String tag; - public String notes; + public String tag; + public String notes; public ByteBuffer cred; // this is a blob in cassandra @@ -139,7 +139,7 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { @Override protected void key(Data data, int _idx, Object[] obj) { - int idx = _idx; + int idx = _idx; obj[idx] = data.id; obj[++idx] = data.type; @@ -221,23 +221,23 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { " WHERE id = ?", CredLoader.deflt,readConsistency); } - /* (non-Javadoc) - * @see org.onap.aaf.auth.dao.CassDAOImpl#create(org.onap.aaf.misc.env.TransStore, java.lang.Object) - */ - @Override - public Result<Data> create(AuthzTrans trans, Data data) { - if(data.tag == null) { - if(data.type==0) { - data.tag="PlaceHolder"; - } else { - long l = srand.nextLong(); - data.tag = Long.toHexString(l); - } - } - return super.create(trans, data); - } + /* (non-Javadoc) + * @see org.onap.aaf.auth.dao.CassDAOImpl#create(org.onap.aaf.misc.env.TransStore, java.lang.Object) + */ + @Override + public Result<Data> create(AuthzTrans trans, Data data) { + if(data.tag == null) { + if(data.type==0) { + data.tag="PlaceHolder"; + } else { + long l = srand.nextLong(); + data.tag = Long.toHexString(l); + } + } + return super.create(trans, data); + } - public Result<List<Data>> readNS(AuthzTrans trans, String ns) { + public Result<List<Data>> readNS(AuthzTrans trans, String ns) { return psNS.read(trans, R_TEXT, new Object[]{ns}); } @@ -267,12 +267,12 @@ public class CredDAO extends CassDAOImpl<AuthzTrans,CredDAO.Data> { : (modified.name() + "d credential for " + data.id); String spacer = ": "; if(data.notes!=null) { - hd.memo+=spacer + data.notes; - spacer = ", "; + hd.memo+=spacer + data.notes; + spacer = ", "; } if(data.tag!=null) { - hd.memo+=spacer + data.tag; + hd.memo+=spacer + data.tag; } // Detail? 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 72c0e98b..eafdb884 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 @@ -69,8 +69,8 @@ public class FutureDAO extends CassDAOImpl<AuthzTrans,FutureDAO.Data> { public String memo; public Date start; public Date expires; - public String target_key; - public Date target_date; + public String target_key; + public Date target_date; public ByteBuffer construct; // this is a blob in cassandra } 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 73ab343b..82874ce9 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 @@ -173,21 +173,21 @@ public class HistoryDAO extends CassDAOImpl<AuthzTrans, HistoryDAO.Data> { } public void createBatch(StringBuilder sb, Data data) { - sb.append("INSERT INTO history ("); - sb.append(helpers[FIELD_COMMAS]); - sb.append(") VALUES(now(),"); - sb.append(data.yr_mon); - sb.append(",'"); - sb.append(data.user); - sb.append("','"); - sb.append(data.action); - sb.append("','"); - sb.append(data.target); - sb.append("','"); - sb.append(data.subject); - sb.append("','"); - sb.append(data.memo); - sb.append("',null);\n"); + sb.append("INSERT INTO history ("); + sb.append(helpers[FIELD_COMMAS]); + sb.append(") VALUES(now(),"); + sb.append(data.yr_mon); + sb.append(",'"); + sb.append(data.user); + sb.append("','"); + sb.append(data.action); + sb.append("','"); + sb.append(data.target); + sb.append("','"); + sb.append(data.subject); + sb.append("','"); + sb.append(data.memo); + sb.append("',null);\n"); } public Result<List<Data>> readByYYYYMM(AuthzTrans trans, int yyyymm) { 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 085f4199..478cceb0 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 @@ -100,8 +100,8 @@ public class LocateDAO extends CassDAOImpl<AuthzTrans,LocateDAO.Data> { LocateLoader.deflt.unmarshal(this, toDIS(bb)); } - public Data copy() { - Data out = new Data(); + public Data copy() { + Data out = new Data(); out.name = name; out.hostname = hostname; out.port = port; @@ -115,8 +115,8 @@ public class LocateDAO extends CassDAOImpl<AuthzTrans,LocateDAO.Data> { out.subprotocol = new HashSet<>(); out.subprotocol.addAll(subprotocol); out.port_key = port_key; - return out; - } + return out; + } } private static class LocateLoader extends Loader<Data> implements Streamer<Data>{ 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 0033f8a1..699d6e28 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 @@ -93,31 +93,31 @@ public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> { } public String fullType() { - StringBuilder sb = new StringBuilder(); - if(ns==null) { - sb.append('.'); - } else { - sb.append(ns); - sb.append(ns.indexOf('@')<0?'.':':'); - } - sb.append(type); - return sb.toString(); + StringBuilder sb = new StringBuilder(); + if(ns==null) { + sb.append('.'); + } else { + sb.append(ns); + sb.append(ns.indexOf('@')<0?'.':':'); + } + sb.append(type); + return sb.toString(); } public String fullPerm() { - StringBuilder sb = new StringBuilder(); - if(ns==null) { - sb.append("null."); - } else { - sb.append(ns); - sb.append(ns.indexOf('@')<0?'.':':'); - } - sb.append(type); - sb.append('|'); - sb.append(instance); - sb.append('|'); - sb.append(action); - return sb.toString(); + StringBuilder sb = new StringBuilder(); + if(ns==null) { + sb.append("null."); + } else { + sb.append(ns); + sb.append(ns.indexOf('@')<0?'.':':'); + } + sb.append(type); + sb.append('|'); + sb.append(instance); + sb.append('|'); + sb.append(action); + return sb.toString(); } public String encode() { @@ -213,26 +213,26 @@ public class PermDAO extends CassDAOImpl<AuthzTrans,PermDAO.Data> { Data rv = new PermDAO.Data(); if (rdns.isOKhasData()) { switch(s.length) { - case 4: - rv.ns=s[0]; - rv.type=s[1]; - rv.instance=s[2]; - rv.action=s[3]; - break; + case 4: + rv.ns=s[0]; + rv.type=s[1]; + rv.instance=s[2]; + rv.action=s[3]; + break; case 3: - rv.ns=s[0]; + rv.ns=s[0]; rv.type=s[1]; rv.instance=s[2]; rv.action=s[3]; break; case 2: - rv.ns=s[0]; + rv.ns=s[0]; rv.type=s[1]; rv.instance=s[2]; rv.action=STAR; break; default: - rv.ns=s[0]; + rv.ns=s[0]; rv.type=s[1]; rv.instance = STAR; rv.action = STAR; 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 a5fa7a77..e5c97559 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 @@ -106,15 +106,15 @@ public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> { } public String fullName() { - StringBuilder sb = new StringBuilder(); - if(ns==null) { - sb.append('.'); - } else { - sb.append(ns); - sb.append(ns.indexOf('@')<0?'.':':'); - } - sb.append(name); - return sb.toString(); + StringBuilder sb = new StringBuilder(); + if(ns==null) { + sb.append('.'); + } else { + sb.append(ns); + sb.append(ns.indexOf('@')<0?'.':':'); + } + sb.append(name); + return sb.toString(); } public String encode() { @@ -131,28 +131,28 @@ public class RoleDAO extends CassDAOImpl<AuthzTrans,RoleDAO.Data> { */ public static Result<Data> decode(AuthzTrans trans, Question q, String r) { Data data = new Data(); - if(r.indexOf('@')>=0) { - int colon = r.indexOf(':'); - if(colon<0) { - return Result.err(Result.ERR_BadData, "%s is not a valid Role",r); - } else { - data.ns=r.substring(0, colon); - data.name=r.substring(++colon); - } - } else { - String[] ss = Split.splitTrim('|', r,2); - if (ss[1]==null) { // older 1 part encoding must be evaluated for NS - Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]); - if (nss.notOK()) { - return Result.err(nss); - } - data.ns=nss.value.ns; - data.name=nss.value.name; - } else { // new 4 part encoding - data.ns=ss[0]; - data.name=ss[1]; - } - } + if(r.indexOf('@')>=0) { + int colon = r.indexOf(':'); + if(colon<0) { + return Result.err(Result.ERR_BadData, "%s is not a valid Role",r); + } else { + data.ns=r.substring(0, colon); + data.name=r.substring(++colon); + } + } else { + String[] ss = Split.splitTrim('|', r,2); + if (ss[1]==null) { // older 1 part encoding must be evaluated for NS + Result<NsSplit> nss = q.deriveNsSplit(trans, ss[0]); + if (nss.notOK()) { + return Result.err(nss); + } + data.ns=nss.value.ns; + data.name=nss.value.name; + } else { // new 4 part encoding + data.ns=ss[0]; + data.name=ss[1]; + } + } return Result.ok(data); } 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 4ec70d4a..dd367c51 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 @@ -245,13 +245,13 @@ public class Function { // 2.1) Does role exist with that name if(cname!=null && q.roleDAO().read(trans, parent, cname).isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, + return Result.err(Status.ERR_ConflictAlreadyExists, "Role exists with that name"); } // 2.2) Do perms exist with that name if(cname!=null && q.permDAO().readByType(trans, parent, cname).isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, + return Result.err(Status.ERR_ConflictAlreadyExists, "Perms exist with that name"); } 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 b0680621..3f0e92e7 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 @@ -153,32 +153,32 @@ public class PermLookup { List<PermDAO.Data> lpdd = new ArrayList<>(); for (String perm : rss.value) { if (lookup) { - Map<String,PermDAO.Data> mspdd = new TreeMap<>(); + Map<String,PermDAO.Data> mspdd = new TreeMap<>(); Result<String[]> ap = PermDAO.Data.decodeToArray(trans, q, perm); if (ap.isOK()) { Result<List<PermDAO.Data>> rlpd = q.permDAO().read(perm,trans,ap.value); if (rlpd.isOKhasData()) { for (PermDAO.Data pData : rlpd.value) { - // ONLY add perms/roles which are related to this lookup - for(String pdr : pData.roles(false)) { - for(RoleDAO.Data r : roles.value) { - if(pdr.equals(r.encode())) { - PermDAO.Data pdd = mspdd.get(pData.fullPerm()); - if(pdd==null) { - pdd = new PermDAO.Data(); - pdd.ns = pData.ns; - pdd.type = pData.type; - pdd.instance = pData.instance; - pdd.action = pData.action; - pdd.description = pData.description; + // ONLY add perms/roles which are related to this lookup + for(String pdr : pData.roles(false)) { + for(RoleDAO.Data r : roles.value) { + if(pdr.equals(r.encode())) { + PermDAO.Data pdd = mspdd.get(pData.fullPerm()); + if(pdd==null) { + pdd = new PermDAO.Data(); + pdd.ns = pData.ns; + pdd.type = pData.type; + pdd.instance = pData.instance; + pdd.action = pData.action; + pdd.description = pData.description; lpdd.add(pdd); - } - pdd.roles(true).add(pdr); - break; - } - } - } + } + pdd.roles(true).add(pdr); + break; + } + } + } } } } else { 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 6b6c23bf..b797ca05 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 @@ -132,62 +132,62 @@ public class Question { private final HistoryDAO historyDAO; public HistoryDAO historyDAO() { - return historyDAO; + return historyDAO; } private final CachedNSDAO nsDAO; public CachedNSDAO nsDAO() { - return nsDAO; + return nsDAO; } private final CachedRoleDAO roleDAO; public CachedRoleDAO roleDAO() { - return roleDAO; + return roleDAO; } private final CachedPermDAO permDAO; public CachedPermDAO permDAO() { - return permDAO; + return permDAO; } private final CachedUserRoleDAO userRoleDAO; public CachedUserRoleDAO userRoleDAO() { - return userRoleDAO; + return userRoleDAO; } private final CachedCredDAO credDAO; public CachedCredDAO credDAO() { - return credDAO; + return credDAO; } private final CachedCertDAO certDAO; public CachedCertDAO certDAO() { - return certDAO; + return certDAO; } private final DelegateDAO delegateDAO; public DelegateDAO delegateDAO() { - return delegateDAO; + return delegateDAO; } private final FutureDAO futureDAO; public FutureDAO futureDAO() { - return futureDAO; + return futureDAO; } private final ApprovalDAO approvalDAO; public ApprovalDAO approvalDAO() { - return approvalDAO; + return approvalDAO; } public final LocateDAO locateDAO; public LocateDAO locateDAO() { - return locateDAO; + return locateDAO; } private final CacheInfoDAO cacheInfoDAO; - private final int cldays; - private final boolean alwaysSpecial; + private final int cldays; + private final boolean alwaysSpecial; public Question(AuthzTrans trans, Cluster cluster, String keyspace) throws APIException, IOException { PERMS = trans.slot("USER_PERMS"); @@ -229,18 +229,18 @@ public class Question { * Note: This Constructor created for JUNIT Purposes. Do not use otherwise. */ public Question(AuthzTrans trans, HistoryDAO historyDAO, CacheInfoDAO cacheInfoDAO, - CachedNSDAO nsDAO, CachedPermDAO permDAO, CachedRoleDAO roleDAO, - CachedUserRoleDAO userRoleDAO, CachedCredDAO credDAO, CachedCertDAO certDAO, - LocateDAO locateDAO,FutureDAO futureDAO, DelegateDAO delegateDAO, - ApprovalDAO approvalDAO ) { - this.historyDAO = historyDAO; - this.cacheInfoDAO = cacheInfoDAO; - this.nsDAO = nsDAO; - this.permDAO = permDAO; - this.roleDAO = roleDAO; - this.userRoleDAO = userRoleDAO; - this.credDAO = credDAO; - this.certDAO = certDAO; + CachedNSDAO nsDAO, CachedPermDAO permDAO, CachedRoleDAO roleDAO, + CachedUserRoleDAO userRoleDAO, CachedCredDAO credDAO, CachedCertDAO certDAO, + LocateDAO locateDAO,FutureDAO futureDAO, DelegateDAO delegateDAO, + ApprovalDAO approvalDAO ) { + this.historyDAO = historyDAO; + this.cacheInfoDAO = cacheInfoDAO; + this.nsDAO = nsDAO; + this.permDAO = permDAO; + this.roleDAO = roleDAO; + this.userRoleDAO = userRoleDAO; + this.credDAO = credDAO; + this.certDAO = certDAO; this.locateDAO = locateDAO; this.futureDAO = futureDAO; this.delegateDAO = delegateDAO; @@ -272,28 +272,28 @@ public class Question { } public Result<PermDAO.Data> permFrom(AuthzTrans trans, String type, String instance, String action) { - if(type.indexOf('@') >= 0) { - int colon = type.indexOf(':'); - if(colon>=0) { - PermDAO.Data pdd = new PermDAO.Data(); - pdd.ns = type.substring(0, colon); - pdd.type = type.substring(colon+1); - pdd.instance = instance; - pdd.action = action; - - return Result.ok(pdd); - } else { - return Result.err(Result.ERR_BadData,"Could not extract ns and type from " + type); - } - } else { - Result<NsDAO.Data> rnd = deriveNs(trans, type); - if (rnd.isOK()) { - return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type), - instance, action)); - } else { - return Result.err(rnd); - } - } + if(type.indexOf('@') >= 0) { + int colon = type.indexOf(':'); + if(colon>=0) { + PermDAO.Data pdd = new PermDAO.Data(); + pdd.ns = type.substring(0, colon); + pdd.type = type.substring(colon+1); + pdd.instance = instance; + pdd.action = action; + + return Result.ok(pdd); + } else { + return Result.err(Result.ERR_BadData,"Could not extract ns and type from " + type); + } + } else { + Result<NsDAO.Data> rnd = deriveNs(trans, type); + if (rnd.isOK()) { + return Result.ok(new PermDAO.Data(new NsSplit(rnd.value, type), + instance, action)); + } else { + return Result.err(rnd); + } + } } /** @@ -357,38 +357,38 @@ public class Question { } public Result<List<PermDAO.Data>> getPermsByType(AuthzTrans trans, String type) { - if(type.indexOf('@') >= 0) { - int colon = type.indexOf(':'); - if(colon>=0) { - return permDAO.readByType(trans, type.substring(0, colon),type.substring(colon+1)); - } else { - return Result.err(Result.ERR_BadData, "%s is malformed",type); - } - } else { - Result<NsSplit> nss = deriveNsSplit(trans, type); - if (nss.notOK()) { - return Result.err(nss); - } - return permDAO.readByType(trans, nss.value.ns, nss.value.name); - } + if(type.indexOf('@') >= 0) { + int colon = type.indexOf(':'); + if(colon>=0) { + return permDAO.readByType(trans, type.substring(0, colon),type.substring(colon+1)); + } else { + return Result.err(Result.ERR_BadData, "%s is malformed",type); + } + } else { + Result<NsSplit> nss = deriveNsSplit(trans, type); + if (nss.notOK()) { + return Result.err(nss); + } + return permDAO.readByType(trans, nss.value.ns, nss.value.name); + } } public Result<List<PermDAO.Data>> getPermsByName(AuthzTrans trans, String type, String instance, String action) { - if(type.indexOf('@') >= 0) { - int colon = type.indexOf(':'); - if(colon>=0) { - return permDAO.read(trans, type.substring(0, colon),type.substring(colon+1), instance,action); - } else { - return Result.err(Result.ERR_BadData, "%s is malformed",type); - } - } else { - Result<NsSplit> nss = deriveNsSplit(trans, type); - if (nss.notOK()) { - return Result.err(nss); - } - - return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action); - } + if(type.indexOf('@') >= 0) { + int colon = type.indexOf(':'); + if(colon>=0) { + return permDAO.read(trans, type.substring(0, colon),type.substring(colon+1), instance,action); + } else { + return Result.err(Result.ERR_BadData, "%s is malformed",type); + } + } else { + Result<NsSplit> nss = deriveNsSplit(trans, type); + if (nss.notOK()) { + return Result.err(nss); + } + + return permDAO.read(trans, nss.value.ns, nss.value.name, instance,action); + } } public Result<List<PermDAO.Data>> getPermsByRole(AuthzTrans trans, String role, boolean lookup) { @@ -435,13 +435,13 @@ public class Question { } public Result<List<RoleDAO.Data>> getRolesByName(AuthzTrans trans, String role) { - if(role.startsWith(trans.user()) ) { - if(role.endsWith(":user")) { - return roleDAO.read(trans,trans.user(), "user"); - } else { - return Result.err(Result.ERR_BadData,"%s is a badly formatted role",role); - } - } + if(role.startsWith(trans.user()) ) { + if(role.endsWith(":user")) { + return roleDAO.read(trans,trans.user(), "user"); + } else { + return Result.err(Result.ERR_BadData,"%s is a badly formatted role",role); + } + } Result<NsSplit> nss = deriveNsSplit(trans, role); if (nss.notOK()) { return Result.err(nss); @@ -619,9 +619,9 @@ public class Question { } public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user, RoleDAO.Data rdd, Access access) { - if(trans.user().equals(rdd.ns)) { - return Result.ok((NsDAO.Data)null); - } + if(trans.user().equals(rdd.ns)) { + return Result.ok((NsDAO.Data)null); + } Result<NsDAO.Data> rnsd = deriveNs(trans, rdd.ns); if (rnsd.isOK()) { return mayUser(trans, user, rnsd.value, rdd, access); @@ -676,17 +676,17 @@ public class Question { } public Result<NsDAO.Data> mayUser(AuthzTrans trans, String user,PermDAO.Data pdd, Access access) { - if(pdd.ns.indexOf('@')>-1) { - if(user.equals(pdd.ns) || isGranted(trans,user,Define.ROOT_NS(),"access",pdd.instance,READ)) { - NsDAO.Data ndd = new NsDAO.Data(); - ndd.name = user; - ndd.type = NsDAO.USER; - ndd.parent = ""; - return Result.ok(ndd); - } else { - return Result.err(Result.ERR_Security,"Only a User may modify User"); - } - } + if(pdd.ns.indexOf('@')>-1) { + if(user.equals(pdd.ns) || isGranted(trans,user,Define.ROOT_NS(),"access",pdd.instance,READ)) { + NsDAO.Data ndd = new NsDAO.Data(); + ndd.name = user; + ndd.type = NsDAO.USER; + ndd.parent = ""; + return Result.ok(ndd); + } else { + return Result.err(Result.ERR_Security,"Only a User may modify User"); + } + } Result<NsDAO.Data> rnsd = deriveNs(trans, pdd.ns); if (rnsd.isOK()) { return mayUser(trans, user, rnsd.value, pdd, access); @@ -885,7 +885,7 @@ public class Question { } } if (cddl.size()>1) { - Collections.sort(cddl, (a, b) -> b.expires.compareTo(a.expires)); + Collections.sort(cddl, (a, b) -> b.expires.compareTo(a.expires)); } } else { cddl = result.value; @@ -945,13 +945,13 @@ public class Question { rv = Result.err(Status.ERR_Security, "Credentials expired %s",Chrono.utcStamp(expired)); } else { - if (debug==null && alwaysSpecial) { - debug = new StringBuilder(); - } - if (debug!=null) { - debug.append(trans.env().encryptor().encrypt(new String(cred))); - rv = Result.err(Status.ERR_Security,String.format("invalid password - %s",debug.toString())); - } + if (debug==null && alwaysSpecial) { + debug = new StringBuilder(); + } + if (debug!=null) { + debug.append(trans.env().encryptor().encrypt(new String(cred))); + rv = Result.err(Status.ERR_Security,String.format("invalid password - %s",debug.toString())); + } } } } else { @@ -1005,14 +1005,14 @@ public class Question { } } else if (cred.type==CredDAO.FQI) { - cred.cred = null; - return Result.ok(cred); + cred.cred = null; + return Result.ok(cred); } return Result.err(Status.ERR_Security,"invalid/unreadable credential"); } public Result<Boolean> userCredCheck(AuthzTrans trans, CredDAO.Data orig, final byte[] raw) { - Result<Boolean> rv; + Result<Boolean> rv; TimeTaken tt = trans.start("CheckCred Cred", Env.SUB); try { switch(orig.type) { @@ -1231,11 +1231,11 @@ public class Question { Result<List<UserRoleDAO.Data>> rur = userRoleDAO.read(trans, user,ns+DOT_ADMIN); if (rur.isOKhasData()) { Date now = new Date(); - for (UserRoleDAO.Data urdd : rur.value){ - if (urdd.expires.after(now)) { - return true; - } - } + for (UserRoleDAO.Data urdd : rur.value){ + if (urdd.expires.after(now)) { + return true; + } + } }; return false; } 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 27d5df74..bd297e7d 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 @@ -73,15 +73,15 @@ public class DirectAAFLocator extends AbsAAFLocator<AuthzTrans> { } try { - String aaf_url; - if(name.indexOf('.')>=0) { - aaf_url = "https://"+Config.AAF_LOCATE_URL_TAG+'/'+name+':'+version; - } else { - aaf_url = "https://"+Config.AAF_LOCATE_URL_TAG+"/%CNS.%NS."+name+':'+version; - } - RegistrationPropHolder rph = new RegistrationPropHolder(access,0); - aaf_url = rph.replacements(getClass().getSimpleName(),aaf_url, null,null); - access.printf(Level.INIT,"Creating DirectAAFLocator to %s",aaf_url); + String aaf_url; + if(name.indexOf('.')>=0) { + aaf_url = "https://"+Config.AAF_LOCATE_URL_TAG+'/'+name+':'+version; + } else { + aaf_url = "https://"+Config.AAF_LOCATE_URL_TAG+"/%CNS.%NS."+name+':'+version; + } + RegistrationPropHolder rph = new RegistrationPropHolder(access,0); + aaf_url = rph.replacements(getClass().getSimpleName(),aaf_url, null,null); + access.printf(Level.INIT,"Creating DirectAAFLocator to %s",aaf_url); uri = new URI(aaf_url); } catch (URISyntaxException | UnknownHostException | CadiException e) { throw new LocatorException(e); 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 3c7d873e..bdeb77f3 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 @@ -52,10 +52,10 @@ public class DirectAAFUserPass implements CredVal { @Override public boolean validate(String user, Type type, byte[] pass, Object state) { - if(user==null || type==null || pass==null) { - return false; - } - + if(user==null || type==null || pass==null) { + return false; + } + try { AuthzTrans trans; boolean transfer = false; @@ -74,7 +74,7 @@ public class DirectAAFUserPass implements CredVal { } Result<Date> result = question.doesUserCredMatch(trans, user, pass); if(transfer) { - ((HttpServletRequest)state).setAttribute("CRED_TAG", trans.getTag()); + ((HttpServletRequest)state).setAttribute("CRED_TAG", trans.getTag()); } trans.logAuditTrail(env.debug()); switch(result.status) { 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 99421097..ce9d5930 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 @@ -41,54 +41,54 @@ public class DirectRegistrar implements Registrant<AuthzEnv> { private LocateDAO ldao; private List<LocateDAO.Data> ldd; public DirectRegistrar(Access access, LocateDAO ldao, int port) throws CadiException { - this.ldao = ldao; + this.ldao = ldao; ldd = new ArrayList<>(); RegistrationCreator rc = new RegistrationCreator(access); MgmtEndpoints mes = rc.create(port); for(MgmtEndpoint me : mes.getMgmtEndpoint()) { - ldd.add(convert(me)); + ldd.add(convert(me)); } } private LocateDAO.Data convert(MgmtEndpoint me) { - LocateDAO.Data out = new LocateDAO.Data(); - out.name=me.getName(); - out.hostname=me.getHostname(); - out.latitude=me.getLatitude(); - out.longitude=me.getLongitude(); - out.major=me.getMajor(); - out.minor=me.getMinor(); - out.pkg=me.getPkg(); - out.patch=me.getPatch(); - out.port=me.getPort(); - out.protocol=me.getProtocol(); - out.subprotocol(true).addAll(me.getSubprotocol()); -// out.port_key = UUID.randomUUID(); - return out; - } + LocateDAO.Data out = new LocateDAO.Data(); + out.name=me.getName(); + out.hostname=me.getHostname(); + out.latitude=me.getLatitude(); + out.longitude=me.getLongitude(); + out.major=me.getMajor(); + out.minor=me.getMinor(); + out.pkg=me.getPkg(); + out.patch=me.getPatch(); + out.port=me.getPort(); + out.protocol=me.getProtocol(); + out.subprotocol(true).addAll(me.getSubprotocol()); +// out.port_key = UUID.randomUUID(); + return out; + } - @Override + @Override public Result<Void> update(AuthzEnv env) { - AuthzTrans trans = env.newTransNoAvg(); - StringBuilder sb = null; - for(LocateDAO.Data ld : ldd) { - org.onap.aaf.auth.layer.Result<Void> dr = ldao.update(trans, ld); - if (dr.notOK()) { - if(sb == null) { - sb = new StringBuilder(dr.errorString()); - } else { - sb.append(';'); - sb.append(dr.errorString()); - } - } - } - - if(sb==null) { - return Result.ok(200, null); - } else { - return Result.err(503, sb.toString()); - } + AuthzTrans trans = env.newTransNoAvg(); + StringBuilder sb = null; + for(LocateDAO.Data ld : ldd) { + org.onap.aaf.auth.layer.Result<Void> dr = ldao.update(trans, ld); + if (dr.notOK()) { + if(sb == null) { + sb = new StringBuilder(dr.errorString()); + } else { + sb.append(';'); + sb.append(dr.errorString()); + } + } + } + + if(sb==null) { + return Result.ok(200, null); + } else { + return Result.err(503, sb.toString()); + } } /* (non-Javadoc) @@ -96,25 +96,25 @@ public class DirectRegistrar implements Registrant<AuthzEnv> { */ @Override public Result<Void> cancel(AuthzEnv env) { - AuthzTrans trans = env.newTransNoAvg(); - StringBuilder sb = null; - for(LocateDAO.Data ld : ldd) { + AuthzTrans trans = env.newTransNoAvg(); + StringBuilder sb = null; + for(LocateDAO.Data ld : ldd) { org.onap.aaf.auth.layer.Result<Void> dr = ldao.delete(trans, ld, false); - if (dr.notOK()) { - if(sb == null) { - sb = new StringBuilder(dr.errorString()); - } else { - sb.append(';'); - sb.append(dr.errorString()); - } - } - } - - if(sb==null) { - return Result.ok(200, null); - } else { - return Result.err(503, sb.toString()); - } + if (dr.notOK()) { + if(sb == null) { + sb = new StringBuilder(dr.errorString()); + } else { + sb.append(';'); + sb.append(dr.errorString()); + } + } + } + + if(sb==null) { + return Result.ok(200, null); + } else { + return Result.err(503, sb.toString()); + } } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java index 0ee0ce8f..c1592bdb 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/JU_DAOException.java @@ -32,35 +32,35 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.modules.junit4.PowerMockRunner; public class JU_DAOException { - DAOException daoException; + DAOException daoException; String message = "message"; Throwable cause; @Before public void setUp(){ - daoException = new DAOException(); + daoException = new DAOException(); } @Test public void testNoArgConstructor(){ - assertNull(daoException.getMessage()); + assertNull(daoException.getMessage()); } @Test public void testOneArgConstructorMsg(){ - daoException = new DAOException("test message"); - assertTrue("test message".equalsIgnoreCase(daoException.getMessage())); + daoException = new DAOException("test message"); + assertTrue("test message".equalsIgnoreCase(daoException.getMessage())); } @Test public void testOneArgConstructorThrowable(){ - daoException = new DAOException(new Throwable()); - assertTrue("java.lang.Throwable".equalsIgnoreCase(daoException.getMessage())); + daoException = new DAOException(new Throwable()); + assertTrue("java.lang.Throwable".equalsIgnoreCase(daoException.getMessage())); } @Test public void testTwoArgConstructor(){ - daoException = new DAOException("test message", new Throwable()); - assertTrue("test message".equalsIgnoreCase(daoException.getMessage())); + daoException = new DAOException("test message", new Throwable()); + assertTrue("test message".equalsIgnoreCase(daoException.getMessage())); } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCertDAOTest.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCertDAOTest.java index 5be0f576..de004fd5 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCertDAOTest.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCertDAOTest.java @@ -32,26 +32,26 @@ import org.onap.aaf.auth.env.AuthzTrans; public class JU_CachedCertDAOTest { - private long expiresIn; - private CIDAO<AuthzTrans> info; - @Mock - private CertDAO dao; - private AuthzTrans trans; - - @Before - public void setUp() throws Exception { - initMocks(this); - } - - @Test - public void test() { - CachedCertDAO ccDao = new CachedCertDAO(dao, info, expiresIn); - - ccDao.readID(trans, "id"); - ccDao.readX500(trans, "x500"); - - verify(dao).readID(trans, "id"); - verify(dao).readX500(trans, "x500"); - } + private long expiresIn; + private CIDAO<AuthzTrans> info; + @Mock + private CertDAO dao; + private AuthzTrans trans; + + @Before + public void setUp() throws Exception { + initMocks(this); + } + + @Test + public void test() { + CachedCertDAO ccDao = new CachedCertDAO(dao, info, expiresIn); + + ccDao.readID(trans, "id"); + ccDao.readX500(trans, "x500"); + + verify(dao).readID(trans, "id"); + verify(dao).readX500(trans, "x500"); + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCredDAOTest.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCredDAOTest.java index 06285357..7f5ed85c 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCredDAOTest.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedCredDAOTest.java @@ -39,32 +39,32 @@ import org.onap.aaf.auth.layer.Result; public class JU_CachedCredDAOTest { - @Mock - private CIDAO<AuthzTrans> info; - @Mock - private CredDAO dao; - private AuthzTrans trans; - @Mock - private Result<List<Data>> value; + @Mock + private CIDAO<AuthzTrans> info; + @Mock + private CredDAO dao; + private AuthzTrans trans; + @Mock + private Result<List<Data>> value; - @Before - public void setUp() throws Exception { - initMocks(this); + @Before + public void setUp() throws Exception { + initMocks(this); - when(dao.readID(trans, "id")).thenReturn(value); - } + when(dao.readID(trans, "id")).thenReturn(value); + } - @Test - public void testOk() { - when(value.isOK()).thenReturn(false); - CachedCredDAO ccDao = new CachedCredDAO(dao, info, 100l); + @Test + public void testOk() { + when(value.isOK()).thenReturn(false); + CachedCredDAO ccDao = new CachedCredDAO(dao, info, 100l); - ccDao.readNS(trans, "ns"); - Result<List<Data>> result = ccDao.readID(trans, "id"); + ccDao.readNS(trans, "ns"); + Result<List<Data>> result = ccDao.readID(trans, "id"); - assertEquals(result.status, Status.OK); - verify(dao).readNS(trans, "ns"); - verify(dao).readID(trans, "id"); - } + assertEquals(result.status, Status.OK); + verify(dao).readNS(trans, "ns"); + verify(dao).readID(trans, "id"); + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedNSDAOTest.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedNSDAOTest.java index b945b36e..064b985c 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedNSDAOTest.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedNSDAOTest.java @@ -32,23 +32,23 @@ import org.onap.aaf.auth.env.AuthzTrans; public class JU_CachedNSDAOTest { - private long expiresIn; - private CIDAO<AuthzTrans> info; - @Mock - private NsDAO dao; - private AuthzTrans trans; + private long expiresIn; + private CIDAO<AuthzTrans> info; + @Mock + private NsDAO dao; + private AuthzTrans trans; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void test() { - CachedNSDAO ccDao = new CachedNSDAO(dao, info, expiresIn); + @Test + public void test() { + CachedNSDAO ccDao = new CachedNSDAO(dao, info, expiresIn); - assertNotNull(ccDao); + assertNotNull(ccDao); - } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedPermDAOTest.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedPermDAOTest.java index 66c32a7b..46bbc7e6 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedPermDAOTest.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedPermDAOTest.java @@ -43,28 +43,28 @@ import org.onap.aaf.misc.env.LogTarget; public class JU_CachedPermDAOTest { - @Mock - private CIDAO<AuthzTrans> info; - @Mock - private PermDAO dao; - - @Mock - RoleDAO.Data role; - - @Mock - private PermDAO.Data perm; - - @Mock - private AuthzTrans trans; - @Mock - private Result<List<PermDAO.Data>> value; - - @Before - public void setUp() throws Exception { - initMocks(this); - - when(dao.readNS(trans, "ns")).thenReturn(value); - when(trans.debug()).thenReturn(new LogTarget() { + @Mock + private CIDAO<AuthzTrans> info; + @Mock + private PermDAO dao; + + @Mock + RoleDAO.Data role; + + @Mock + private PermDAO.Data perm; + + @Mock + private AuthzTrans trans; + @Mock + private Result<List<PermDAO.Data>> value; + + @Before + public void setUp() throws Exception { + initMocks(this); + + when(dao.readNS(trans, "ns")).thenReturn(value); + when(trans.debug()).thenReturn(new LogTarget() { @Override public void printf(String fmt, Object... vars) {} @@ -87,80 +87,80 @@ public class JU_CachedPermDAOTest { return true; } }); - } - - @Test - public void testReadNS() { - when(value.isOKhasData()).thenReturn(true); - when(value.isOK()).thenReturn(false); - CachedPermDAO ccDao = new CachedPermDAO(dao, info, 100l); - - Result<List<Data>> result = ccDao.readNS(trans, "ns"); - - assertEquals(result, value); - - when(value.isOKhasData()).thenReturn(false); - - result = ccDao.readNS(trans, "ns"); - - assertEquals(result.status, Status.ERR_PermissionNotFound); - - ccDao.readChildren(trans, "ns", "type"); - - verify(dao).readChildren(trans, "ns", "type"); - } - - @Test - public void testReadByTypeSuccess() { - CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test4",new String[0]); - Mockito.doReturn(retVal1).when(dao).readByType(trans, "test4",""); - Result<List<Data>> retVal = roleDaoObj.readByType(trans, "test4",""); -// System.out.println(retVal.status); - //retVal.status = 0; - assertEquals("1", Integer.toString(retVal.status)); - } - - @Test - public void testReadByTypeFailure() { - CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test3123",new String[0]); - Mockito.doReturn(retVal1).when(dao).readByType(trans, "test3",""); - Result<List<Data>> retVal = roleDaoObj.readByType(trans, "test3",""); - //System.out.println(retVal.status); - assertEquals("23", Integer.toString(retVal.status)); - } - - @Test - public void testAddRole() { - CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10); - Result<Void> retVal1 = new Result<Void>(null,0,"testAddRole",new String[0]); - Mockito.doReturn(retVal1).when(info).touch(trans, null,null); - Mockito.doReturn(retVal1).when(dao).addRole(trans, perm,null); - Result<Void> retVal = roleDaoObj.addRole(trans, perm, role); -// System.out.println("ret value is::"+retVal); - assertEquals("testAddRole", retVal.toString()); - } - - @Test - public void testDelRole() { - CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10); - Result<Void> retVal1 = new Result<Void>(null,0,"testAddRole",new String[0]); - Mockito.doReturn(retVal1).when(info).touch(trans, null,null); - Mockito.doReturn(retVal1).when(dao).delRole(trans, perm,null); - Result<Void> retVal = roleDaoObj.delRole(trans, perm, role); -// System.out.println(retVal); - assertEquals("testAddRole", retVal.toString()); - } - - @Test - public void testAddDescription() { - CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<Void> retVal1 = new Result<Void>(null,0,"test1",new String[0]); - Mockito.doReturn(retVal1).when(dao).addDescription(trans, "","","","",""); - Result<Void> retVal = roleDaoObj.addDescription(trans, "", "","","",""); - //System.out.println(retVal.status); - assertEquals("0", Integer.toString(retVal.status)); - } + } + + @Test + public void testReadNS() { + when(value.isOKhasData()).thenReturn(true); + when(value.isOK()).thenReturn(false); + CachedPermDAO ccDao = new CachedPermDAO(dao, info, 100l); + + Result<List<Data>> result = ccDao.readNS(trans, "ns"); + + assertEquals(result, value); + + when(value.isOKhasData()).thenReturn(false); + + result = ccDao.readNS(trans, "ns"); + + assertEquals(result.status, Status.ERR_PermissionNotFound); + + ccDao.readChildren(trans, "ns", "type"); + + verify(dao).readChildren(trans, "ns", "type"); + } + + @Test + public void testReadByTypeSuccess() { + CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test4",new String[0]); + Mockito.doReturn(retVal1).when(dao).readByType(trans, "test4",""); + Result<List<Data>> retVal = roleDaoObj.readByType(trans, "test4",""); +// System.out.println(retVal.status); + //retVal.status = 0; + assertEquals("1", Integer.toString(retVal.status)); + } + + @Test + public void testReadByTypeFailure() { + CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test3123",new String[0]); + Mockito.doReturn(retVal1).when(dao).readByType(trans, "test3",""); + Result<List<Data>> retVal = roleDaoObj.readByType(trans, "test3",""); + //System.out.println(retVal.status); + assertEquals("23", Integer.toString(retVal.status)); + } + + @Test + public void testAddRole() { + CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10); + Result<Void> retVal1 = new Result<Void>(null,0,"testAddRole",new String[0]); + Mockito.doReturn(retVal1).when(info).touch(trans, null,null); + Mockito.doReturn(retVal1).when(dao).addRole(trans, perm,null); + Result<Void> retVal = roleDaoObj.addRole(trans, perm, role); +// System.out.println("ret value is::"+retVal); + assertEquals("testAddRole", retVal.toString()); + } + + @Test + public void testDelRole() { + CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10); + Result<Void> retVal1 = new Result<Void>(null,0,"testAddRole",new String[0]); + Mockito.doReturn(retVal1).when(info).touch(trans, null,null); + Mockito.doReturn(retVal1).when(dao).delRole(trans, perm,null); + Result<Void> retVal = roleDaoObj.delRole(trans, perm, role); +// System.out.println(retVal); + assertEquals("testAddRole", retVal.toString()); + } + + @Test + public void testAddDescription() { + CachedPermDAO roleDaoObj =new CachedPermDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<Void> retVal1 = new Result<Void>(null,0,"test1",new String[0]); + Mockito.doReturn(retVal1).when(dao).addDescription(trans, "","","","",""); + Result<Void> retVal = roleDaoObj.addDescription(trans, "", "","","",""); + //System.out.println(retVal.status); + assertEquals("0", Integer.toString(retVal.status)); + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedRoleDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedRoleDAO.java index f2bdad2d..4d9527c5 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedRoleDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedRoleDAO.java @@ -45,25 +45,25 @@ import org.onap.aaf.misc.env.LogTarget; @RunWith(MockitoJUnitRunner.class) public class JU_CachedRoleDAO { - @Mock - RoleDAO dao; - - @Mock - CIDAO<AuthzTrans> info; - - @Mock - AuthzTransImpl trans; - - @Mock - RoleDAO.Data data; - - @Mock - PermDAO.Data permData; - - @Before - public void setUp() throws Exception { - initMocks(this); - when(trans.debug()).thenReturn(new LogTarget() { + @Mock + RoleDAO dao; + + @Mock + CIDAO<AuthzTrans> info; + + @Mock + AuthzTransImpl trans; + + @Mock + RoleDAO.Data data; + + @Mock + PermDAO.Data permData; + + @Before + public void setUp() throws Exception { + initMocks(this); + when(trans.debug()).thenReturn(new LogTarget() { @Override public void printf(String fmt, Object... vars) {} @@ -86,90 +86,90 @@ public class JU_CachedRoleDAO { return true; } }); - } - - @Test - public void testReadNameSuccess() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test4",new String[0]); - roleDaoObj.invalidate(""); - Mockito.doReturn(retVal1).when(dao).readName(trans, "test4"); -// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); - Result<List<Data>> retVal = roleDaoObj.readName(trans, "test4"); -// System.out.println(retVal.status); - //retVal.status = 0; - assertEquals("1", Integer.toString(retVal.status)); - } - - @Test - public void testReadNameFailure() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test3123",new String[0]); - Mockito.doReturn(retVal1).when(dao).readName(trans, "test3"); -// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); - Result<List<Data>> retVal = roleDaoObj.readName(trans, "test3"); -// System.out.println(retVal.status); - assertEquals("22", Integer.toString(retVal.status)); - } - @Test - public void testReadNSSuccess() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(retVal1).when(dao).readNS(trans, ""); -// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); - Result<List<Data>> retVal = roleDaoObj.readNS(trans, ""); -// System.out.println(retVal.status); - assertEquals("1", Integer.toString(retVal.status)); - } - @Test - public void testReadNSFailure() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test1",new String[0]); - Mockito.doReturn(retVal1).when(dao).readNS(trans, ""); -// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); - Result<List<Data>> retVal = roleDaoObj.readNS(trans, ""); -// System.out.println(retVal.status); - assertEquals("22", Integer.toString(retVal.status)); - } - - @Test - public void testReadChildren() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test1",new String[0]); - Mockito.doReturn(retVal1).when(dao).readChildren(trans, "",""); - Result<List<Data>> retVal = roleDaoObj.readChildren(trans, "", ""); - //System.out.println(retVal.status); - assertEquals("0", Integer.toString(retVal.status)); - } - - @Test - public void testAddPerm() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10); - Result<Void> retVal1 = new Result<Void>(null,0,"testAddPerm",new String[0]); - Mockito.doReturn(retVal1).when(info).touch(trans, null,null); - Mockito.doReturn(retVal1).when(dao).addPerm(trans, data,permData); - Result<Void> retVal = roleDaoObj.addPerm(trans, data, permData); - assertEquals("testAddPerm", retVal.toString()); - } - - @Test - public void testDelPerm() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10); - Result<Void> retVal1 = new Result<Void>(null,0,"testAddPerm",new String[0]); - Mockito.doReturn(retVal1).when(info).touch(trans, null,null); - Mockito.doReturn(retVal1).when(dao).delPerm(trans, data,permData); - Result<Void> retVal = roleDaoObj.delPerm(trans, data, permData); - System.out.println(retVal); - assertEquals("testAddPerm", retVal.toString()); - } + } + + @Test + public void testReadNameSuccess() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test4",new String[0]); + roleDaoObj.invalidate(""); + Mockito.doReturn(retVal1).when(dao).readName(trans, "test4"); +// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); + Result<List<Data>> retVal = roleDaoObj.readName(trans, "test4"); +// System.out.println(retVal.status); + //retVal.status = 0; + assertEquals("1", Integer.toString(retVal.status)); + } + + @Test + public void testReadNameFailure() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test3123",new String[0]); + Mockito.doReturn(retVal1).when(dao).readName(trans, "test3"); +// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); + Result<List<Data>> retVal = roleDaoObj.readName(trans, "test3"); +// System.out.println(retVal.status); + assertEquals("22", Integer.toString(retVal.status)); + } + @Test + public void testReadNSSuccess() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(retVal1).when(dao).readNS(trans, ""); +// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); + Result<List<Data>> retVal = roleDaoObj.readNS(trans, ""); +// System.out.println(retVal.status); + assertEquals("1", Integer.toString(retVal.status)); + } + @Test + public void testReadNSFailure() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test1",new String[0]); + Mockito.doReturn(retVal1).when(dao).readNS(trans, ""); +// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); + Result<List<Data>> retVal = roleDaoObj.readNS(trans, ""); +// System.out.println(retVal.status); + assertEquals("22", Integer.toString(retVal.status)); + } + + @Test + public void testReadChildren() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test1",new String[0]); + Mockito.doReturn(retVal1).when(dao).readChildren(trans, "",""); + Result<List<Data>> retVal = roleDaoObj.readChildren(trans, "", ""); + //System.out.println(retVal.status); + assertEquals("0", Integer.toString(retVal.status)); + } + + @Test + public void testAddPerm() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10); + Result<Void> retVal1 = new Result<Void>(null,0,"testAddPerm",new String[0]); + Mockito.doReturn(retVal1).when(info).touch(trans, null,null); + Mockito.doReturn(retVal1).when(dao).addPerm(trans, data,permData); + Result<Void> retVal = roleDaoObj.addPerm(trans, data, permData); + assertEquals("testAddPerm", retVal.toString()); + } + + @Test + public void testDelPerm() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10); + Result<Void> retVal1 = new Result<Void>(null,0,"testAddPerm",new String[0]); + Mockito.doReturn(retVal1).when(info).touch(trans, null,null); + Mockito.doReturn(retVal1).when(dao).delPerm(trans, data,permData); + Result<Void> retVal = roleDaoObj.delPerm(trans, data, permData); + System.out.println(retVal); + assertEquals("testAddPerm", retVal.toString()); + } - @Test - public void testAddDescription() { - CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<Void> retVal1 = new Result<Void>(null,0,"test1",new String[0]); - Mockito.doReturn(retVal1).when(dao).addDescription(trans, "","",""); - Result<Void> retVal = roleDaoObj.addDescription(trans, "", "",""); - //System.out.println(retVal.status); - assertEquals("0", Integer.toString(retVal.status)); - } + @Test + public void testAddDescription() { + CachedRoleDAO roleDaoObj =new CachedRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<Void> retVal1 = new Result<Void>(null,0,"test1",new String[0]); + Mockito.doReturn(retVal1).when(dao).addDescription(trans, "","",""); + Result<Void> retVal = roleDaoObj.addDescription(trans, "", "",""); + //System.out.println(retVal.status); + assertEquals("0", Integer.toString(retVal.status)); + } }
\ No newline at end of file diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedUserRoleDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedUserRoleDAO.java index 8dcf8e44..053fc889 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedUserRoleDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cached/JU_CachedUserRoleDAO.java @@ -48,25 +48,25 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_CachedUserRoleDAO { - @Mock - UserRoleDAO dao; - - @Mock - CIDAO<AuthzTrans> info; - - @Mock - AuthzTransImpl trans; - - @Mock - RoleDAO.Data data; - - @Mock - PermDAO.Data permData; - - @Before - public void setUp() throws Exception { - initMocks(this); - when(trans.debug()).thenReturn(new LogTarget() { + @Mock + UserRoleDAO dao; + + @Mock + CIDAO<AuthzTrans> info; + + @Mock + AuthzTransImpl trans; + + @Mock + RoleDAO.Data data; + + @Mock + PermDAO.Data permData; + + @Before + public void setUp() throws Exception { + initMocks(this); + when(trans.debug()).thenReturn(new LogTarget() { @Override public void printf(String fmt, Object... vars) {} @@ -89,92 +89,92 @@ public class JU_CachedUserRoleDAO { return true; } }); - } - - private class TaggedPrincipalStub extends TaggedPrincipal { - String name="TaggedPrincipalStub"; + } + + private class TaggedPrincipalStub extends TaggedPrincipal { + String name="TaggedPrincipalStub"; public TaggedPrincipalStub() { super(); } public TaggedPrincipalStub(final TagLookup tl) { super(tl); } @Override public String getName() { return name; } @Override public String tag() { return null; } } - - @Test - public void testReadName() { - CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 10L); - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test4",new String[0]); - Mockito.doReturn(retVal1).when(dao).readByUser(trans, "test4"); -// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); - Result<List<Data>> retVal = roleDaoObj.readByUser(trans, "test4"); - //System.out.println(retVal.status); - //retVal.status = 0; - assertEquals("25", Integer.toString(retVal.status)); - } - - @Test - public void testReadNameUser() { - CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 10L); - Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"TaggedPrincipalStub",new String[0]); - AuthzEnv env = Mockito.mock(AuthzEnv.class); - AuthzTransImpl transTemp = new AuthzTransImpl(env) { - @Override - public<T> T get(Slot slot, T deflt) { - Object o=null; - return (T)o; - } - - }; - transTemp.setUser(new TaggedPrincipalStub()); - Mockito.doReturn(retVal1).when(info).touch(trans, null,null); - Mockito.doReturn(retVal1).when(dao).readByUser(transTemp, "TaggedPrincipalStub"); - roleDaoObj.invalidate("TaggedPrincipalStub"); - Result<List<Data>> retVal = roleDaoObj.readByUser(transTemp, "TaggedPrincipalStub"); -// System.out.println(retVal.status); - assertEquals("1", Integer.toString(retVal.status)); - } - - @Test - public void testReadByRoleSuccess() { - CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 0);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(retVal1).when(dao).readByRole(trans, ""); - roleDaoObj.invalidate(""); - Result<List<Data>> retVal = roleDaoObj.readByRole(trans, ""); - //System.out.println(retVal.status); - assertEquals("1", Integer.toString(retVal.status)); - } - @Test - public void testReadByRoleFailure() { - CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 0);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test1",new String[0]); - Mockito.doReturn(retVal1).when(dao).readByRole(trans, ""); - roleDaoObj.invalidate(""); - Result<List<Data>> retVal = roleDaoObj.readByRole(trans, ""); - //System.out.println(retVal.status); - assertEquals("25", Integer.toString(retVal.status)); - } - - @Test - public void testReadUserInRole() { - CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"TaggedPrincipalStub",new String[0]); - AuthzEnv env = Mockito.mock(AuthzEnv.class); - AuthzTransImpl transTemp = new AuthzTransImpl(env) { - @Override - public<T> T get(Slot slot, T deflt) { - Object o=null; - return (T)o; - } - - }; - transTemp.setUser(new TaggedPrincipalStub()); - Mockito.doReturn(retVal1).when(info).touch(trans, null,null); - Mockito.doReturn(retVal1).when(dao).readByUserRole(transTemp, "",""); - Mockito.doReturn(retVal1).when(dao).readByUser(transTemp, "TaggedPrincipalStub"); - Result<List<Data>> retVal = roleDaoObj.readUserInRole(transTemp, "TaggedPrincipalStub",""); - //System.out.println(retVal.status); - assertEquals("25", Integer.toString(retVal.status)); - } - + + @Test + public void testReadName() { + CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 10L); + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test4",new String[0]); + Mockito.doReturn(retVal1).when(dao).readByUser(trans, "test4"); +// Mockito.when(roleDaoObj.get(Mockito.any(), Mockito.any(String.class), Mockito.any())).thenReturn(retVal1); + Result<List<Data>> retVal = roleDaoObj.readByUser(trans, "test4"); + //System.out.println(retVal.status); + //retVal.status = 0; + assertEquals("25", Integer.toString(retVal.status)); + } + + @Test + public void testReadNameUser() { + CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 10L); + Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"TaggedPrincipalStub",new String[0]); + AuthzEnv env = Mockito.mock(AuthzEnv.class); + AuthzTransImpl transTemp = new AuthzTransImpl(env) { + @Override + public<T> T get(Slot slot, T deflt) { + Object o=null; + return (T)o; + } + + }; + transTemp.setUser(new TaggedPrincipalStub()); + Mockito.doReturn(retVal1).when(info).touch(trans, null,null); + Mockito.doReturn(retVal1).when(dao).readByUser(transTemp, "TaggedPrincipalStub"); + roleDaoObj.invalidate("TaggedPrincipalStub"); + Result<List<Data>> retVal = roleDaoObj.readByUser(transTemp, "TaggedPrincipalStub"); +// System.out.println(retVal.status); + assertEquals("1", Integer.toString(retVal.status)); + } + + @Test + public void testReadByRoleSuccess() { + CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 0);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(retVal1).when(dao).readByRole(trans, ""); + roleDaoObj.invalidate(""); + Result<List<Data>> retVal = roleDaoObj.readByRole(trans, ""); + //System.out.println(retVal.status); + assertEquals("1", Integer.toString(retVal.status)); + } + @Test + public void testReadByRoleFailure() { + CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 0);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"test1",new String[0]); + Mockito.doReturn(retVal1).when(dao).readByRole(trans, ""); + roleDaoObj.invalidate(""); + Result<List<Data>> retVal = roleDaoObj.readByRole(trans, ""); + //System.out.println(retVal.status); + assertEquals("25", Integer.toString(retVal.status)); + } + + @Test + public void testReadUserInRole() { + CachedUserRoleDAO roleDaoObj =new CachedUserRoleDAO(dao,info, 10);//Mockito.mock(CachedRoleDAO.class);// + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"TaggedPrincipalStub",new String[0]); + AuthzEnv env = Mockito.mock(AuthzEnv.class); + AuthzTransImpl transTemp = new AuthzTransImpl(env) { + @Override + public<T> T get(Slot slot, T deflt) { + Object o=null; + return (T)o; + } + + }; + transTemp.setUser(new TaggedPrincipalStub()); + Mockito.doReturn(retVal1).when(info).touch(trans, null,null); + Mockito.doReturn(retVal1).when(dao).readByUserRole(transTemp, "",""); + Mockito.doReturn(retVal1).when(dao).readByUser(transTemp, "TaggedPrincipalStub"); + Result<List<Data>> retVal = roleDaoObj.readUserInRole(transTemp, "TaggedPrincipalStub",""); + //System.out.println(retVal.status); + assertEquals("25", Integer.toString(retVal.status)); + } + }
\ No newline at end of file diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ApprovalDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ApprovalDAO.java index 79b4aeb5..2b303673 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ApprovalDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ApprovalDAO.java @@ -56,315 +56,315 @@ import com.google.common.util.concurrent.ListenableFuture; public class JU_ApprovalDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - } - - @Test - public void testInit() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - ApprovalDAO.Data data = new ApprovalDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl CREATE", data); - - ApprovalDAOImpl daoObj = new ApprovalDAOImpl(trans, cluster, "test",data, createPS); -// data.id - Result<Data> retVal = daoObj.create(trans, data); - assertTrue(retVal.status == 0); - - rs = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl CREATE", data); - retVal = daoObj.create(trans, data); - assertTrue(retVal.status == 1); - - Result<List<ApprovalDAO.Data>> rs1 = new Result<List<ApprovalDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{"testUser"}); - Result<List<ApprovalDAO.Data>> retVal1 = daoObj.readByUser(trans, "testUser"); - assertNull(retVal1); - - Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{"testApprover"}); - retVal1 = daoObj.readByApprover(trans, "testApprover"); - assertNull(retVal1); - - Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{new UUID(0, 0)}); - retVal1 = daoObj.readByTicket(trans, new UUID(0, 0)); - assertNull(retVal1); - - Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{"testStatus"}); - retVal1 = daoObj.readByStatus(trans, "testStatus"); - assertNull(retVal1); - } - - @Test - public void testDelete() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - ApprovalDAO.Data data = new ApprovalDAO.Data(); + @Mock + Cluster cluster; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + } + + @Test + public void testInit() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + ApprovalDAO.Data data = new ApprovalDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl CREATE", data); + + ApprovalDAOImpl daoObj = new ApprovalDAOImpl(trans, cluster, "test",data, createPS); +// data.id + Result<Data> retVal = daoObj.create(trans, data); + assertTrue(retVal.status == 0); + + rs = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl CREATE", data); + retVal = daoObj.create(trans, data); + assertTrue(retVal.status == 1); + + Result<List<ApprovalDAO.Data>> rs1 = new Result<List<ApprovalDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{"testUser"}); + Result<List<ApprovalDAO.Data>> retVal1 = daoObj.readByUser(trans, "testUser"); + assertNull(retVal1); + + Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{"testApprover"}); + retVal1 = daoObj.readByApprover(trans, "testApprover"); + assertNull(retVal1); + + Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{new UUID(0, 0)}); + retVal1 = daoObj.readByTicket(trans, new UUID(0, 0)); + assertNull(retVal1); + + Mockito.doReturn(rs1).when(createPS).read(trans, "ApprovalDAOImpl CREATE", new Object[]{"testStatus"}); + retVal1 = daoObj.readByStatus(trans, "testStatus"); + assertNull(retVal1); + } + + @Test + public void testDelete() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + ApprovalDAO.Data data = new ApprovalDAO.Data(); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - PSInfo createPS = Mockito.mock(PSInfo.class); - ResultSet rsObj = new ResultSetImpl(); - Result<ResultSet> rs = new Result<ResultSet>(rsObj,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl READ", data); - Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl DELETE", data); - - ApprovalDAOImpl daoObj = new ApprovalDAOImpl(trans, cluster, "test", createPS, historyDAO); -// data.id - Result<Void> retVal = daoObj.delete(trans, data, true); - assertTrue(retVal.status == 0); - - rs = new Result<ResultSet>(rsObj,1,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl READ", data); - retVal = daoObj.delete(trans, data, true); - assertTrue(retVal.status == 1); - - data.status="approved"; - data.memo="test"; - retVal = daoObj.delete(trans, data, false); - assertTrue(retVal.status == 0); - - daoObj.async(true); - data.status="denied"; - retVal = daoObj.delete(trans, data, false); - assertTrue(retVal.status == 0); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + PSInfo createPS = Mockito.mock(PSInfo.class); + ResultSet rsObj = new ResultSetImpl(); + Result<ResultSet> rs = new Result<ResultSet>(rsObj,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl READ", data); + Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl DELETE", data); + + ApprovalDAOImpl daoObj = new ApprovalDAOImpl(trans, cluster, "test", createPS, historyDAO); +// data.id + Result<Void> retVal = daoObj.delete(trans, data, true); + assertTrue(retVal.status == 0); + + rs = new Result<ResultSet>(rsObj,1,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "ApprovalDAOImpl READ", data); + retVal = daoObj.delete(trans, data, true); + assertTrue(retVal.status == 1); + + data.status="approved"; + data.memo="test"; + retVal = daoObj.delete(trans, data, false); + assertTrue(retVal.status == 0); + + daoObj.async(true); + data.status="denied"; + retVal = daoObj.delete(trans, data, false); + assertTrue(retVal.status == 0); - data.status=null; - retVal = daoObj.delete(trans, data, false); - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - ApprovalDAO.Data data = new ApprovalDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - ApprovalDAOImpl daoObj = new ApprovalDAOImpl(trans, cluster, "test", createPS, historyDAO); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - daoObj.wasModified(trans, CRUD.create, data, new String[] {}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - } - - @Test - public void testSecondConstructor() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - ApprovalDAO.Data data = new ApprovalDAO.Data(); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - - ApprovalDAO daoObj = new ApprovalDAO(trans, historyDAO); - } + data.status=null; + retVal = daoObj.delete(trans, data, false); + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + ApprovalDAO.Data data = new ApprovalDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + ApprovalDAOImpl daoObj = new ApprovalDAOImpl(trans, cluster, "test", createPS, historyDAO); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + daoObj.wasModified(trans, CRUD.create, data, new String[] {}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + } + + @Test + public void testSecondConstructor() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ApprovalDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ApprovalDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + ApprovalDAO.Data data = new ApprovalDAO.Data(); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + + ApprovalDAO daoObj = new ApprovalDAO(trans, historyDAO); + } } class ResultSetImpl implements ResultSet{ - @Override - public boolean isExhausted() { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean isExhausted() { + // TODO Auto-generated method stub + return false; + } - @Override - public boolean isFullyFetched() { - // TODO Auto-generated method stub - return false; - } + @Override + public boolean isFullyFetched() { + // TODO Auto-generated method stub + return false; + } - @Override - public int getAvailableWithoutFetching() { - // TODO Auto-generated method stub - return 0; - } + @Override + public int getAvailableWithoutFetching() { + // TODO Auto-generated method stub + return 0; + } - @Override - public ListenableFuture<ResultSet> fetchMoreResults() { - // TODO Auto-generated method stub - return null; - } + @Override + public ListenableFuture<ResultSet> fetchMoreResults() { + // TODO Auto-generated method stub + return null; + } - @Override - public List<Row> all() { - // TODO Auto-generated method stub - return null; - } + @Override + public List<Row> all() { + // TODO Auto-generated method stub + return null; + } - @Override - public Iterator<Row> iterator() { - // TODO Auto-generated method stub - return null; - } + @Override + public Iterator<Row> iterator() { + // TODO Auto-generated method stub + return null; + } - @Override - public ExecutionInfo getExecutionInfo() { - // TODO Auto-generated method stub - return null; - } + @Override + public ExecutionInfo getExecutionInfo() { + // TODO Auto-generated method stub + return null; + } - @Override - public List<ExecutionInfo> getAllExecutionInfo() { - // TODO Auto-generated method stub - return null; - } + @Override + public List<ExecutionInfo> getAllExecutionInfo() { + // TODO Auto-generated method stub + return null; + } - @Override - public Row one() { - // TODO Auto-generated method stub - Row rowObj = Mockito.mock(Row.class); - Mockito.doReturn(Mockito.mock(ColumnDefinitions.class)).when(rowObj).getColumnDefinitions(); - return rowObj; - } + @Override + public Row one() { + // TODO Auto-generated method stub + Row rowObj = Mockito.mock(Row.class); + Mockito.doReturn(Mockito.mock(ColumnDefinitions.class)).when(rowObj).getColumnDefinitions(); + return rowObj; + } - @Override - public ColumnDefinitions getColumnDefinitions() { - // TODO Auto-generated method stub - return null; - } + @Override + public ColumnDefinitions getColumnDefinitions() { + // TODO Auto-generated method stub + return null; + } - @Override - public boolean wasApplied() { - // TODO Auto-generated method stub - return false; - } - + @Override + public boolean wasApplied() { + // TODO Auto-generated method stub + return false; + } + } class ApprovalDAOImpl extends ApprovalDAO{ - public ApprovalDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,ApprovalDAO.Data data,PSInfo createPS ) { - super(trans, cluster, keyspace); - this.createPS = createPS; - setPs(this, createPS, "psByUser"); - setPs(this, createPS, "psByApprover"); - setPs(this, createPS, "psByTicket"); - setPs(this, createPS, "psByStatus"); - } - - public ApprovalDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS ) { - super(trans, cluster, keyspace); - this.readPS = readPS; - } - - public ApprovalDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS, HistoryDAO historyDAO ) { - super(trans, cluster, keyspace); - this.deletePS = readPS; - this.readPS = readPS; - setHistoryDao(this, historyDAO); - setSession(this, Mockito.mock(Session.class)); - } - - public void setPs(ApprovalDAOImpl approvalDaoObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = ApprovalDAO.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(approvalDaoObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public ApprovalDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,ApprovalDAO.Data data,PSInfo createPS ) { + super(trans, cluster, keyspace); + this.createPS = createPS; + setPs(this, createPS, "psByUser"); + setPs(this, createPS, "psByApprover"); + setPs(this, createPS, "psByTicket"); + setPs(this, createPS, "psByStatus"); + } + + public ApprovalDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS ) { + super(trans, cluster, keyspace); + this.readPS = readPS; + } + + public ApprovalDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS, HistoryDAO historyDAO ) { + super(trans, cluster, keyspace); + this.deletePS = readPS; + this.readPS = readPS; + setHistoryDao(this, historyDAO); + setSession(this, Mockito.mock(Session.class)); + } + + public void setPs(ApprovalDAOImpl approvalDaoObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = ApprovalDAO.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(approvalDaoObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - public void setHistoryDao(ApprovalDAOImpl approvalDaoObj, HistoryDAO historyDAO) { - Field nsDaoField; - try { - nsDaoField = ApprovalDAO.class.getDeclaredField("historyDAO"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(approvalDaoObj, historyDAO); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - public void setSession(ApprovalDAOImpl approvalDaoObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(approvalDaoObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setHistoryDao(ApprovalDAOImpl approvalDaoObj, HistoryDAO historyDAO) { + Field nsDaoField; + try { + nsDaoField = ApprovalDAO.class.getDeclaredField("historyDAO"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(approvalDaoObj, historyDAO); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + public void setSession(ApprovalDAOImpl approvalDaoObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(approvalDaoObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ArtiDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ArtiDAO.java index e6318b99..d6e1fb55 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ArtiDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ArtiDAO.java @@ -55,247 +55,247 @@ import com.datastax.driver.core.Session; public class JU_ArtiDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - } - - @Test - public void testReadByMechID() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ArtiDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ArtiDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - - PSInfo psByMechIdObj = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); -// Mockito.doReturn(rs).when(createPS).exec(trans, "ArtiDAOImpl CREATE", data); - - ArtiDAOImpl daoObj = new ArtiDAOImpl(trans, cluster, "test", psByMechIdObj); - - Result<List<ArtiDAO.Data>> rs1 = new Result<List<ArtiDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psByMechIdObj).read(trans, "ArtiDAOImpl READ", new Object[]{"testMechId"}); - daoObj.readByMechID(trans, "testMechId"); - - rs1 = new Result<List<ArtiDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psByMechIdObj).read(trans, "ArtiDAOImpl READ", new Object[]{"testMachine"}); - daoObj.readByMachine(trans, "testMachine"); + @Mock + Cluster cluster; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + } + + @Test + public void testReadByMechID() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ArtiDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ArtiDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + + PSInfo psByMechIdObj = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); +// Mockito.doReturn(rs).when(createPS).exec(trans, "ArtiDAOImpl CREATE", data); + + ArtiDAOImpl daoObj = new ArtiDAOImpl(trans, cluster, "test", psByMechIdObj); + + Result<List<ArtiDAO.Data>> rs1 = new Result<List<ArtiDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psByMechIdObj).read(trans, "ArtiDAOImpl READ", new Object[]{"testMechId"}); + daoObj.readByMechID(trans, "testMechId"); + + rs1 = new Result<List<ArtiDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psByMechIdObj).read(trans, "ArtiDAOImpl READ", new Object[]{"testMachine"}); + daoObj.readByMachine(trans, "testMachine"); - rs1 = new Result<List<ArtiDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psByMechIdObj).read(trans, "ArtiDAOImpl READ", new Object[]{"testNs"}); - daoObj.readByNs(trans, "testNs"); - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ArtiDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ArtiDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - ArtiDAO.Data data = new ArtiDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - ArtiDAOImpl daoObj = new ArtiDAOImpl(trans, cluster, "test", createPS, historyDAO); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - daoObj.wasModified(trans, CRUD.create, data, new String[] {}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - - data.type(true); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); - - } - @Test - public void testData(){ - ArtiDAO.Data data = new ArtiDAO.Data(); - data.type(true); - data.type(false); - - data.sans(true); - data.sans(false); - data.sans = new TreeSet(); - data.sans(false); - data.sans(true); - - data.expires = new Date(); - data.toString(); - } - - @Test - public void testArtifactLoader(){ - ArtiDAO daoObj = new ArtiDAO(trans, cluster, "test"); - Class<?> innerClass = ArtiDAO.class.getDeclaredClasses()[0]; + rs1 = new Result<List<ArtiDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psByMechIdObj).read(trans, "ArtiDAOImpl READ", new Object[]{"testNs"}); + daoObj.readByNs(trans, "testNs"); + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ArtiDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ArtiDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + ArtiDAO.Data data = new ArtiDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + ArtiDAOImpl daoObj = new ArtiDAOImpl(trans, cluster, "test", createPS, historyDAO); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + daoObj.wasModified(trans, CRUD.create, data, new String[] {}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + + data.type(true); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); + + } + @Test + public void testData(){ + ArtiDAO.Data data = new ArtiDAO.Data(); + data.type(true); + data.type(false); + + data.sans(true); + data.sans(false); + data.sans = new TreeSet(); + data.sans(false); + data.sans(true); + + data.expires = new Date(); + data.toString(); + } + + @Test + public void testArtifactLoader(){ + ArtiDAO daoObj = new ArtiDAO(trans, cluster, "test"); + Class<?> innerClass = ArtiDAO.class.getDeclaredClasses()[0]; Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(10); - Method innnerClassMtd; - - ArtiDAO.Data data = new ArtiDAO.Data(); - Row row = Mockito.mock(Row.class); - innnerClassMtd = innerClass.getMethod("load", new Class[] {ArtiDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {ArtiDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); - - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {ArtiDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - -// DataInputStream in = Mockito.mock(DataInputStream.class); -//// Mockito.doReturn(100).when(in).read(); -//// Mockito.doReturn(100).when(in).readInt(); -// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {ArtiDAO.Data.class, DataInputStream.class }); -// innnerClassMtd.invoke(obj, new Object[] {data, in}); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testSecondConstructor() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ArtiDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ArtiDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - ArtiDAO.Data data = new ArtiDAO.Data(); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - - ArtiDAO daoObj = new ArtiDAO(trans, historyDAO, Mockito.mock(CacheInfoDAO.class)); - } - + Object obj = constructor.newInstance(10); + Method innnerClassMtd; + + ArtiDAO.Data data = new ArtiDAO.Data(); + Row row = Mockito.mock(Row.class); + innnerClassMtd = innerClass.getMethod("load", new Class[] {ArtiDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {ArtiDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); + + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {ArtiDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + +// DataInputStream in = Mockito.mock(DataInputStream.class); +//// Mockito.doReturn(100).when(in).read(); +//// Mockito.doReturn(100).when(in).readInt(); +// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {ArtiDAO.Data.class, DataInputStream.class }); +// innnerClassMtd.invoke(obj, new Object[] {data, in}); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testSecondConstructor() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ArtiDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ArtiDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + ArtiDAO.Data data = new ArtiDAO.Data(); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + + ArtiDAO daoObj = new ArtiDAO(trans, historyDAO, Mockito.mock(CacheInfoDAO.class)); + } + } class ArtiDAOImpl extends ArtiDAO{ - public ArtiDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace, PSInfo createPS ) { - super(trans, cluster, keyspace); - this.createPS = createPS; - setPs(this, createPS, "psByMechID"); - setPs(this, createPS, "psByMachine"); - setPs(this, createPS, "psByNs"); - } - - public ArtiDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS, HistoryDAO historyDAO ) { - super(trans, cluster, keyspace); - this.deletePS = readPS; - this.readPS = readPS; - setHistoryDao(this, historyDAO); - setSession(this, Mockito.mock(Session.class)); - } - - public void setPs(ArtiDAOImpl ArtiDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = ArtiDAO.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(ArtiDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public ArtiDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace, PSInfo createPS ) { + super(trans, cluster, keyspace); + this.createPS = createPS; + setPs(this, createPS, "psByMechID"); + setPs(this, createPS, "psByMachine"); + setPs(this, createPS, "psByNs"); + } + + public ArtiDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS, HistoryDAO historyDAO ) { + super(trans, cluster, keyspace); + this.deletePS = readPS; + this.readPS = readPS; + setHistoryDao(this, historyDAO); + setSession(this, Mockito.mock(Session.class)); + } + + public void setPs(ArtiDAOImpl ArtiDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = ArtiDAO.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(ArtiDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - public void setHistoryDao(ArtiDAOImpl ArtiDAOObj, HistoryDAO historyDAO) { - Field nsDaoField; - try { - nsDaoField = ArtiDAO.class.getDeclaredField("historyDAO"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(ArtiDAOObj, historyDAO); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - public void setSession(ArtiDAOImpl ArtiDAOObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(ArtiDAOObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setHistoryDao(ArtiDAOImpl ArtiDAOObj, HistoryDAO historyDAO) { + Field nsDaoField; + try { + nsDaoField = ArtiDAO.class.getDeclaredField("historyDAO"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(ArtiDAOObj, historyDAO); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + public void setSession(ArtiDAOImpl ArtiDAOObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(ArtiDAOObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CacheInfoDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CacheInfoDAO.java index 939cd27d..c23a3729 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CacheInfoDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CacheInfoDAO.java @@ -67,572 +67,572 @@ import com.datastax.driver.core.exceptions.DriverException; public class JU_CacheInfoDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - Session session; - @Mock - AuthzEnv env; - @Mock - LogTarget logTarget; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); - Mockito.doReturn(session).when(cluster).connect("test"); - } - - @Test - public void testInit() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); - - CacheInfoDAOImpl daoObj=null; - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// data.id - Result<Data> retVal = daoObj.create(trans, data); - assertTrue(retVal.status == 0); - } - - @Test - public void testTouch() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test: 1", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test: 1,2", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); + @Mock + Cluster cluster; + @Mock + Session session; + @Mock + AuthzEnv env; + @Mock + LogTarget logTarget; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); + Mockito.doReturn(session).when(cluster).connect("test"); + } + + @Test + public void testInit() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); + + CacheInfoDAOImpl daoObj=null; + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } +// data.id + Result<Data> retVal = daoObj.create(trans, data); + assertTrue(retVal.status == 0); + } + + @Test + public void testTouch() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test: 1", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test: 1,2", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); - Mockito.doReturn(logTarget).when(env).debug(); - - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); - - CacheInfoDAOImpl daoObj=null; - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// data.id - Result<Void> retVal = daoObj.touch(trans, "test", 1, 2); - assertTrue(retVal.status == 0); - Mockito.doThrow(DriverException.class).when(session).executeAsync(Mockito.anyString()); - daoObj.startUpdate(env, Mockito.mock(HMangr.class), Mockito.mock(SecuritySetter.class), "12.0.0.1", 8080); - retVal = daoObj.touch(trans, "test", 1, 2); - - - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(retVal.status == Result.ERR_Backend); - Mockito.doThrow(APIException.class).when(session).executeAsync(Mockito.anyString()); - retVal = daoObj.touch(trans, "test", 1, 2); - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - assertTrue(retVal.status == Result.ERR_Backend); - Mockito.doThrow(IOException.class).when(session).executeAsync(Mockito.anyString()); - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.touch(trans, "test", 1, 2); - assertTrue(retVal.status == Result.ERR_Backend); - } - - @Test - public void testCheck() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Check Table Timestamps", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); - - CacheInfoDAOImpl daoObj=null; - PreparedStatement ps = Mockito.mock(PreparedStatement.class); - Mockito.doReturn(ps).when(session).prepare(Mockito.anyString()); - Mockito.doReturn(Mockito.mock(ColumnDefinitions.class)).when(ps).getVariables(); - Mockito.doReturn(Mockito.mock(PreparedId.class)).when(ps).getPreparedId(); - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// data.id - ResultSet resultSet = Mockito.mock(ResultSet.class); - List<Row> rowList = new ArrayList<>(); - Mockito.doReturn(rowList).when(resultSet).all(); - Mockito.doReturn(resultSet).when(session).execute(Mockito.any(Statement.class)); - Result<Void> retVal = daoObj.check(trans); - assertTrue(retVal.status == 0); - - Row row = Mockito.mock(Row.class); - Mockito.doReturn("test").when(row).getString(Mockito.anyInt()); - rowList.add(row); - row = Mockito.mock(Row.class); - Mockito.doReturn("test").when(row).getString(Mockito.anyInt()); - Mockito.doReturn(100).when(row).getInt(Mockito.anyInt()); - rowList.add(row); - retVal = daoObj.check(trans); - assertTrue(retVal.status == 0); + Mockito.doReturn(logTarget).when(env).debug(); + + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); + + CacheInfoDAOImpl daoObj=null; + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } +// data.id + Result<Void> retVal = daoObj.touch(trans, "test", 1, 2); + assertTrue(retVal.status == 0); + Mockito.doThrow(DriverException.class).when(session).executeAsync(Mockito.anyString()); + daoObj.startUpdate(env, Mockito.mock(HMangr.class), Mockito.mock(SecuritySetter.class), "12.0.0.1", 8080); + retVal = daoObj.touch(trans, "test", 1, 2); + + + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(retVal.status == Result.ERR_Backend); + Mockito.doThrow(APIException.class).when(session).executeAsync(Mockito.anyString()); + retVal = daoObj.touch(trans, "test", 1, 2); + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + assertTrue(retVal.status == Result.ERR_Backend); + Mockito.doThrow(IOException.class).when(session).executeAsync(Mockito.anyString()); + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.touch(trans, "test", 1, 2); + assertTrue(retVal.status == Result.ERR_Backend); + } + + @Test + public void testCheck() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Check Table Timestamps", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); + + CacheInfoDAOImpl daoObj=null; + PreparedStatement ps = Mockito.mock(PreparedStatement.class); + Mockito.doReturn(ps).when(session).prepare(Mockito.anyString()); + Mockito.doReturn(Mockito.mock(ColumnDefinitions.class)).when(ps).getVariables(); + Mockito.doReturn(Mockito.mock(PreparedId.class)).when(ps).getPreparedId(); + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } +// data.id + ResultSet resultSet = Mockito.mock(ResultSet.class); + List<Row> rowList = new ArrayList<>(); + Mockito.doReturn(rowList).when(resultSet).all(); + Mockito.doReturn(resultSet).when(session).execute(Mockito.any(Statement.class)); + Result<Void> retVal = daoObj.check(trans); + assertTrue(retVal.status == 0); + + Row row = Mockito.mock(Row.class); + Mockito.doReturn("test").when(row).getString(Mockito.anyInt()); + rowList.add(row); + row = Mockito.mock(Row.class); + Mockito.doReturn("test").when(row).getString(Mockito.anyInt()); + Mockito.doReturn(100).when(row).getInt(Mockito.anyInt()); + rowList.add(row); + retVal = daoObj.check(trans); + assertTrue(retVal.status == 0); - Mockito.doThrow(DriverException.class).when(session).execute(Mockito.any(Statement.class)); - retVal = daoObj.check(trans); - assertTrue(retVal.status == Result.ERR_Backend); - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doThrow(APIException.class).when(session).execute(Mockito.any(Statement.class)); - retVal = daoObj.check(trans); - assertTrue(retVal.status == Result.ERR_Backend); - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doThrow(IOException.class).when(session).execute(Mockito.any(Statement.class)); - retVal = daoObj.check(trans); - assertTrue(retVal.status == Result.ERR_Backend); - } - @Test - public void testStopUpdate() { - - CacheInfoDAO.stopUpdate(); - - } + Mockito.doThrow(DriverException.class).when(session).execute(Mockito.any(Statement.class)); + retVal = daoObj.check(trans); + assertTrue(retVal.status == Result.ERR_Backend); + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doThrow(APIException.class).when(session).execute(Mockito.any(Statement.class)); + retVal = daoObj.check(trans); + assertTrue(retVal.status == Result.ERR_Backend); + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doThrow(IOException.class).when(session).execute(Mockito.any(Statement.class)); + retVal = daoObj.check(trans); + assertTrue(retVal.status == Result.ERR_Backend); + } + @Test + public void testStopUpdate() { + + CacheInfoDAO.stopUpdate(); + + } /* - * This has intermittent Null Pointers, JUnit only - @Test - public void testGet() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); - - CacheInfoDAOImpl daoObj=null; - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); - Date retVal = daoObj.get(trans, "test", 1011); -// assertTrue(retVal.status == 0); - retVal = daoObj.get(trans, "test1", 1011); - } catch (APIException | IOException e) { - e.printStackTrace(); - } - } + * This has intermittent Null Pointers, JUnit only + @Test + public void testGet() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data); + + CacheInfoDAOImpl daoObj=null; + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test",data, createPS); + Date retVal = daoObj.get(trans, "test", 1011); +// assertTrue(retVal.status == 0); + retVal = daoObj.get(trans, "test1", 1011); + } catch (APIException | IOException e) { + e.printStackTrace(); + } + } */ - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data = new CacheInfoDAO.Data("test",1); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - CacheInfoDAOImpl daoObj=null; - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - - } - - @Test - public void testInfoLoader(){ - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data1 = new CacheInfoDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data1); + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data = new CacheInfoDAO.Data("test",1); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + CacheInfoDAOImpl daoObj=null; + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + + } + + @Test + public void testInfoLoader(){ + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data1 = new CacheInfoDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data1); - CacheInfoDAOImpl daoObj=null; - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Class[] classList = CacheInfoDAO.class.getDeclaredClasses(); - Class<?> innerClass = null; - for(Class indCls:classList) { - if(indCls.getName().contains("InfoLoader")) { - innerClass = indCls; - } - } + CacheInfoDAOImpl daoObj=null; + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Class[] classList = CacheInfoDAO.class.getDeclaredClasses(); + Class<?> innerClass = null; + for(Class indCls:classList) { + if(indCls.getName().contains("InfoLoader")) { + innerClass = indCls; + } + } Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - Row row = Mockito.mock(Row.class); - innnerClassMtd = innerClass.getMethod("load", new Class[] {CacheInfoDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {CacheInfoDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"}}); + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + Row row = Mockito.mock(Row.class); + innnerClassMtd = innerClass.getMethod("load", new Class[] {CacheInfoDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {CacheInfoDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"}}); - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {CacheInfoDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"}}); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testCacheUpdate(){ - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data1 = new CacheInfoDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data1); + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {CacheInfoDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"}}); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testCacheUpdate(){ + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data1 = new CacheInfoDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data1); - CacheInfoDAOImpl daoObj=null; - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Class[] classList = CacheInfoDAO.class.getDeclaredClasses(); - Class<?> innerClass = null; - for(Class indCls:classList) { - if(indCls.getName().contains("CacheUpdate")) { - innerClass = indCls; - } - } + CacheInfoDAOImpl daoObj=null; + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Class[] classList = CacheInfoDAO.class.getDeclaredClasses(); + Class<?> innerClass = null; + for(Class indCls:classList) { + if(indCls.getName().contains("CacheUpdate")) { + innerClass = indCls; + } + } Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(env,Mockito.mock(HMangr.class), Mockito.mock(SecuritySetter.class), "12.0.0.1", 8080); + Object obj = constructor.newInstance(env,Mockito.mock(HMangr.class), Mockito.mock(SecuritySetter.class), "12.0.0.1", 8080); - Class<?> innerInnerClass = Class.forName("org.onap.aaf.auth.dao.cass.CacheInfoDAO$CacheUpdate$CacheClear"); + Class<?> innerInnerClass = Class.forName("org.onap.aaf.auth.dao.cass.CacheInfoDAO$CacheUpdate$CacheClear"); Constructor<?> innerConstructor = innerInnerClass.getDeclaredConstructors()[0]; innerConstructor.setAccessible(true); Object innerClassObj = innerConstructor.newInstance(obj, trans); - - Method innnerClassMtd; - - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - Row row = Mockito.mock(Row.class); - Rcli rcli = Mockito.mock(Rcli.class); - URI uri = new URI("ftp","admin:admin@geeksforgeeks.org:1234","/path/data","tt","ttd"); - Mockito.doReturn(uri).when(rcli).getURI(); - Mockito.doReturn(Mockito.mock(org.onap.aaf.cadi.client.Future.class)).when(rcli).delete("/mgmt/cache/null/null", "application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"); - - innnerClassMtd = innerInnerClass.getMethod("code", new Class[] {Rcli.class}); - innnerClassMtd.invoke(innerClassObj, new Object[] {rcli}); - - org.onap.aaf.cadi.client.Future futureObj = Mockito.mock(org.onap.aaf.cadi.client.Future.class); - Mockito.doReturn(futureObj).when(rcli).delete("/mgmt/cache/null/null", "application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"); - Mockito.doReturn(true).when(futureObj).get(0); - innnerClassMtd.invoke(innerClassObj, new Object[] {rcli}); - - uri = new URI("ftp","12.0.0.1:8080","/path/data","tt","ttd"); - Mockito.doReturn(uri).when(rcli).getURI(); - innnerClassMtd.invoke(innerClassObj, new Object[] {rcli}); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testIntHolder(){ - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data1 = new CacheInfoDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data1); + + Method innnerClassMtd; + + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + Row row = Mockito.mock(Row.class); + Rcli rcli = Mockito.mock(Rcli.class); + URI uri = new URI("ftp","admin:admin@geeksforgeeks.org:1234","/path/data","tt","ttd"); + Mockito.doReturn(uri).when(rcli).getURI(); + Mockito.doReturn(Mockito.mock(org.onap.aaf.cadi.client.Future.class)).when(rcli).delete("/mgmt/cache/null/null", "application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"); + + innnerClassMtd = innerInnerClass.getMethod("code", new Class[] {Rcli.class}); + innnerClassMtd.invoke(innerClassObj, new Object[] {rcli}); + + org.onap.aaf.cadi.client.Future futureObj = Mockito.mock(org.onap.aaf.cadi.client.Future.class); + Mockito.doReturn(futureObj).when(rcli).delete("/mgmt/cache/null/null", "application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"); + Mockito.doReturn(true).when(futureObj).get(0); + innnerClassMtd.invoke(innerClassObj, new Object[] {rcli}); + + uri = new URI("ftp","12.0.0.1:8080","/path/data","tt","ttd"); + Mockito.doReturn(uri).when(rcli).getURI(); + innnerClassMtd.invoke(innerClassObj, new Object[] {rcli}); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (URISyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testIntHolder(){ + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO Touch segments test1: 1011", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data1 = new CacheInfoDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CacheInfoDAOImpl CREATE", data1); - CacheInfoDAOImpl daoObj=null; - try { - daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Class[] classList = CacheInfoDAO.class.getDeclaredClasses(); - Class<?> innerClass = null; - for(Class indCls:classList) { - if(indCls.getName().contains("CacheUpdate")) { - innerClass = indCls; - } - } + CacheInfoDAOImpl daoObj=null; + try { + daoObj = new CacheInfoDAOImpl(trans, cluster, "test", createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Class[] classList = CacheInfoDAO.class.getDeclaredClasses(); + Class<?> innerClass = null; + for(Class indCls:classList) { + if(indCls.getName().contains("CacheUpdate")) { + innerClass = indCls; + } + } Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(env,Mockito.mock(HMangr.class), Mockito.mock(SecuritySetter.class), "12.0.0.1", 8080); + Object obj = constructor.newInstance(env,Mockito.mock(HMangr.class), Mockito.mock(SecuritySetter.class), "12.0.0.1", 8080); - Class<?> innerInnerClass = Class.forName("org.onap.aaf.auth.dao.cass.CacheInfoDAO$CacheUpdate$IntHolder"); + Class<?> innerInnerClass = Class.forName("org.onap.aaf.auth.dao.cass.CacheInfoDAO$CacheUpdate$IntHolder"); Constructor<?> innerConstructor = innerInnerClass.getDeclaredConstructors()[0]; innerConstructor.setAccessible(true); int[] a = new int[10]; Object innerClassObj = innerConstructor.newInstance(obj, a); - - Method innnerClassMtd=null; - - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - Row row = Mockito.mock(Row.class); - Rcli rcli = Mockito.mock(Rcli.class); - URI uri = new URI("ftp","admin:admin@geeksforgeeks.org:1234","/path/data","tt","ttd"); - Mockito.doReturn(uri).when(rcli).getURI(); - Mockito.doReturn(Mockito.mock(org.onap.aaf.cadi.client.Future.class)).when(rcli).delete("/mgmt/cache/null/null", "application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"); - - Method[] allMtds = innerInnerClass.getDeclaredMethods(); - for(Method indMtd:allMtds) { - if(indMtd.getName().contains("add")) { - innnerClassMtd = indMtd; - } - } - innnerClassMtd.invoke(innerClassObj, new Object[] {a}); - - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (ClassNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - //@Test - public void testSecondConstructor() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - CacheInfoDAO.Data data = new CacheInfoDAO.Data(); - AbsCassDAO absCassDAO = Mockito.mock(AbsCassDAO.class); + + Method innnerClassMtd=null; + + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + Row row = Mockito.mock(Row.class); + Rcli rcli = Mockito.mock(Rcli.class); + URI uri = new URI("ftp","admin:admin@geeksforgeeks.org:1234","/path/data","tt","ttd"); + Mockito.doReturn(uri).when(rcli).getURI(); + Mockito.doReturn(Mockito.mock(org.onap.aaf.cadi.client.Future.class)).when(rcli).delete("/mgmt/cache/null/null", "application/Void+json;q=1.0;charset=utf-8;version=2.0,application/json;q=1.0;version=2.0,*/*;q=1.0"); + + Method[] allMtds = innerInnerClass.getDeclaredMethods(); + for(Method indMtd:allMtds) { + if(indMtd.getName().contains("add")) { + innnerClassMtd = indMtd; + } + } + innnerClassMtd.invoke(innerClassObj, new Object[] {a}); + + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (ClassNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (URISyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + //@Test + public void testSecondConstructor() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CacheInfoDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CacheInfoDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + CacheInfoDAO.Data data = new CacheInfoDAO.Data(); + AbsCassDAO absCassDAO = Mockito.mock(AbsCassDAO.class); - try { - CacheInfoDAO daoObj = new CacheInfoDAO(trans, absCassDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + try { + CacheInfoDAO daoObj = new CacheInfoDAO(trans, absCassDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } class CacheInfoDAOImpl extends CacheInfoDAO{ - public CacheInfoDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,CacheInfoDAO.Data data,PSInfo createPS ) throws APIException, IOException { - super(trans, cluster, keyspace); - this.createPS = createPS; -// setPs(this, createPS, "psByUser"); -// setPs(this, createPS, "psByApprover"); -// setPs(this, createPS, "psByTicket"); -// setPs(this, createPS, "psByStatus"); -// setSession(this, Mockito.mock(Session.class)); - } - - public CacheInfoDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS ) throws APIException, IOException { - super(trans, cluster, keyspace); - this.readPS = readPS; - } - + public CacheInfoDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,CacheInfoDAO.Data data,PSInfo createPS ) throws APIException, IOException { + super(trans, cluster, keyspace); + this.createPS = createPS; +// setPs(this, createPS, "psByUser"); +// setPs(this, createPS, "psByApprover"); +// setPs(this, createPS, "psByTicket"); +// setPs(this, createPS, "psByStatus"); +// setSession(this, Mockito.mock(Session.class)); + } + + public CacheInfoDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS ) throws APIException, IOException { + super(trans, cluster, keyspace); + this.readPS = readPS; + } + - public void setPs(CacheInfoDAOImpl CacheInfoDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = CacheInfoDAO.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(CacheInfoDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setPs(CacheInfoDAOImpl CacheInfoDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = CacheInfoDAO.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(CacheInfoDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - public void setSession(CacheInfoDAOImpl CacheInfoDAOObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - nsDaoField.set(CacheInfoDAOObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + + public void setSession(CacheInfoDAOImpl CacheInfoDAOObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + nsDaoField.set(CacheInfoDAOObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CertDAOTest.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CertDAOTest.java index 3b2352c0..782bd985 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CertDAOTest.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_CertDAOTest.java @@ -56,331 +56,331 @@ import com.datastax.driver.core.Session; public class JU_CertDAOTest { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - Session session; - @Mock - AuthzEnv env; - @Mock - LogTarget logTarget; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); - Mockito.doReturn(session).when(cluster).connect("test"); - } - - @Test - public void testInit() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - CertDAO.Data data = new CertDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "CertDAOImpl CREATE", data); - - CertDAOImpl daoObj=null; - try { - daoObj = new CertDAOImpl(trans, cluster, "test",data, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + @Mock + Cluster cluster; + @Mock + Session session; + @Mock + AuthzEnv env; + @Mock + LogTarget logTarget; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); + Mockito.doReturn(session).when(cluster).connect("test"); + } + + @Test + public void testInit() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + CertDAO.Data data = new CertDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "CertDAOImpl CREATE", data); + + CertDAOImpl daoObj=null; + try { + daoObj = new CertDAOImpl(trans, cluster, "test",data, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - } - - @Test - public void testCertLoader(){ - - Class<?> innerClass = CertDAO.class.getDeclaredClasses()[0]; + } + + @Test + public void testCertLoader(){ + + Class<?> innerClass = CertDAO.class.getDeclaredClasses()[0]; Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - CertDAO.Data data = new CertDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {CertDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {CertDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {CertDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - -// DataInputStream in = Mockito.mock(DataInputStream.class); -//// Mockito.doReturn(100).when(in).read(); -//// Mockito.doReturn(100).when(in).readInt(); -// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {ArtiDAO.Data.class, DataInputStream.class }); -// innnerClassMtd.invoke(obj, new Object[] {data, in}); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - CertDAO.Data data = new CertDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(trans, CertDAO.TABLE, new int[1]); - - CertDAO daoObj = null; - try { - daoObj = new CertDAO(trans, historyDAO, cacheInfoDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(trans, CertDAO.TABLE, new int[1]); - - try { - daoObj = new CertDAO(trans, historyDAO, cacheInfoDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + CertDAO.Data data = new CertDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {CertDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {CertDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {CertDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + +// DataInputStream in = Mockito.mock(DataInputStream.class); +//// Mockito.doReturn(100).when(in).read(); +//// Mockito.doReturn(100).when(in).readInt(); +// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {ArtiDAO.Data.class, DataInputStream.class }); +// innnerClassMtd.invoke(obj, new Object[] {data, in}); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + CertDAO.Data data = new CertDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(trans, CertDAO.TABLE, new int[1]); + + CertDAO daoObj = null; + try { + daoObj = new CertDAO(trans, historyDAO, cacheInfoDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(trans, CertDAO.TABLE, new int[1]); + + try { + daoObj = new CertDAO(trans, historyDAO, cacheInfoDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test"}); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test", null}); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test", "test"}); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {}); - - try { - CertDAO.Data data1 = Mockito.mock(CertDAO.Data.class); - Mockito.doThrow(new IOException()).when(data1).bytify(); - Mockito.doReturn(new int[1]).when(data1).invalidate(Mockito.any()); - daoObj.wasModified(trans, CRUD.delete, data1, new String[] {}); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testRead() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CertDAO READ", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("CertDAOImpl READ",Env.REMOTE); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Mockito.doReturn(Mockito.mock(Decryptor.class)).when(trans).decryptor(); - Mockito.doNothing().when(tt).done(); - CertDAO.Data data = new CertDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(trans, CertDAO.TABLE, new int[1]); - - CertDAOImpl daoObj = null; - try { - daoObj = new CertDAOImpl(trans, historyDAO, cacheInfoDAO, createPS); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - daoObj.read(trans, new Object[] {"test", BigInteger.ONE}); - Field cbField; - try { - cbField = CassAccess.class.getDeclaredField("cb"); - - cbField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - cbField.set(null, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - daoObj.readX500(trans, "test"); - - try { - cbField = CassAccess.class.getDeclaredField("cb"); - - cbField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - cbField.set(null, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - daoObj.readID(trans, "test"); - } + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test"}); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test", null}); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test", "test"}); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {}); + + try { + CertDAO.Data data1 = Mockito.mock(CertDAO.Data.class); + Mockito.doThrow(new IOException()).when(data1).bytify(); + Mockito.doReturn(new int[1]).when(data1).invalidate(Mockito.any()); + daoObj.wasModified(trans, CRUD.delete, data1, new String[] {}); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testRead() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CertDAO READ", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("CertDAOImpl READ",Env.REMOTE); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + Mockito.doReturn(Mockito.mock(Decryptor.class)).when(trans).decryptor(); + Mockito.doNothing().when(tt).done(); + CertDAO.Data data = new CertDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(trans, CertDAO.TABLE, new int[1]); + + CertDAOImpl daoObj = null; + try { + daoObj = new CertDAOImpl(trans, historyDAO, cacheInfoDAO, createPS); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + daoObj.read(trans, new Object[] {"test", BigInteger.ONE}); + Field cbField; + try { + cbField = CassAccess.class.getDeclaredField("cb"); + + cbField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + cbField.set(null, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + daoObj.readX500(trans, "test"); + + try { + cbField = CassAccess.class.getDeclaredField("cb"); + + cbField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + cbField.set(null, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + daoObj.readID(trans, "test"); + } - - @Test - public void testSecondConstructor() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - CertDAO.Data data = new CertDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + + @Test + public void testSecondConstructor() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("CertDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on CertDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + CertDAO.Data data = new CertDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - try { - CertDAO daoObj = new CertDAO(trans, historyDAO, cacheInfoDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + try { + CertDAO daoObj = new CertDAO(trans, historyDAO, cacheInfoDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } class CertDAOImpl extends CertDAO{ - public CertDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,CertDAO.Data data,PSInfo createPS ) throws APIException, IOException { - super(trans, cluster, keyspace); - this.createPS = createPS; -// setPs(this, createPS, "psByUser"); -// setPs(this, createPS, "psByApprover"); -// setPs(this, createPS, "psByTicket"); -// setPs(this, createPS, "psByStatus"); -// setSession(this, Mockito.mock(Session.class)); - } - - public CertDAOImpl(AuthzTrans trans, HistoryDAO historyDAO, CacheInfoDAO cacheInfoDAO,PSInfo readPS ) throws APIException, IOException { - super(trans, historyDAO, cacheInfoDAO); - this.readPS = readPS; - } - + public CertDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,CertDAO.Data data,PSInfo createPS ) throws APIException, IOException { + super(trans, cluster, keyspace); + this.createPS = createPS; +// setPs(this, createPS, "psByUser"); +// setPs(this, createPS, "psByApprover"); +// setPs(this, createPS, "psByTicket"); +// setPs(this, createPS, "psByStatus"); +// setSession(this, Mockito.mock(Session.class)); + } + + public CertDAOImpl(AuthzTrans trans, HistoryDAO historyDAO, CacheInfoDAO cacheInfoDAO,PSInfo readPS ) throws APIException, IOException { + super(trans, historyDAO, cacheInfoDAO); + this.readPS = readPS; + } + - public void setPs(CertDAOImpl CertDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = CertDAO.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(CertDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setPs(CertDAOImpl CertDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = CertDAO.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(CertDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - public void setSession(CertDAOImpl CertDAOObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - nsDaoField.set(CertDAOObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + + public void setSession(CertDAOImpl CertDAOObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + nsDaoField.set(CertDAOObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ConfigDAOTest.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ConfigDAOTest.java index 9eee56c4..91d16970 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ConfigDAOTest.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_ConfigDAOTest.java @@ -63,248 +63,248 @@ import com.datastax.driver.core.Session; public class JU_ConfigDAOTest { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - Session session; - @Mock - AuthzEnv env; - @Mock - LogTarget logTarget; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); - Mockito.doReturn(session).when(cluster).connect("test"); - } - - @Test - public void testInit() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ConfigDAO", Env.SUB); - Mockito.doNothing().when(tt).done(); - ConfigDAO.Data data = new ConfigDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs).when(createPS).exec(trans, "ConfigDAOImpl CREATE", data); - - ConfigDAO daoObj=null; - try { - daoObj = new ConfigDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + @Mock + Cluster cluster; + @Mock + Session session; + @Mock + AuthzEnv env; + @Mock + LogTarget logTarget; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); + Mockito.doReturn(session).when(cluster).connect("test"); + } + + @Test + public void testInit() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ConfigDAO", Env.SUB); + Mockito.doNothing().when(tt).done(); + ConfigDAO.Data data = new ConfigDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + Result<ResultSet> rs = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs).when(createPS).exec(trans, "ConfigDAOImpl CREATE", data); + + ConfigDAO daoObj=null; + try { + daoObj = new ConfigDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - } - - @Test - public void testConfigLoader(){ - - Class<?> innerClass = ConfigDAO.class.getDeclaredClasses()[0]; + } + + @Test + public void testConfigLoader(){ + + Class<?> innerClass = ConfigDAO.class.getDeclaredClasses()[0]; Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - ConfigDAO.Data data = new ConfigDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {ConfigDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {ConfigDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {ConfigDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {ConfigDAO.Data.class, DataOutputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dos }); + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + ConfigDAO.Data data = new ConfigDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {ConfigDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {ConfigDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {ConfigDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {ConfigDAO.Data.class, DataOutputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dos }); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DataInputStream dis = new DataInputStream(bais); - innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {ConfigDAO.Data.class, DataInputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ConfigDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - ConfigDAO.Data data = new ConfigDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - ConfigDAO daoObj = null; - try { - daoObj = new ConfigDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - - - } - - @Test - public void testRead() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("ConfigDAO READ", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo READ on ConfigDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start(Mockito.anyString(),Mockito.anyInt()); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Mockito.doReturn(Mockito.mock(Decryptor.class)).when(trans).decryptor(); - Mockito.doNothing().when(tt).done(); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); - + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + DataInputStream dis = new DataInputStream(bais); + innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {ConfigDAO.Data.class, DataInputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ConfigDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + ConfigDAO.Data data = new ConfigDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + ConfigDAO daoObj = null; + try { + daoObj = new ConfigDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + + + } + + @Test + public void testRead() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("ConfigDAO READ", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo READ on ConfigDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start(Mockito.anyString(),Mockito.anyInt()); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + Mockito.doReturn(Mockito.mock(Decryptor.class)).when(trans).decryptor(); + Mockito.doNothing().when(tt).done(); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); + - PSInfo psObj = Mockito.mock(PSInfo.class); - ConfigDAOImpl daoObj = null; - try { - daoObj = new ConfigDAOImpl(trans, cluster, "test",psObj); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doReturn(rs1).when(psObj).read(trans, "ConfigDAO READ", new Object[]{"test"}); - daoObj.readName(trans, "test"); - - - } + PSInfo psObj = Mockito.mock(PSInfo.class); + ConfigDAOImpl daoObj = null; + try { + daoObj = new ConfigDAOImpl(trans, cluster, "test",psObj); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doReturn(rs1).when(psObj).read(trans, "ConfigDAO READ", new Object[]{"test"}); + daoObj.readName(trans, "test"); + + + } - - - @Test - public void testSecondConstructor() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ConfigDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); - Mockito.doNothing().when(tt).done(); - AbsCassDAO absDAO = Mockito.mock(AbsCassDAO.class); + + + @Test + public void testSecondConstructor() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("ConfigDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on ConfigDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE APPROVAL",Env.REMOTE); + Mockito.doNothing().when(tt).done(); + AbsCassDAO absDAO = Mockito.mock(AbsCassDAO.class); - try { - ConfigDAO daoObj = new ConfigDAO(trans, absDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + try { + ConfigDAO daoObj = new ConfigDAO(trans, absDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } class ConfigDAOImpl extends ConfigDAO{ - - public ConfigDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS ) throws APIException, IOException { - super(trans, cluster, keyspace); - setPs(this, readPS, "psName"); - } - + + public ConfigDAOImpl(AuthzTrans trans, Cluster cluster, String keyspace,PSInfo readPS ) throws APIException, IOException { + super(trans, cluster, keyspace); + setPs(this, readPS, "psName"); + } + - public void setPs(ConfigDAOImpl ConfigDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = ConfigDAO.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(ConfigDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setPs(ConfigDAOImpl ConfigDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = ConfigDAO.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(ConfigDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - public void setSession(ConfigDAOImpl ConfigDAOObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - nsDaoField.set(ConfigDAOObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + + public void setSession(ConfigDAOImpl ConfigDAOObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + nsDaoField.set(ConfigDAOObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_DelegateDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_DelegateDAO.java index 88d71a99..39d7492a 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_DelegateDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_DelegateDAO.java @@ -47,142 +47,142 @@ import com.datastax.driver.core.Row; public class JU_DelegateDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - } + @Mock + Cluster cluster; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + } - @Test - public void testInit() { - DelegateDAO daoObj = new DelegateDAO(trans, cluster, "test"); -// daoObj. - } - @Test - public void testReadByDelegate() { - DelegateDAO daoObj = new DelegateDAO(trans, cluster, "test"); - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsDelegate(daoObj, psObj, "psByDelegate"); - - Result<List<DelegateDAO.Data>> rs1 = new Result<List<DelegateDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "DelegateDAO READ", new Object[]{"test"}); - - daoObj.readByDelegate(trans, "test"); - } - - public void setPsDelegate(DelegateDAO delegateDAOObj, PSInfo psInfoObj, String fieldName) { - Field nsDaoField; - try { - nsDaoField = DelegateDAO.class.getDeclaredField(fieldName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(delegateDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testSecondConstructor() { - AbsCassDAO absDAO = Mockito.mock(AbsCassDAO.class); + @Test + public void testInit() { + DelegateDAO daoObj = new DelegateDAO(trans, cluster, "test"); +// daoObj. + } + @Test + public void testReadByDelegate() { + DelegateDAO daoObj = new DelegateDAO(trans, cluster, "test"); + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsDelegate(daoObj, psObj, "psByDelegate"); + + Result<List<DelegateDAO.Data>> rs1 = new Result<List<DelegateDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "DelegateDAO READ", new Object[]{"test"}); + + daoObj.readByDelegate(trans, "test"); + } + + public void setPsDelegate(DelegateDAO delegateDAOObj, PSInfo psInfoObj, String fieldName) { + Field nsDaoField; + try { + nsDaoField = DelegateDAO.class.getDeclaredField(fieldName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(delegateDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testSecondConstructor() { + AbsCassDAO absDAO = Mockito.mock(AbsCassDAO.class); - DelegateDAO daoObj = new DelegateDAO(trans, absDAO); - - } + DelegateDAO daoObj = new DelegateDAO(trans, absDAO); + + } - @Test - public void testDelegateLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = DelegateDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("DelegateLoader")) { - innerClass = indCls; - break; - } - } - + @Test + public void testDelegateLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = DelegateDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("DelegateLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - DelegateDAO.Data data = new DelegateDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {DelegateDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {DelegateDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {DelegateDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - -// DataOutputStream dos = new DataOutputStream(new FileOutputStream("JU_DelegateDAOTest.java")); -// innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {DelegateDAO.Data.class, DataOutputStream.class }); -// innnerClassMtd.invoke(obj, new Object[] {data, dos }); + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + DelegateDAO.Data data = new DelegateDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {DelegateDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {DelegateDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {DelegateDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + +// DataOutputStream dos = new DataOutputStream(new FileOutputStream("JU_DelegateDAOTest.java")); +// innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {DelegateDAO.Data.class, DataOutputStream.class }); +// innnerClassMtd.invoke(obj, new Object[] {data, dos }); -// DataInputStream dis = new DataInputStream(new FileInputStream("JU_DelegateDAOTest.java")); -// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {DelegateDAO.Data.class, DataInputStream.class }); -// innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testData(){ - DelegateDAO.Data data = new DelegateDAO.Data(); - data.user="user"; - data.delegate="delegate"; - data.expires = new Date(); - try { - data.bytify(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - +// DataInputStream dis = new DataInputStream(new FileInputStream("JU_DelegateDAOTest.java")); +// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {DelegateDAO.Data.class, DataInputStream.class }); +// innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testData(){ + DelegateDAO.Data data = new DelegateDAO.Data(); + data.user="user"; + data.delegate="delegate"; + data.expires = new Date(); + try { + data.bytify(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_FutureDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_FutureDAO.java index 68764a60..07946156 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_FutureDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_FutureDAO.java @@ -54,240 +54,240 @@ import com.datastax.driver.core.Row; public class JU_FutureDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - } + @Mock + Cluster cluster; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + } - @Test - public void testInit() { - FutureDAO daoObj = new FutureDAO(trans, cluster, "test"); -// daoObj. - } - @Test - public void testReadByStartAndTarget() { - FutureDAO daoObj = new FutureDAO(trans, cluster, "test"); - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psByStartAndTarget"); - - Result<List<FutureDAO.Data>> rs1 = new Result<List<FutureDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "FutureDAO READ", new Object[]{"test"}); - - daoObj.readByStartAndTarget(trans,new Date(), "test"); - } - @Test - public void testCreate() { - PSInfo psObj = Mockito.mock(PSInfo.class); + @Test + public void testInit() { + FutureDAO daoObj = new FutureDAO(trans, cluster, "test"); +// daoObj. + } + @Test + public void testReadByStartAndTarget() { + FutureDAO daoObj = new FutureDAO(trans, cluster, "test"); + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psByStartAndTarget"); + + Result<List<FutureDAO.Data>> rs1 = new Result<List<FutureDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "FutureDAO READ", new Object[]{"test"}); + + daoObj.readByStartAndTarget(trans,new Date(), "test"); + } + @Test + public void testCreate() { + PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - FutureDAO.Data data = new FutureDAO.Data(); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + FutureDAO.Data data = new FutureDAO.Data(); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "FutureDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - FutureDAOImpl daoObj=null; - try { - daoObj = new FutureDAOImpl(trans, historyDAO, psObj); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doReturn("test user").when(trans).user(); - - Result<FutureDAO.Data> retVal = daoObj.create(trans,data, "test"); - assertTrue(retVal.status == 0); - - StringBuilder sb = new StringBuilder(trans.user()); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "FutureDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + FutureDAOImpl daoObj=null; + try { + daoObj = new FutureDAOImpl(trans, historyDAO, psObj); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doReturn("test user").when(trans).user(); + + Result<FutureDAO.Data> retVal = daoObj.create(trans,data, "test"); + assertTrue(retVal.status == 0); + + StringBuilder sb = new StringBuilder(trans.user()); sb.append(data.target); sb.append(System.currentTimeMillis()); - data.id = UUID.nameUUIDFromBytes(sb.toString().getBytes()); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "FutureDAOImpl CREATE", data); - - retVal = daoObj.create(trans,data, "test"); - assertTrue(retVal.status != 0); - - - } - - public void setPsByStartAndTarget(FutureDAO FutureDAOObj, PSInfo psInfoObj, String fieldName) { - Field nsDaoField; - try { - nsDaoField = FutureDAO.class.getDeclaredField(fieldName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(FutureDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("FutureDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on FutureDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doNothing().when(tt).done(); - FutureDAO.Data data = new FutureDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - FutureDAOImpl daoObj = null; - try { - daoObj = new FutureDAOImpl(trans, historyDAO, createPS ); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - daoObj.wasModified(trans, CRUD.create, data, new String[] {}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - } - - @Test - public void testSecondConstructor() { - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + data.id = UUID.nameUUIDFromBytes(sb.toString().getBytes()); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "FutureDAOImpl CREATE", data); + + retVal = daoObj.create(trans,data, "test"); + assertTrue(retVal.status != 0); + + + } + + public void setPsByStartAndTarget(FutureDAO FutureDAOObj, PSInfo psInfoObj, String fieldName) { + Field nsDaoField; + try { + nsDaoField = FutureDAO.class.getDeclaredField(fieldName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(FutureDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("FutureDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on FutureDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doNothing().when(tt).done(); + FutureDAO.Data data = new FutureDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + FutureDAOImpl daoObj = null; + try { + daoObj = new FutureDAOImpl(trans, historyDAO, createPS ); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + daoObj.wasModified(trans, CRUD.create, data, new String[] {}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + } + + @Test + public void testSecondConstructor() { + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - FutureDAO daoObj = new FutureDAO(trans, historyDAO); - - } + FutureDAO daoObj = new FutureDAO(trans, historyDAO); + + } - @Test - public void testFutureLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = FutureDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("FLoader")) { - innerClass = indCls; - break; - } - } - + @Test + public void testFutureLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = FutureDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("FLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[1]; constructor.setAccessible(true); Constructor<?> constructor1 = innerClass.getDeclaredConstructors()[0]; constructor1.setAccessible(true); try { - - Object obj = constructor.newInstance(1); - obj = constructor1.newInstance(); - Method innnerClassMtd; - - FutureDAO.Data data = new FutureDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {FutureDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {FutureDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {FutureDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - -// DataOutputStream dos = new DataOutputStream(new FileOutputStream("JU_FutureDAOTest.java")); -// innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {FutureDAO.Data.class, DataOutputStream.class }); -// innnerClassMtd.invoke(obj, new Object[] {data, dos }); + + Object obj = constructor.newInstance(1); + obj = constructor1.newInstance(); + Method innnerClassMtd; + + FutureDAO.Data data = new FutureDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {FutureDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {FutureDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {FutureDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + +// DataOutputStream dos = new DataOutputStream(new FileOutputStream("JU_FutureDAOTest.java")); +// innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {FutureDAO.Data.class, DataOutputStream.class }); +// innnerClassMtd.invoke(obj, new Object[] {data, dos }); -// DataInputStream dis = new DataInputStream(new FileInputStream("JU_FutureDAOTest.java")); -// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {FutureDAO.Data.class, DataInputStream.class }); -// innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - +// DataInputStream dis = new DataInputStream(new FileInputStream("JU_FutureDAOTest.java")); +// innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {FutureDAO.Data.class, DataInputStream.class }); +// innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } class FutureDAOImpl extends FutureDAO{ - - public FutureDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { - super(trans, historyDAO); - setPs(this, readPS, "createPS"); - } - + + public FutureDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { + super(trans, historyDAO); + setPs(this, readPS, "createPS"); + } + - public void setPs(FutureDAOImpl FutureDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(FutureDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + public void setPs(FutureDAOImpl FutureDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(FutureDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_HistoryDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_HistoryDAO.java index 78eb92e8..f6d0a65b 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_HistoryDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_HistoryDAO.java @@ -57,275 +57,275 @@ import com.datastax.driver.core.Row; public class JU_HistoryDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - } + @Mock + Cluster cluster; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + } - @Test - public void testInit() { - HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); - } - @Test - public void testNewInitedData() { - HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); - HistoryDAO.Data data = daoObj.newInitedData(); - assertTrue( Integer.toString(((new Date()).getYear())+1900).equalsIgnoreCase(Integer.toString(data.yr_mon).substring(0,4)) ); - } - - @Test - public void testCreateBatch() { - HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); - StringBuilder sb = new StringBuilder(); - HistoryDAO.Data data = new HistoryDAO.Data(); - daoObj.createBatch(sb, data); - assertTrue(sb.toString().contains("INSERT INTO history")); - } - - @Test - public void testReadByYYYYMM() { - HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); - AbsCassDAO<AuthzTrans, Data>.PSInfo psInfoObj = Mockito.mock(PSInfo.class); - setAbsCassDAO(daoObj, psInfoObj, "readByYRMN"); - - ResultSet rs = Mockito.mock(ResultSet.class); - Result<ResultSet> rs1 = new Result<ResultSet>(rs,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "yr_mon", 201905); - - Result<List<Data>> retVal = daoObj.readByYYYYMM(trans, 201905); - assertTrue(retVal.status !=1); - - rs1 = new Result<ResultSet>(rs,1,"test",new String[0]); - Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "yr_mon", 201905); - retVal = daoObj.readByYYYYMM(trans, 201905); - assertTrue(retVal.status !=0); - } - - @Test - public void testReadByUser() { - HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); - AbsCassDAO<AuthzTrans, Data>.PSInfo psInfoObj = Mockito.mock(PSInfo.class); - setAbsCassDAO(daoObj, psInfoObj, "readByUser"); - - ResultSet rs = Mockito.mock(ResultSet.class); - Result<ResultSet> rs1 = new Result<ResultSet>(rs,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "user", "test"); - - Result<List<Data>> retVal = daoObj.readByUser(trans, "test", 201905); - assertTrue(retVal.status !=1); - - rs1 = new Result<ResultSet>(rs,1,"test",new String[0]); - Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "user", "test"); - retVal = daoObj.readByUser(trans,"test", 201905); - assertTrue(retVal.status !=0); - - retVal = daoObj.readByUser(trans,"test"); - assertTrue(retVal.status !=0); - } - - @Test - public void testReadBySubject() { - HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); - AbsCassDAO<AuthzTrans, Data>.PSInfo psInfoObj = Mockito.mock(PSInfo.class); - setAbsCassDAO(daoObj, psInfoObj, "readBySubject"); - - ResultSet rs = Mockito.mock(ResultSet.class); - Result<ResultSet> rs1 = new Result<ResultSet>(rs,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "subject", "test", "test"); - - Result<List<Data>> retVal = daoObj.readBySubject(trans, "test", "test", 201905); - assertTrue(retVal.status !=1); - - rs1 = new Result<ResultSet>(rs,1,"test",new String[0]); - Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "subject", "test", "test"); - retVal = daoObj.readBySubject(trans,"test", "test", 201905); - assertTrue(retVal.status !=0); - - retVal = daoObj.readBySubject(trans,"test", "test"); - assertTrue(retVal.status !=0); - } - - public void setAbsCassDAO(HistoryDAO HistoryDAOObj, PSInfo psInfoObj, String fieldName) { - Field nsDaoField; - try { - nsDaoField = HistoryDAO.class.getDeclaredField(fieldName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(HistoryDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - - @Test - public void testSecondConstructor() { - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + @Test + public void testInit() { + HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); + } + @Test + public void testNewInitedData() { + HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); + HistoryDAO.Data data = daoObj.newInitedData(); + assertTrue( Integer.toString(((new Date()).getYear())+1900).equalsIgnoreCase(Integer.toString(data.yr_mon).substring(0,4)) ); + } + + @Test + public void testCreateBatch() { + HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); + StringBuilder sb = new StringBuilder(); + HistoryDAO.Data data = new HistoryDAO.Data(); + daoObj.createBatch(sb, data); + assertTrue(sb.toString().contains("INSERT INTO history")); + } + + @Test + public void testReadByYYYYMM() { + HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); + AbsCassDAO<AuthzTrans, Data>.PSInfo psInfoObj = Mockito.mock(PSInfo.class); + setAbsCassDAO(daoObj, psInfoObj, "readByYRMN"); + + ResultSet rs = Mockito.mock(ResultSet.class); + Result<ResultSet> rs1 = new Result<ResultSet>(rs,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "yr_mon", 201905); + + Result<List<Data>> retVal = daoObj.readByYYYYMM(trans, 201905); + assertTrue(retVal.status !=1); + + rs1 = new Result<ResultSet>(rs,1,"test",new String[0]); + Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "yr_mon", 201905); + retVal = daoObj.readByYYYYMM(trans, 201905); + assertTrue(retVal.status !=0); + } + + @Test + public void testReadByUser() { + HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); + AbsCassDAO<AuthzTrans, Data>.PSInfo psInfoObj = Mockito.mock(PSInfo.class); + setAbsCassDAO(daoObj, psInfoObj, "readByUser"); + + ResultSet rs = Mockito.mock(ResultSet.class); + Result<ResultSet> rs1 = new Result<ResultSet>(rs,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "user", "test"); + + Result<List<Data>> retVal = daoObj.readByUser(trans, "test", 201905); + assertTrue(retVal.status !=1); + + rs1 = new Result<ResultSet>(rs,1,"test",new String[0]); + Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "user", "test"); + retVal = daoObj.readByUser(trans,"test", 201905); + assertTrue(retVal.status !=0); + + retVal = daoObj.readByUser(trans,"test"); + assertTrue(retVal.status !=0); + } + + @Test + public void testReadBySubject() { + HistoryDAO daoObj = new HistoryDAO(trans, cluster, "test"); + AbsCassDAO<AuthzTrans, Data>.PSInfo psInfoObj = Mockito.mock(PSInfo.class); + setAbsCassDAO(daoObj, psInfoObj, "readBySubject"); + + ResultSet rs = Mockito.mock(ResultSet.class); + Result<ResultSet> rs1 = new Result<ResultSet>(rs,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "subject", "test", "test"); + + Result<List<Data>> retVal = daoObj.readBySubject(trans, "test", "test", 201905); + assertTrue(retVal.status !=1); + + rs1 = new Result<ResultSet>(rs,1,"test",new String[0]); + Mockito.doReturn(rs1).when(psInfoObj).exec(trans, "subject", "test", "test"); + retVal = daoObj.readBySubject(trans,"test", "test", 201905); + assertTrue(retVal.status !=0); + + retVal = daoObj.readBySubject(trans,"test", "test"); + assertTrue(retVal.status !=0); + } + + public void setAbsCassDAO(HistoryDAO HistoryDAOObj, PSInfo psInfoObj, String fieldName) { + Field nsDaoField; + try { + nsDaoField = HistoryDAO.class.getDeclaredField(fieldName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(HistoryDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + @Test + public void testSecondConstructor() { + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - HistoryDAO daoObj = new HistoryDAO(trans, historyDAO); - - } + HistoryDAO daoObj = new HistoryDAO(trans, historyDAO); + + } - @Test - public void testHistoryLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = HistoryDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("HistLoader")) { - innerClass = indCls; - break; - } - } - + @Test + public void testHistoryLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = HistoryDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("HistLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - HistoryDAO.Data data = new HistoryDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {HistoryDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {HistoryDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {HistoryDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testYYYYMM(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = HistoryDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("YYYYMM")) { - innerClass = indCls; - break; - } - } - + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + HistoryDAO.Data data = new HistoryDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {HistoryDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {HistoryDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {HistoryDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testYYYYMM(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = HistoryDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("YYYYMM")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); int yyyymm[] = new int[2]; try { - Object obj = constructor.newInstance(new HistoryDAO(trans, cluster, "test"), yyyymm); - Method innnerClassMtd; - - HistoryDAO.Data data = new HistoryDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("ok", new Class[] {HistoryDAO.Data.class}); - innnerClassMtd.invoke(obj, new Object[] {data}); - - data.yr_mon=201904; - innnerClassMtd.invoke(obj, new Object[] {data}); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + Object obj = constructor.newInstance(new HistoryDAO(trans, cluster, "test"), yyyymm); + Method innnerClassMtd; + + HistoryDAO.Data data = new HistoryDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("ok", new Class[] {HistoryDAO.Data.class}); + innnerClassMtd.invoke(obj, new Object[] {data}); + + data.yr_mon=201904; + innnerClassMtd.invoke(obj, new Object[] {data}); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } class HistoryDAOImpl extends HistoryDAO{ - - public HistoryDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { - super(trans, historyDAO); - setPs(this, readPS, "createPS"); - } - - public void setPs(HistoryDAOImpl HistoryDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(HistoryDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + + public HistoryDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { + super(trans, historyDAO); + setPs(this, readPS, "createPS"); + } + + public void setPs(HistoryDAOImpl HistoryDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(HistoryDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_LocateDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_LocateDAO.java index 3493b088..53bad44e 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_LocateDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_LocateDAO.java @@ -56,262 +56,262 @@ import com.datastax.driver.core.Row; public class JU_LocateDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - } + @Mock + Cluster cluster; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + } - @Test - public void testInit() { - try { - LocateDAO daoObj = new LocateDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testReadByStartAndTarget() { - LocateDAO daoObj = null; - try { - daoObj = new LocateDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psName"); - - Result<List<LocateDAO.Data>> rs1 = new Result<List<LocateDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "LocateDAO READ", new Object[]{"test"}); - - daoObj.readByName(trans, "test"); - } - - - public void setPsByStartAndTarget(LocateDAO LocateDAOObj, PSInfo psInfoObj, String fieldName) { - Field nsDaoField; - try { - nsDaoField = LocateDAO.class.getDeclaredField(fieldName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(LocateDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - - LocateDAO.Data data = new LocateDAO.Data(); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - - LocateDAO daoObj = null; - try { - daoObj = new LocateDAO(trans, historyDAO ); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - - } - - @Test - public void testSecondConstructor() { - AbsCassDAO historyDAO = Mockito.mock(AbsCassDAO.class); + @Test + public void testInit() { + try { + LocateDAO daoObj = new LocateDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testReadByStartAndTarget() { + LocateDAO daoObj = null; + try { + daoObj = new LocateDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psName"); + + Result<List<LocateDAO.Data>> rs1 = new Result<List<LocateDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "LocateDAO READ", new Object[]{"test"}); + + daoObj.readByName(trans, "test"); + } + + + public void setPsByStartAndTarget(LocateDAO LocateDAOObj, PSInfo psInfoObj, String fieldName) { + Field nsDaoField; + try { + nsDaoField = LocateDAO.class.getDeclaredField(fieldName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(LocateDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + + LocateDAO.Data data = new LocateDAO.Data(); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + + LocateDAO daoObj = null; + try { + daoObj = new LocateDAO(trans, historyDAO ); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + + } + + @Test + public void testSecondConstructor() { + AbsCassDAO historyDAO = Mockito.mock(AbsCassDAO.class); - try { - LocateDAO daoObj = new LocateDAO(trans, historyDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } + try { + LocateDAO daoObj = new LocateDAO(trans, historyDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } - @Test - public void testLocateLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = LocateDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("LocateLoader")) { - innerClass = indCls; - break; - } - } - + @Test + public void testLocateLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = LocateDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("LocateLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - LocateDAO.Data data = new LocateDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {LocateDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {LocateDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 0, new Object[] {"test","test","test"} }); - - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {LocateDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {LocateDAO.Data.class, DataOutputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dos }); + + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + LocateDAO.Data data = new LocateDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {LocateDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {LocateDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 0, new Object[] {"test","test","test"} }); + + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {LocateDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {LocateDAO.Data.class, DataOutputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dos }); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DataInputStream dis = new DataInputStream(bais); - innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {LocateDAO.Data.class, DataInputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testData(){ - LocateDAO.Data data = new LocateDAO.Data(); - data.name="name"; - data.hostname="hostname"; - try { - data.bytify(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - data.subprotocol(true); - - Set<String> subProt = new HashSet<String>(); - Field protField; - try { - protField = LocateDAO.Data.class.getDeclaredField("subprotocol"); - - protField.setAccessible(true); - - protField.set(data, subProt); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - data.subprotocol(true); - subProt = new TreeSet<String>(); - subProt.add("test"); - try { - protField = LocateDAO.Data.class.getDeclaredField("subprotocol"); - - protField.setAccessible(true); - - protField.set(data, subProt); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - data.subprotocol(true); - data.subprotocol(false); - - LocateDAO.Data newDate = data.copy(); - assertTrue(data.name.equals(newDate.name)); - } - + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + DataInputStream dis = new DataInputStream(bais); + innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {LocateDAO.Data.class, DataInputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testData(){ + LocateDAO.Data data = new LocateDAO.Data(); + data.name="name"; + data.hostname="hostname"; + try { + data.bytify(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + data.subprotocol(true); + + Set<String> subProt = new HashSet<String>(); + Field protField; + try { + protField = LocateDAO.Data.class.getDeclaredField("subprotocol"); + + protField.setAccessible(true); + + protField.set(data, subProt); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + data.subprotocol(true); + subProt = new TreeSet<String>(); + subProt.add("test"); + try { + protField = LocateDAO.Data.class.getDeclaredField("subprotocol"); + + protField.setAccessible(true); + + protField.set(data, subProt); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + data.subprotocol(true); + data.subprotocol(false); + + LocateDAO.Data newDate = data.copy(); + assertTrue(data.name.equals(newDate.name)); + } + } class LocateDAOImpl extends LocateDAO{ - - public LocateDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { - super(trans, historyDAO); - setPs(this, readPS, "createPS"); - } - + + public LocateDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { + super(trans, historyDAO); + setPs(this, readPS, "createPS"); + } + - public void setPs(LocateDAOImpl LocateDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(LocateDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + public void setPs(LocateDAOImpl LocateDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(LocateDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_Namespace.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_Namespace.java index 8de750c6..6bdb3d76 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_Namespace.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_Namespace.java @@ -37,69 +37,69 @@ import org.onap.aaf.misc.env.APIException; public class JU_Namespace { - Namespace namespace; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - } + Namespace namespace; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + } - @Test - public void testInit() { - new Namespace(); - NsDAO.Data data = new NsDAO.Data(); - data.name = "name"; - namespace = new Namespace(data); - assertTrue(namespace.name.equals("name")); - data.attrib = new HashMap<>(); - namespace = new Namespace(data); - data.attrib.put("test", "test"); - namespace = new Namespace(data); - } - - - - @Test - public void testSecondConstructor() { + @Test + public void testInit() { + new Namespace(); + NsDAO.Data data = new NsDAO.Data(); + data.name = "name"; + namespace = new Namespace(data); + assertTrue(namespace.name.equals("name")); + data.attrib = new HashMap<>(); + namespace = new Namespace(data); + data.attrib.put("test", "test"); + namespace = new Namespace(data); + } + + + + @Test + public void testSecondConstructor() { - NsDAO.Data data = new NsDAO.Data(); - data.name = "name"; - List<String> owner = new ArrayList<>(); - List<String> admin = new ArrayList<>();; - namespace = new Namespace(data,owner, admin); - assertTrue(namespace.name.equals("name")); - data.attrib = new HashMap<>(); - namespace = new Namespace(data,owner, admin); - data.attrib.put("test", "test"); - namespace = new Namespace(data ,owner, admin); - - NsDAO.Data retData = namespace.data(); - assertTrue(retData.name.equals("name")); - - } - @Test - public void testBytify() { - testSecondConstructor(); - try { - ByteBuffer retVal = namespace.bytify(); - namespace.reconstitute(retVal); - namespace.hashCode(); - namespace.toString(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testEquals() { - testSecondConstructor(); - NsDAO.Data data = new NsDAO.Data(); - data.name = "name"; - Namespace nameObj = null; - assertFalse(namespace.equals(nameObj)); - assertFalse(namespace.equals(data)); - nameObj = new Namespace(data); - assertTrue(namespace.equals(nameObj)); - } - + NsDAO.Data data = new NsDAO.Data(); + data.name = "name"; + List<String> owner = new ArrayList<>(); + List<String> admin = new ArrayList<>();; + namespace = new Namespace(data,owner, admin); + assertTrue(namespace.name.equals("name")); + data.attrib = new HashMap<>(); + namespace = new Namespace(data,owner, admin); + data.attrib.put("test", "test"); + namespace = new Namespace(data ,owner, admin); + + NsDAO.Data retData = namespace.data(); + assertTrue(retData.name.equals("name")); + + } + @Test + public void testBytify() { + testSecondConstructor(); + try { + ByteBuffer retVal = namespace.bytify(); + namespace.reconstitute(retVal); + namespace.hashCode(); + namespace.toString(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testEquals() { + testSecondConstructor(); + NsDAO.Data data = new NsDAO.Data(); + data.name = "name"; + Namespace nameObj = null; + assertFalse(namespace.equals(nameObj)); + assertFalse(namespace.equals(data)); + nameObj = new Namespace(data); + assertTrue(namespace.equals(nameObj)); + } + }
\ No newline at end of file diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_NsDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_NsDAO.java index d5af0a63..9be4f5a2 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_NsDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_NsDAO.java @@ -68,818 +68,818 @@ import com.datastax.driver.core.Session; public class JU_NsDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - Session session; - @Mock - ResultSet rs; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn(session).when(cluster).connect("test"); - Mockito.doReturn(Mockito.mock(TimeTaken.class)).when(trans).start(Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); - - Iterator<Row> ite = Mockito.mock(Iterator.class); - Mockito.doReturn(ite).when(rs).iterator(); - Mockito.doReturn(rs).when(session).execute(Mockito.anyString()); - } - - @Test - public void testInit() { - try { - Session session = Mockito.mock(Session.class); - new NsDAOImpl(trans, cluster, "test", session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void setPsByStartAndTarget(NsDAO NsDAOObj, PSInfo psInfoObj, String fieldName) { - Field nsDaoField; - try { - nsDaoField = NsDAO.class.getDeclaredField(fieldName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(NsDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("NsDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on NsDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doNothing().when(tt).done(); - NsDAO.Data data = new NsDAO.Data(); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - - NsDAO daoObj = null; - try { - daoObj = new NsDAO(trans, historyDAO, cacheInfoDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - daoObj.wasModified(trans, CRUD.create, data, new String[] {}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - - rs1 = new Result<ResultSet>(null,1,"test",new Object[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - } - - @Test - public void testSecondConstructor() { - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - - try { - new NsDAO(trans, historyDAO, cacheInfoDAO); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - @Test - public void testNSLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = NsDAO.class.getDeclaredClasses(); - for(Class<?> indCls:innerClassArr) { - if(indCls.getName().contains("NSLoader")) { - innerClass = indCls; - break; - } - } - + @Mock + Cluster cluster; + @Mock + Session session; + @Mock + ResultSet rs; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn(session).when(cluster).connect("test"); + Mockito.doReturn(Mockito.mock(TimeTaken.class)).when(trans).start(Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); + + Iterator<Row> ite = Mockito.mock(Iterator.class); + Mockito.doReturn(ite).when(rs).iterator(); + Mockito.doReturn(rs).when(session).execute(Mockito.anyString()); + } + + @Test + public void testInit() { + try { + Session session = Mockito.mock(Session.class); + new NsDAOImpl(trans, cluster, "test", session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void setPsByStartAndTarget(NsDAO NsDAOObj, PSInfo psInfoObj, String fieldName) { + Field nsDaoField; + try { + nsDaoField = NsDAO.class.getDeclaredField(fieldName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(NsDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("NsDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on NsDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doNothing().when(tt).done(); + NsDAO.Data data = new NsDAO.Data(); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + + NsDAO daoObj = null; + try { + daoObj = new NsDAO(trans, historyDAO, cacheInfoDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + daoObj.wasModified(trans, CRUD.create, data, new String[] {}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + + rs1 = new Result<ResultSet>(null,1,"test",new Object[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + } + + @Test + public void testSecondConstructor() { + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + + try { + new NsDAO(trans, historyDAO, cacheInfoDAO); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + + @Test + public void testNSLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = NsDAO.class.getDeclaredClasses(); + for(Class<?> indCls:innerClassArr) { + if(indCls.getName().contains("NSLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - NsDAO.Data data = new NsDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {NsDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {NsDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {NsDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {NsDAO.Data.class, DataOutputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dos }); - - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DataInputStream dis = new DataInputStream(bais); - innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {NsDAO.Data.class, DataInputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testCreate() { - PSInfo psObj = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doReturn("test user").when(trans).user(); - - Result<NsDAO.Data> retVal = daoObj.create(trans,data); - assertTrue(retVal.status == 4); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - data.parent = "parent"; - data.attrib = new HashMap<>(); - data.attrib.put("test", "test"); - - Field cbField; - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - try { - cbField = CassAccess.class.getDeclaredField("cb"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - retVal = daoObj.create(trans,data); - assertTrue(retVal.status == 9); - - Field owningField; - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - try { - owningField = AbsCassDAO.class.getDeclaredField("owningDAO"); - owningField.setAccessible(true); - owningField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.create(trans,data); - assertTrue(retVal.status == 0); - - } - - @Test - public void testUpdate() { - PSInfo psObj = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doReturn("test user").when(trans).user(); - - Result<Void> retVal = daoObj.update(trans,data); - assertTrue(retVal.status == 4); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - data.parent = "parent"; - data.attrib = new HashMap<>(); - data.attrib.put("test", "test"); - Field cbField; - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - retVal = daoObj.update(trans,data); - assertTrue(retVal.status == 0); - - ResultSet rsMock = Mockito.mock(ResultSet.class); - Iterator<Row> iteMock = Mockito.mock(Iterator.class); - Mockito.doReturn(iteMock).when(rsMock).iterator(); - Row rowMock = Mockito.mock(Row.class); - Mockito.doReturn(rowMock).when(iteMock).next(); - Mockito.when(iteMock.hasNext()).thenReturn(true, false); - Mockito.doReturn("test").when(rowMock).getString(Mockito.anyInt()); - Mockito.doReturn(rsMock).when(session).execute(Mockito.anyString()); - retVal = daoObj.update(trans,data); - assertTrue(retVal.status == 0); - } - - @Test - public void testRead() { - PSInfo psObj = Mockito.mock(PSInfo.class); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doReturn("test user").when(trans).user(); - - Result<List<Data>> retVal = daoObj.read(trans,data); - assertTrue(retVal.status == 0); - - List<Data> dataAL= new ArrayList<>(); - dataAL.add(data); - rs1 = new Result<List<Data>>(dataAL,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - Field cbField; - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.read(trans,data); - assertTrue(retVal.status == 0); - - } - - @Test - public void testReadByObject() { - PSInfo psObj = Mockito.mock(PSInfo.class); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", new Object[] {}); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doReturn("test user").when(trans).user(); - - Result<List<Data>> retVal = daoObj.read(trans,new Object[] {}); - assertTrue(retVal.status == 0); - - List<Data> dataAL= new ArrayList<>(); - dataAL.add(data); - rs1 = new Result<List<Data>>(dataAL,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", new Object[] {}); - Field cbField; - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.read(trans,new Object[] {}); - assertTrue(retVal.status == 0); - - } - - @Test - public void testDelete() { - PSInfo psObj = Mockito.mock(PSInfo.class); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Mockito.doReturn("test user").when(trans).user(); - Field cbField; - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Void> retVal = daoObj.delete(trans,data, false); - assertTrue(retVal.status == 0); - - List<Data> dataAL= new ArrayList<>(); - dataAL.add(data); - rs1 = new Result<List<Data>>(dataAL,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - - retVal = daoObj.delete(trans,data, false); - assertTrue(retVal.status == 0); - - } - - @Test - public void testReadNsByAttrib() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Mockito.doReturn("test user").when(trans).user(); - Field cbField; - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Set<String>> retVal = daoObj.readNsByAttrib(trans,"test"); - assertTrue(retVal.status == 0); - - ResultSet rsMock = Mockito.mock(ResultSet.class); - Iterator<Row> iteMock = Mockito.mock(Iterator.class); - Mockito.doReturn(iteMock).when(rsMock).iterator(); - Row rowMock = Mockito.mock(Row.class); - Mockito.doReturn(rowMock).when(iteMock).next(); - Mockito.when(iteMock.hasNext()).thenReturn(true, false); - Mockito.doReturn("test").when(rowMock).getString(Mockito.anyInt()); - Mockito.doReturn(rsMock).when(session).execute(Mockito.anyString()); - - retVal = daoObj.readNsByAttrib(trans,"test"); - assertTrue(retVal.status == 0); - - } - @Test - public void testAttribAdd() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Mockito.doReturn("test user").when(trans).user(); - Field cbField; - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Void> retVal = daoObj.attribAdd(trans, "test", "test", "test"); - assertTrue(retVal.status == 0); - } - - @Test - public void testAttribRemove() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Mockito.doReturn("test user").when(trans).user(); - Field cbField; - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Void> retVal = daoObj.attribRemove(trans, "test", "test"); - assertTrue(retVal.status == 0); - } - - @Test - public void testAddDescription() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - NsDAO.Data data = new NsDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - rs1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("test user").when(trans).user(); - Field cbField; - try { - cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Void> retVal = daoObj.addDescription(trans, "test", "test"); - assertTrue(retVal.status == 0); - } - - @Test - public void testGetChildren() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - NsDAOImpl daoObj=null; - try { - daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<List<Data>> retVal = daoObj.getChildren(trans, "test"); - assertNull(retVal); - } - - @Test - public void testData() { - NsDAO.Data data = new NsDAO.Data(); - data.attrib = null; - data.attrib(true); - - data.attrib = new HashMap<>(); - data.attrib(true); - - data.attrib(false); - data.attrib = new ConcurrentHashMap<>(); - data.attrib(true); - - data.name="123"; - data.split("test"); - - data.toString(); - } + + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + NsDAO.Data data = new NsDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {NsDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {NsDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {NsDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {NsDAO.Data.class, DataOutputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dos }); + + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + DataInputStream dis = new DataInputStream(bais); + innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {NsDAO.Data.class, DataInputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testCreate() { + PSInfo psObj = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doReturn("test user").when(trans).user(); + + Result<NsDAO.Data> retVal = daoObj.create(trans,data); + assertTrue(retVal.status == 4); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + data.parent = "parent"; + data.attrib = new HashMap<>(); + data.attrib.put("test", "test"); + + Field cbField; + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + try { + cbField = CassAccess.class.getDeclaredField("cb"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + retVal = daoObj.create(trans,data); + assertTrue(retVal.status == 9); + + Field owningField; + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + try { + owningField = AbsCassDAO.class.getDeclaredField("owningDAO"); + owningField.setAccessible(true); + owningField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.create(trans,data); + assertTrue(retVal.status == 0); + + } + + @Test + public void testUpdate() { + PSInfo psObj = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doReturn("test user").when(trans).user(); + + Result<Void> retVal = daoObj.update(trans,data); + assertTrue(retVal.status == 4); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + data.parent = "parent"; + data.attrib = new HashMap<>(); + data.attrib.put("test", "test"); + Field cbField; + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + retVal = daoObj.update(trans,data); + assertTrue(retVal.status == 0); + + ResultSet rsMock = Mockito.mock(ResultSet.class); + Iterator<Row> iteMock = Mockito.mock(Iterator.class); + Mockito.doReturn(iteMock).when(rsMock).iterator(); + Row rowMock = Mockito.mock(Row.class); + Mockito.doReturn(rowMock).when(iteMock).next(); + Mockito.when(iteMock.hasNext()).thenReturn(true, false); + Mockito.doReturn("test").when(rowMock).getString(Mockito.anyInt()); + Mockito.doReturn(rsMock).when(session).execute(Mockito.anyString()); + retVal = daoObj.update(trans,data); + assertTrue(retVal.status == 0); + } + + @Test + public void testRead() { + PSInfo psObj = Mockito.mock(PSInfo.class); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doReturn("test user").when(trans).user(); + + Result<List<Data>> retVal = daoObj.read(trans,data); + assertTrue(retVal.status == 0); + + List<Data> dataAL= new ArrayList<>(); + dataAL.add(data); + rs1 = new Result<List<Data>>(dataAL,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + Field cbField; + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.read(trans,data); + assertTrue(retVal.status == 0); + + } + + @Test + public void testReadByObject() { + PSInfo psObj = Mockito.mock(PSInfo.class); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", new Object[] {}); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doReturn("test user").when(trans).user(); + + Result<List<Data>> retVal = daoObj.read(trans,new Object[] {}); + assertTrue(retVal.status == 0); + + List<Data> dataAL= new ArrayList<>(); + dataAL.add(data); + rs1 = new Result<List<Data>>(dataAL,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", new Object[] {}); + Field cbField; + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.read(trans,new Object[] {}); + assertTrue(retVal.status == 0); + + } + + @Test + public void testDelete() { + PSInfo psObj = Mockito.mock(PSInfo.class); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Mockito.doReturn("test user").when(trans).user(); + Field cbField; + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Void> retVal = daoObj.delete(trans,data, false); + assertTrue(retVal.status == 0); + + List<Data> dataAL= new ArrayList<>(); + dataAL.add(data); + rs1 = new Result<List<Data>>(dataAL,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + + retVal = daoObj.delete(trans,data, false); + assertTrue(retVal.status == 0); + + } + + @Test + public void testReadNsByAttrib() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Mockito.doReturn("test user").when(trans).user(); + Field cbField; + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Set<String>> retVal = daoObj.readNsByAttrib(trans,"test"); + assertTrue(retVal.status == 0); + + ResultSet rsMock = Mockito.mock(ResultSet.class); + Iterator<Row> iteMock = Mockito.mock(Iterator.class); + Mockito.doReturn(iteMock).when(rsMock).iterator(); + Row rowMock = Mockito.mock(Row.class); + Mockito.doReturn(rowMock).when(iteMock).next(); + Mockito.when(iteMock.hasNext()).thenReturn(true, false); + Mockito.doReturn("test").when(rowMock).getString(Mockito.anyInt()); + Mockito.doReturn(rsMock).when(session).execute(Mockito.anyString()); + + retVal = daoObj.readNsByAttrib(trans,"test"); + assertTrue(retVal.status == 0); + + } + @Test + public void testAttribAdd() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Mockito.doReturn("test user").when(trans).user(); + Field cbField; + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Void> retVal = daoObj.attribAdd(trans, "test", "test", "test"); + assertTrue(retVal.status == 0); + } + + @Test + public void testAttribRemove() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Mockito.doReturn("test user").when(trans).user(); + Field cbField; + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Void> retVal = daoObj.attribRemove(trans, "test", "test"); + assertTrue(retVal.status == 0); + } + + @Test + public void testAddDescription() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + NsDAO.Data data = new NsDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "NsDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "NsDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + rs1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("test user").when(trans).user(); + Field cbField; + try { + cbField = AbsCassDAO.class.getDeclaredField("owningDAO"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Void> retVal = daoObj.addDescription(trans, "test", "test"); + assertTrue(retVal.status == 0); + } + + @Test + public void testGetChildren() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + NsDAOImpl daoObj=null; + try { + daoObj = new NsDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, session); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<List<Data>> retVal = daoObj.getChildren(trans, "test"); + assertNull(retVal); + } + + @Test + public void testData() { + NsDAO.Data data = new NsDAO.Data(); + data.attrib = null; + data.attrib(true); + + data.attrib = new HashMap<>(); + data.attrib(true); + + data.attrib(false); + data.attrib = new ConcurrentHashMap<>(); + data.attrib(true); + + data.name="123"; + data.split("test"); + + data.toString(); + } } class NsDAOImpl extends NsDAO{ - -// public NsDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { -// super(trans, historyDAO); -// setSession(this, Mockito.mock(Session.class)); -// } - - - public NsDAOImpl(AuthzTrans trans, Cluster cluster, String keySpace, Session session)throws APIException, IOException { - super(trans, cluster, keySpace); - setSession(this, session); - } - - - public NsDAOImpl(AuthzTrans trans, HistoryDAO historyDAO, CacheInfoDAO cacheInfoDAO, - org.onap.aaf.auth.dao.AbsCassDAO.PSInfo psObj, Session session) throws APIException, IOException { - super(trans, historyDAO, cacheInfoDAO); - setPs(this, psObj, "createPS"); - setPs(this, psObj, "updatePS"); - setPs(this, psObj, "readPS"); - setPs(this, psObj, "deletePS"); - setPsNs(this, psObj, "psNS"); - setSession(this, session); - } - public void setPsNs(NsDAOImpl NsDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = NsDAO.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(NsDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void setPs(NsDAOImpl NsDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(NsDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - public void setSession(NsDAOImpl approvalDaoObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(approvalDaoObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + +// public NsDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { +// super(trans, historyDAO); +// setSession(this, Mockito.mock(Session.class)); +// } + + + public NsDAOImpl(AuthzTrans trans, Cluster cluster, String keySpace, Session session)throws APIException, IOException { + super(trans, cluster, keySpace); + setSession(this, session); + } + + + public NsDAOImpl(AuthzTrans trans, HistoryDAO historyDAO, CacheInfoDAO cacheInfoDAO, + org.onap.aaf.auth.dao.AbsCassDAO.PSInfo psObj, Session session) throws APIException, IOException { + super(trans, historyDAO, cacheInfoDAO); + setPs(this, psObj, "createPS"); + setPs(this, psObj, "updatePS"); + setPs(this, psObj, "readPS"); + setPs(this, psObj, "deletePS"); + setPsNs(this, psObj, "psNS"); + setSession(this, session); + } + public void setPsNs(NsDAOImpl NsDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = NsDAO.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(NsDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void setPs(NsDAOImpl NsDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(NsDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + public void setSession(NsDAOImpl approvalDaoObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(approvalDaoObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_OAuthTokenDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_OAuthTokenDAO.java index e8de65ad..5c158b6a 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_OAuthTokenDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_OAuthTokenDAO.java @@ -59,214 +59,214 @@ import com.datastax.driver.core.Row; public class JU_OAuthTokenDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - } + @Mock + Cluster cluster; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + } - @Test - public void testInit() { - OAuthTokenDAO daoObj = new OAuthTokenDAO(trans, cluster, "test"); -// daoObj. - } - @Test - public void testReadByUser() { - OAuthTokenDAO daoObj = new OAuthTokenDAO(trans, cluster, "test"); - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psByUser"); - - Result<List<OAuthTokenDAO.Data>> rs1 = new Result<List<OAuthTokenDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "OAuthTokenDAO READ", new Object[]{"test"}); - - daoObj.readByUser(trans, "test"); - } - - public void setPsByStartAndTarget(OAuthTokenDAO OAuthTokenDAOObj, PSInfo psInfoObj, String fieldName) { - Field nsDaoField; - try { - nsDaoField = OAuthTokenDAO.class.getDeclaredField(fieldName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(OAuthTokenDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("OAuthTokenDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on OAuthTokenDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doNothing().when(tt).done(); - OAuthTokenDAO.Data data = new OAuthTokenDAO.Data(); + @Test + public void testInit() { + OAuthTokenDAO daoObj = new OAuthTokenDAO(trans, cluster, "test"); +// daoObj. + } + @Test + public void testReadByUser() { + OAuthTokenDAO daoObj = new OAuthTokenDAO(trans, cluster, "test"); + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psByUser"); + + Result<List<OAuthTokenDAO.Data>> rs1 = new Result<List<OAuthTokenDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "OAuthTokenDAO READ", new Object[]{"test"}); + + daoObj.readByUser(trans, "test"); + } + + public void setPsByStartAndTarget(OAuthTokenDAO OAuthTokenDAOObj, PSInfo psInfoObj, String fieldName) { + Field nsDaoField; + try { + nsDaoField = OAuthTokenDAO.class.getDeclaredField(fieldName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(OAuthTokenDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("OAuthTokenDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on OAuthTokenDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doNothing().when(tt).done(); + OAuthTokenDAO.Data data = new OAuthTokenDAO.Data(); - OAuthTokenDAO daoObj = null; - daoObj = new OAuthTokenDAO(trans, cluster, "test" ); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - } - - @Test - public void testSecondConstructor() { - AbsCassDAO absCassDAO = Mockito.mock(AbsCassDAO.class); + OAuthTokenDAO daoObj = null; + daoObj = new OAuthTokenDAO(trans, cluster, "test" ); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + } + + @Test + public void testSecondConstructor() { + AbsCassDAO absCassDAO = Mockito.mock(AbsCassDAO.class); - OAuthTokenDAO daoObj = new OAuthTokenDAO(trans, absCassDAO); - - } + OAuthTokenDAO daoObj = new OAuthTokenDAO(trans, absCassDAO); + + } - @Test - public void testData(){ - OAuthTokenDAO.Data data = new OAuthTokenDAO.Data(); - data.scopes = null; - data.scopes(true); + @Test + public void testData(){ + OAuthTokenDAO.Data data = new OAuthTokenDAO.Data(); + data.scopes = null; + data.scopes(true); - data.scopes = new HashSet<>(); - data.scopes(true); + data.scopes = new HashSet<>(); + data.scopes(true); - data.scopes(false); - data.scopes = new ConcurrentHashSet<>(); - data.scopes(true); - - data.expires = new Date(); - data.user="test"; - data.id="id"; - data.toString(); - - data.active=true; - data.toString(); - - try { - ByteBuffer bb = data.bytify(); - data.reconstitute(bb); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testOAuthLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = OAuthTokenDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("OAuthLoader")) { - innerClass = indCls; - break; - } - } - + data.scopes(false); + data.scopes = new ConcurrentHashSet<>(); + data.scopes(true); + + data.expires = new Date(); + data.user="test"; + data.id="id"; + data.toString(); + + data.active=true; + data.toString(); + + try { + ByteBuffer bb = data.bytify(); + data.reconstitute(bb); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testOAuthLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = OAuthTokenDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("OAuthLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - OAuthTokenDAO.Data data = new OAuthTokenDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {OAuthTokenDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {OAuthTokenDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {OAuthTokenDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test","test"} }); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {OAuthTokenDAO.Data.class, DataOutputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dos }); + + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + OAuthTokenDAO.Data data = new OAuthTokenDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {OAuthTokenDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {OAuthTokenDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {OAuthTokenDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test","test"} }); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {OAuthTokenDAO.Data.class, DataOutputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dos }); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DataInputStream dis = new DataInputStream(bais); - innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {OAuthTokenDAO.Data.class, DataInputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + DataInputStream dis = new DataInputStream(bais); + innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {OAuthTokenDAO.Data.class, DataInputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } class OAuthTokenDAOImpl extends OAuthTokenDAO{ - - public OAuthTokenDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { - super(trans, historyDAO); - setPs(this, readPS, "createPS"); - } - + + public OAuthTokenDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,PSInfo readPS ) throws APIException, IOException { + super(trans, historyDAO); + setPs(this, readPS, "createPS"); + } + - public void setPs(OAuthTokenDAOImpl OAuthTokenDAOObj, PSInfo psInfoObj, String methodName) { - Field nsDaoField; - try { - nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(OAuthTokenDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + public void setPs(OAuthTokenDAOImpl OAuthTokenDAOObj, PSInfo psInfoObj, String methodName) { + Field nsDaoField; + try { + nsDaoField = CassDAOImpl.class.getDeclaredField(methodName); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(OAuthTokenDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_PermDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_PermDAO.java index c92420da..57f39922 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_PermDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_PermDAO.java @@ -63,591 +63,591 @@ import com.datastax.driver.core.Session; public class JU_PermDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - Session session; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); - Mockito.doReturn(session).when(cluster).connect("test"); - } + @Mock + Cluster cluster; + @Mock + Session session; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); + Mockito.doReturn(session).when(cluster).connect("test"); + } - @Test - public void testInit() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - try { - Session session = Mockito.mock(Session.class); - PermDAO daoObj = new PermDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// daoObj. - } - @Test - public void testReadByStartAndTarget() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - PermDAO daoObj = null; - try { - Session session = Mockito.mock(Session.class); - daoObj = new PermDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psByType"); - - Result<List<PermDAO.Data>> rs1 = new Result<List<PermDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAO READ", new Object[]{"test"}); - - daoObj.readByType(trans, "test", "test"); - } - @Test - public void testReadChildren() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - PermDAO daoObj = null; - try { - Session session = Mockito.mock(Session.class); - daoObj = new PermDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psChildren"); - - Result<List<PermDAO.Data>> rs1 = new Result<List<PermDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAO READ", new Object[]{"test"}); - - daoObj.readChildren(trans, "test", "test"); - } - @Test - public void testReadNs() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - PermDAO daoObj = null; - try { - Session session = Mockito.mock(Session.class); - daoObj = new PermDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psNS"); - - Result<List<PermDAO.Data>> rs1 = new Result<List<PermDAO.Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAO READ", new Object[]{"test"}); - - daoObj.readNS(trans, "test"); - } - @Test - public void testAddRole() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - PermDAO.Data data = new PermDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - PermDAOImpl daoObj=null; - try { - daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + @Test + public void testInit() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + try { + Session session = Mockito.mock(Session.class); + PermDAO daoObj = new PermDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } +// daoObj. + } + @Test + public void testReadByStartAndTarget() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + PermDAO daoObj = null; + try { + Session session = Mockito.mock(Session.class); + daoObj = new PermDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psByType"); + + Result<List<PermDAO.Data>> rs1 = new Result<List<PermDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAO READ", new Object[]{"test"}); + + daoObj.readByType(trans, "test", "test"); + } + @Test + public void testReadChildren() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + PermDAO daoObj = null; + try { + Session session = Mockito.mock(Session.class); + daoObj = new PermDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psChildren"); + + Result<List<PermDAO.Data>> rs1 = new Result<List<PermDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAO READ", new Object[]{"test"}); + + daoObj.readChildren(trans, "test", "test"); + } + @Test + public void testReadNs() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + PermDAO daoObj = null; + try { + Session session = Mockito.mock(Session.class); + daoObj = new PermDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psNS"); + + Result<List<PermDAO.Data>> rs1 = new Result<List<PermDAO.Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAO READ", new Object[]{"test"}); + + daoObj.readNS(trans, "test"); + } + @Test + public void testAddRole() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + PermDAO.Data data = new PermDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + PermDAOImpl daoObj=null; + try { + daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - rs1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("test user").when(trans).user(); - Field cbField; - try { - cbField = CassAccess.class.getDeclaredField("cb"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PermDAO.Data perm = new PermDAO.Data(); - Result<Void> retVal = daoObj.addRole(trans, perm, "test"); - assertTrue(retVal.status == 9); - - Field owningField; - try { - owningField = AbsCassDAO.class.getDeclaredField("owningDAO"); - owningField.setAccessible(true); - owningField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.addRole(trans, perm, "test"); - assertTrue(retVal.status == 0); - } - - @Test - public void testDelRole() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - PermDAO.Data data = new PermDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - PermDAOImpl daoObj=null; - try { - daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + rs1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("test user").when(trans).user(); + Field cbField; + try { + cbField = CassAccess.class.getDeclaredField("cb"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PermDAO.Data perm = new PermDAO.Data(); + Result<Void> retVal = daoObj.addRole(trans, perm, "test"); + assertTrue(retVal.status == 9); + + Field owningField; + try { + owningField = AbsCassDAO.class.getDeclaredField("owningDAO"); + owningField.setAccessible(true); + owningField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.addRole(trans, perm, "test"); + assertTrue(retVal.status == 0); + } + + @Test + public void testDelRole() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + PermDAO.Data data = new PermDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + PermDAOImpl daoObj=null; + try { + daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - rs1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("test user").when(trans).user(); - - PermDAO.Data perm = new PermDAO.Data(); - Field cbField; - try { - cbField = CassAccess.class.getDeclaredField("cb"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Void> retVal = daoObj.delRole(trans, perm, "test"); - assertTrue(retVal.status == 9); - - Field owningDaoField; - try { - owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); - owningDaoField.setAccessible(true); - owningDaoField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.delRole(trans, perm, "test"); - assertTrue(retVal.status == 0); - } - - @Test - public void testAddDescription() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - PermDAO.Data data = new PermDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - PermDAOImpl daoObj=null; - try { - daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + rs1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("test user").when(trans).user(); + + PermDAO.Data perm = new PermDAO.Data(); + Field cbField; + try { + cbField = CassAccess.class.getDeclaredField("cb"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Void> retVal = daoObj.delRole(trans, perm, "test"); + assertTrue(retVal.status == 9); + + Field owningDaoField; + try { + owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); + owningDaoField.setAccessible(true); + owningDaoField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.delRole(trans, perm, "test"); + assertTrue(retVal.status == 0); + } + + @Test + public void testAddDescription() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + PermDAO.Data data = new PermDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + PermDAOImpl daoObj=null; + try { + daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Result<Void> rs2 = new Result<Void>(null,1,"test",new String[0]); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - rs1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("test user").when(trans).user(); - - PermDAO.Data perm = new PermDAO.Data(); - Field cbField; - try { - cbField = CassAccess.class.getDeclaredField("cb"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Void> retVal = daoObj.addDescription(trans, "test", "test", "test", "test", "test"); - assertTrue(retVal.status == 9); - - Field owningDaoField; - try { - owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); - owningDaoField.setAccessible(true); - owningDaoField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.addDescription(trans, "test", "test", "test", "test", "test"); - assertTrue(retVal.status == 0); - } - - public void setPsByStartAndTarget(PermDAO PermDAOObj, PSInfo psInfoObj, String fieldName) { - Field PermDAOField; - try { - PermDAOField = PermDAO.class.getDeclaredField(fieldName); - - PermDAOField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(PermDAOField, PermDAOField.getModifiers() & ~Modifier.FINAL); - - PermDAOField.set(PermDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doNothing().when(tt).done(); - PermDAO.Data data = new PermDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - PermDAOImpl daoObj = null; - try { - daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, createPS ); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - daoObj.wasModified(trans, CRUD.create, data, new String[] {}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); - } - - @Test - public void testSecondConstructor() { - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "PermDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "PermDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Result<Void> rs2 = new Result<Void>(null,1,"test",new String[0]); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + rs1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("test user").when(trans).user(); + + PermDAO.Data perm = new PermDAO.Data(); + Field cbField; + try { + cbField = CassAccess.class.getDeclaredField("cb"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Void> retVal = daoObj.addDescription(trans, "test", "test", "test", "test", "test"); + assertTrue(retVal.status == 9); + + Field owningDaoField; + try { + owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); + owningDaoField.setAccessible(true); + owningDaoField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.addDescription(trans, "test", "test", "test", "test", "test"); + assertTrue(retVal.status == 0); + } + + public void setPsByStartAndTarget(PermDAO PermDAOObj, PSInfo psInfoObj, String fieldName) { + Field PermDAOField; + try { + PermDAOField = PermDAO.class.getDeclaredField(fieldName); + + PermDAOField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(PermDAOField, PermDAOField.getModifiers() & ~Modifier.FINAL); + + PermDAOField.set(PermDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("PermDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on PermDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doNothing().when(tt).done(); + PermDAO.Data data = new PermDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + PermDAOImpl daoObj = null; + try { + daoObj = new PermDAOImpl(trans, historyDAO, cacheInfoDAO, createPS ); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + daoObj.wasModified(trans, CRUD.create, data, new String[] {}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); + } + + @Test + public void testSecondConstructor() { + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - PermDAO daoObj = new PermDAO(trans, historyDAO, cacheInfoDAO); - - } + PermDAO daoObj = new PermDAO(trans, historyDAO, cacheInfoDAO); + + } - @Test - public void testFutureLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = PermDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("PermLoader")) { - innerClass = indCls; - break; - } - } - + @Test + public void testFutureLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = PermDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("PermLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - PermDAO.Data data = new PermDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {PermDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {PermDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {PermDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {PermDAO.Data.class, DataOutputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dos }); + + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + PermDAO.Data data = new PermDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {PermDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {PermDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {PermDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {PermDAO.Data.class, DataOutputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dos }); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DataInputStream dis = new DataInputStream(bais); - innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {PermDAO.Data.class, DataInputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testData() { - PermDAO.Data data = new PermDAO.Data(); - NsSplit nss = new NsSplit("test", "test"); - data = new PermDAO.Data(nss, "test", "test"); - - data.toString(); - - assertTrue("test.test|test|test".equalsIgnoreCase(data.fullPerm())); - - Question q = Mockito.mock( Question.class); - - Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); - Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); - Result<Data> retVal= PermDAO.Data.decode(trans, q, "test|||"); - assertTrue(retVal.status==0); - Result<String[]> retVal1= PermDAO.Data.decodeToArray(trans, q, "test|||"); - assertTrue(retVal.status==0); - retVal= PermDAO.Data.decode(trans, q, "test||"); - retVal1= PermDAO.Data.decodeToArray(trans, q, "test||"); - assertTrue(retVal.status==0); - - rs = new Result<NsSplit>(nss,1,"test",new Object[0]); - Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); - retVal= PermDAO.Data.decode(trans, q, "test||"); - retVal1= PermDAO.Data.decodeToArray(trans, q, "test||"); - assertTrue(retVal.status==1); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + DataInputStream dis = new DataInputStream(bais); + innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {PermDAO.Data.class, DataInputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testData() { + PermDAO.Data data = new PermDAO.Data(); + NsSplit nss = new NsSplit("test", "test"); + data = new PermDAO.Data(nss, "test", "test"); + + data.toString(); + + assertTrue("test.test|test|test".equalsIgnoreCase(data.fullPerm())); + + Question q = Mockito.mock( Question.class); + + Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); + Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); + Result<Data> retVal= PermDAO.Data.decode(trans, q, "test|||"); + assertTrue(retVal.status==0); + Result<String[]> retVal1= PermDAO.Data.decodeToArray(trans, q, "test|||"); + assertTrue(retVal.status==0); + retVal= PermDAO.Data.decode(trans, q, "test||"); + retVal1= PermDAO.Data.decodeToArray(trans, q, "test||"); + assertTrue(retVal.status==0); + + rs = new Result<NsSplit>(nss,1,"test",new Object[0]); + Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); + retVal= PermDAO.Data.decode(trans, q, "test||"); + retVal1= PermDAO.Data.decodeToArray(trans, q, "test||"); + assertTrue(retVal.status==1); - retVal= PermDAO.Data.decode(trans, q, "test|"); - retVal1= PermDAO.Data.decodeToArray(trans, q, "test|"); - assertTrue(retVal.status==4); - - NsDAO.Data ns = new NsDAO.Data(); - ns.name="test"; - PermDAO.Data.create(ns, "test"); + retVal= PermDAO.Data.decode(trans, q, "test|"); + retVal1= PermDAO.Data.decodeToArray(trans, q, "test|"); + assertTrue(retVal.status==4); + + NsDAO.Data ns = new NsDAO.Data(); + ns.name="test"; + PermDAO.Data.create(ns, "test"); - PermDAO.Data.create(trans,q, "test"); - rs = new Result<NsSplit>(nss,0,"test",new Object[0]); - Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); - PermDAO.Data.create(trans,q, "test|test|test|test"); - } - + PermDAO.Data.create(trans,q, "test"); + rs = new Result<NsSplit>(nss,0,"test",new Object[0]); + Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); + PermDAO.Data.create(trans,q, "test|test|test|test"); + } + } class PermDAOImpl extends PermDAO{ - public PermDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS) throws APIException, IOException { - super(trans, historyDAO, cacheDao); - setPs(this, readPS, "createPS"); - } - - public PermDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS, Session session ) throws APIException, IOException { - super(trans, historyDAO, cacheDao); - setPs(this, readPS, "createPS"); - setSession(this, session); - } - + public PermDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS) throws APIException, IOException { + super(trans, historyDAO, cacheDao); + setPs(this, readPS, "createPS"); + } + + public PermDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS, Session session ) throws APIException, IOException { + super(trans, historyDAO, cacheDao); + setPs(this, readPS, "createPS"); + setSession(this, session); + } + - public void setPs(PermDAOImpl PermDAOObj, PSInfo psInfoObj, String methodName) { - Field PermDAOField; - try { - PermDAOField = CassDAOImpl.class.getDeclaredField(methodName); - - PermDAOField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(PermDAOField, PermDAOField.getModifiers() & ~Modifier.FINAL); - - PermDAOField.set(PermDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void setSession(PermDAOImpl approvalDaoObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(approvalDaoObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setPs(PermDAOImpl PermDAOObj, PSInfo psInfoObj, String methodName) { + Field PermDAOField; + try { + PermDAOField = CassDAOImpl.class.getDeclaredField(methodName); + + PermDAOField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(PermDAOField, PermDAOField.getModifiers() & ~Modifier.FINAL); + + PermDAOField.set(PermDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void setSession(PermDAOImpl approvalDaoObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(approvalDaoObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_RoleDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_RoleDAO.java index fa023af3..4057a6ed 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_RoleDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_RoleDAO.java @@ -64,602 +64,602 @@ import com.datastax.driver.core.Session; public class JU_RoleDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - Session session; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); - Mockito.doReturn(session).when(cluster).connect("test"); - } + @Mock + Cluster cluster; + @Mock + Session session; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); + Mockito.doReturn(session).when(cluster).connect("test"); + } - @Test - public void testInit() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - try { - new RoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// daoObj. - } - @Test - public void testReadByStartAndTarget() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - RoleDAO daoObj = null; - try { - daoObj = new RoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psName"); - - Result<List<RoleDAO.Data>> rs1 = new Result<List<RoleDAO.Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAO READ", new Object[]{"test"}); - - daoObj.readName(trans, "test"); - } - @Test - public void testReadChildren() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - RoleDAO daoObj = null; - try { - daoObj = new RoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psChildren"); - - Result<List<RoleDAO.Data>> rs1 = new Result<List<RoleDAO.Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAO READ", new Object[]{"test"}); - - daoObj.readChildren(trans, "test", "test"); - - daoObj.readChildren(trans, "test", "*"); - daoObj.readChildren(trans, "test", ""); - } - @Test - public void testReadNs() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - RoleDAO daoObj = null; - try { - daoObj = new RoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psNS"); - - Result<List<RoleDAO.Data>> rs1 = new Result<List<RoleDAO.Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAO READ", new Object[]{"test"}); - - daoObj.readNS(trans, "test"); - } - @Test - public void testAddRole() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - RoleDAO.Data data = new RoleDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - RoleDAOImpl daoObj=null; - try { - daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + @Test + public void testInit() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + try { + new RoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } +// daoObj. + } + @Test + public void testReadByStartAndTarget() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + RoleDAO daoObj = null; + try { + daoObj = new RoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psName"); + + Result<List<RoleDAO.Data>> rs1 = new Result<List<RoleDAO.Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAO READ", new Object[]{"test"}); + + daoObj.readName(trans, "test"); + } + @Test + public void testReadChildren() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + RoleDAO daoObj = null; + try { + daoObj = new RoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psChildren"); + + Result<List<RoleDAO.Data>> rs1 = new Result<List<RoleDAO.Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAO READ", new Object[]{"test"}); + + daoObj.readChildren(trans, "test", "test"); + + daoObj.readChildren(trans, "test", "*"); + daoObj.readChildren(trans, "test", ""); + } + @Test + public void testReadNs() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + RoleDAO daoObj = null; + try { + daoObj = new RoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psNS"); + + Result<List<RoleDAO.Data>> rs1 = new Result<List<RoleDAO.Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAO READ", new Object[]{"test"}); + + daoObj.readNS(trans, "test"); + } + @Test + public void testAddRole() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + RoleDAO.Data data = new RoleDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + RoleDAOImpl daoObj=null; + try { + daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Result<Void> rs2 = new Result<Void>(null,0,"test",new Object[0]); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - rs1 = new Result<List<Data>>(null,1,"test",new Object[0]); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("test user").when(trans).user(); - Field cbField; - try { - cbField = CassAccess.class.getDeclaredField("cb"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PermDAO.Data perm = new PermDAO.Data(); - RoleDAO.Data role = new RoleDAO.Data(); - Result<Void> retVal = daoObj.addPerm(trans, role, perm); - assertTrue(retVal.status == 9); - - Field owningField; - try { - owningField = AbsCassDAO.class.getDeclaredField("owningDAO"); - owningField.setAccessible(true); - owningField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.addPerm(trans, role, perm); - assertTrue(retVal.status == 0); - } - - @Test - public void testDelRole() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - RoleDAO.Data data = new RoleDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - RoleDAOImpl daoObj=null; - try { - daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Result<Void> rs2 = new Result<Void>(null,0,"test",new Object[0]); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + rs1 = new Result<List<Data>>(null,1,"test",new Object[0]); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("test user").when(trans).user(); + Field cbField; + try { + cbField = CassAccess.class.getDeclaredField("cb"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PermDAO.Data perm = new PermDAO.Data(); + RoleDAO.Data role = new RoleDAO.Data(); + Result<Void> retVal = daoObj.addPerm(trans, role, perm); + assertTrue(retVal.status == 9); + + Field owningField; + try { + owningField = AbsCassDAO.class.getDeclaredField("owningDAO"); + owningField.setAccessible(true); + owningField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.addPerm(trans, role, perm); + assertTrue(retVal.status == 0); + } + + @Test + public void testDelRole() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + RoleDAO.Data data = new RoleDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + RoleDAOImpl daoObj=null; + try { + daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - rs1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("test user").when(trans).user(); - - PermDAO.Data perm = new PermDAO.Data(); - Field cbField; - try { - cbField = CassAccess.class.getDeclaredField("cb"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - RoleDAO.Data role = new RoleDAO.Data(); - Result<Void> retVal = daoObj.delPerm(trans, role, perm); - assertTrue(retVal.status == 9); - - Field owningDaoField; - try { - owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); - owningDaoField.setAccessible(true); - owningDaoField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.delPerm(trans,role, perm); - assertTrue(retVal.status == 0); - } - - @Test - public void testAddDescription() { - PSInfo psObj = Mockito.mock(PSInfo.class); - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - RoleDAO.Data data = new RoleDAO.Data(); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - RoleDAOImpl daoObj=null; - try { - daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + rs1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("test user").when(trans).user(); + + PermDAO.Data perm = new PermDAO.Data(); + Field cbField; + try { + cbField = CassAccess.class.getDeclaredField("cb"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + RoleDAO.Data role = new RoleDAO.Data(); + Result<Void> retVal = daoObj.delPerm(trans, role, perm); + assertTrue(retVal.status == 9); + + Field owningDaoField; + try { + owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); + owningDaoField.setAccessible(true); + owningDaoField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.delPerm(trans,role, perm); + assertTrue(retVal.status == 0); + } + + @Test + public void testAddDescription() { + PSInfo psObj = Mockito.mock(PSInfo.class); + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + RoleDAO.Data data = new RoleDAO.Data(); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + RoleDAOImpl daoObj=null; + try { + daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, psObj, Mockito.mock(Session.class)); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); - Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_PORT,"9042"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,"100"); + Mockito.doReturn("100").when(trans).getProperty(CassAccess.CASSANDRA_CLUSTERS_USER_NAME,null); - Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl CREATE", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl UPDATE", data); - Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAOImpl READ", data); - Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl DELETE", data); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - Result<Void> rs2 = new Result<Void>(null,1,"test",new String[0]); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - rs1 = new Result<List<Data>>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); - Mockito.doReturn("test user").when(trans).user(); - - RoleDAO.Data perm = new RoleDAO.Data(); - Field cbField; - try { - cbField = CassAccess.class.getDeclaredField("cb"); - cbField.setAccessible(true); - cbField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Result<Void> retVal = daoObj.addDescription(trans, "test", "test", "test"); - assertTrue(retVal.status == 9); - - Field owningDaoField; - try { - owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); - owningDaoField.setAccessible(true); - owningDaoField.set(daoObj, null); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - retVal = daoObj.addDescription(trans, "test", "test", "test"); - assertTrue(retVal.status == 0); - } - - public void setPsByStartAndTarget(RoleDAO RoleDAOObj, PSInfo psInfoObj, String fieldName) { - Field RoleDAOField; - try { - RoleDAOField = RoleDAO.class.getDeclaredField(fieldName); - - RoleDAOField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(RoleDAOField, RoleDAOField.getModifiers() & ~Modifier.FINAL); - - RoleDAOField.set(RoleDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasModified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doNothing().when(tt).done(); - RoleDAO.Data data = new RoleDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); - Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - RoleDAOImpl daoObj = null; - try { - daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, createPS ); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - daoObj.wasModified(trans, CRUD.create, data, new String[] {}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); - } - - @Test - public void testSecondConstructor() { - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Result<List<Data>> rs1 = new Result<List<Data>>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl CREATE", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl UPDATE", data); + Mockito.doReturn(rs1).when(psObj).read(trans, "RoleDAOImpl READ", data); + Mockito.doReturn(rs1).when(psObj).exec(trans, "RoleDAOImpl DELETE", data); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + Result<Void> rs2 = new Result<Void>(null,1,"test",new String[0]); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + rs1 = new Result<List<Data>>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(cacheInfoDAO).touch(Mockito.any(), Mockito.anyString(), Mockito.anyInt()); + Mockito.doReturn("test user").when(trans).user(); + + RoleDAO.Data perm = new RoleDAO.Data(); + Field cbField; + try { + cbField = CassAccess.class.getDeclaredField("cb"); + cbField.setAccessible(true); + cbField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Result<Void> retVal = daoObj.addDescription(trans, "test", "test", "test"); + assertTrue(retVal.status == 9); + + Field owningDaoField; + try { + owningDaoField = AbsCassDAO.class.getDeclaredField("owningDAO"); + owningDaoField.setAccessible(true); + owningDaoField.set(daoObj, null); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + retVal = daoObj.addDescription(trans, "test", "test", "test"); + assertTrue(retVal.status == 0); + } + + public void setPsByStartAndTarget(RoleDAO RoleDAOObj, PSInfo psInfoObj, String fieldName) { + Field RoleDAOField; + try { + RoleDAOField = RoleDAO.class.getDeclaredField(fieldName); + + RoleDAOField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(RoleDAOField, RoleDAOField.getModifiers() & ~Modifier.FINAL); + + RoleDAOField.set(RoleDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasModified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("RoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on RoleDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doNothing().when(tt).done(); + RoleDAO.Data data = new RoleDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new String[0]); + Result<Void> rs2 = new Result<Void>(null,0,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + RoleDAOImpl daoObj = null; + try { + daoObj = new RoleDAOImpl(trans, historyDAO, cacheInfoDAO, createPS ); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + daoObj.wasModified(trans, CRUD.create, data, new String[] {}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test","test"}); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); + } + + @Test + public void testSecondConstructor() { + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - RoleDAO daoObj = new RoleDAO(trans, historyDAO, cacheInfoDAO); - - } + RoleDAO daoObj = new RoleDAO(trans, historyDAO, cacheInfoDAO); + + } - @Test - public void testFutureLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = RoleDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("RoleLoader")) { - innerClass = indCls; - break; - } - } - + @Test + public void testFutureLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = RoleDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("RoleLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - RoleDAO.Data data = new RoleDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {RoleDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {RoleDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {RoleDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {RoleDAO.Data.class, DataOutputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dos }); + + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + RoleDAO.Data data = new RoleDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {RoleDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {RoleDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {RoleDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {RoleDAO.Data.class, DataOutputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dos }); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DataInputStream dis = new DataInputStream(bais); - innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {RoleDAO.Data.class, DataInputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testData() { - RoleDAO.Data data = new RoleDAO.Data(); - NsSplit nss = new NsSplit("test", "test"); - data = new RoleDAO.Data(); - - data.toString(); - - - Question q = Mockito.mock( Question.class); - - Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); - Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); - Result<Data> retVal= RoleDAO.Data.decode(trans, q, "test|||"); - assertTrue(retVal.status==0); - Result<String[]> retVal1= RoleDAO.Data.decodeToArray(trans, q, "test|||"); - assertTrue(retVal.status==0); - retVal= RoleDAO.Data.decode(trans, q, "test"); - retVal1= RoleDAO.Data.decodeToArray(trans, q, "test"); - assertTrue(retVal.status==0); - - rs = new Result<NsSplit>(nss,1,"test",new Object[0]); - Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); - retVal= RoleDAO.Data.decode(trans, q, "test"); - retVal1= RoleDAO.Data.decodeToArray(trans, q, "test"); - assertTrue(retVal.status==1); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + DataInputStream dis = new DataInputStream(bais); + innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {RoleDAO.Data.class, DataInputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testData() { + RoleDAO.Data data = new RoleDAO.Data(); + NsSplit nss = new NsSplit("test", "test"); + data = new RoleDAO.Data(); + + data.toString(); + + + Question q = Mockito.mock( Question.class); + + Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); + Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); + Result<Data> retVal= RoleDAO.Data.decode(trans, q, "test|||"); + assertTrue(retVal.status==0); + Result<String[]> retVal1= RoleDAO.Data.decodeToArray(trans, q, "test|||"); + assertTrue(retVal.status==0); + retVal= RoleDAO.Data.decode(trans, q, "test"); + retVal1= RoleDAO.Data.decodeToArray(trans, q, "test"); + assertTrue(retVal.status==0); + + rs = new Result<NsSplit>(nss,1,"test",new Object[0]); + Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); + retVal= RoleDAO.Data.decode(trans, q, "test"); + retVal1= RoleDAO.Data.decodeToArray(trans, q, "test"); + assertTrue(retVal.status==1); - retVal= RoleDAO.Data.decode(trans, q, "test"); - retVal1= RoleDAO.Data.decodeToArray(trans, q, "test"); - assertTrue(retVal.status==1); - - NsDAO.Data ns = new NsDAO.Data(); - ns.name="test"; - RoleDAO.Data.create(ns, "test"); + retVal= RoleDAO.Data.decode(trans, q, "test"); + retVal1= RoleDAO.Data.decodeToArray(trans, q, "test"); + assertTrue(retVal.status==1); + + NsDAO.Data ns = new NsDAO.Data(); + ns.name="test"; + RoleDAO.Data.create(ns, "test"); - UserRoleDAO.Data urdd = new UserRoleDAO.Data(); - urdd.ns="test"; - RoleDAO.Data dd=RoleDAO.Data.decode(urdd); - assertTrue("test".equals(dd.ns)); - - assertTrue(data.encode().contains("null")); - - data.perms = null; - data.perms(true); + UserRoleDAO.Data urdd = new UserRoleDAO.Data(); + urdd.ns="test"; + RoleDAO.Data dd=RoleDAO.Data.decode(urdd); + assertTrue("test".equals(dd.ns)); + + assertTrue(data.encode().contains("null")); + + data.perms = null; + data.perms(true); - data.perms = new HashSet<>(); - data.perms(true); + data.perms = new HashSet<>(); + data.perms(true); - data.perms(false); - data.perms = new TreeSet<>(); - data.perms(true); - } - + data.perms(false); + data.perms = new TreeSet<>(); + data.perms(true); + } + } class RoleDAOImpl extends RoleDAO{ - public RoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS) throws APIException, IOException { - super(trans, historyDAO, cacheDao); - setPs(this, readPS, "createPS"); - } - - public RoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS, Session session ) throws APIException, IOException { - super(trans, historyDAO, cacheDao); - setPs(this, readPS, "createPS"); - setSession(this, session); - } - + public RoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS) throws APIException, IOException { + super(trans, historyDAO, cacheDao); + setPs(this, readPS, "createPS"); + } + + public RoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS, Session session ) throws APIException, IOException { + super(trans, historyDAO, cacheDao); + setPs(this, readPS, "createPS"); + setSession(this, session); + } + - public void setPs(RoleDAOImpl RoleDAOObj, PSInfo psInfoObj, String methodName) { - Field RoleDAOField; - try { - RoleDAOField = CassDAOImpl.class.getDeclaredField(methodName); - - RoleDAOField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(RoleDAOField, RoleDAOField.getModifiers() & ~Modifier.FINAL); - - RoleDAOField.set(RoleDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void setSession(RoleDAOImpl approvalDaoObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(approvalDaoObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setPs(RoleDAOImpl RoleDAOObj, PSInfo psInfoObj, String methodName) { + Field RoleDAOField; + try { + RoleDAOField = CassDAOImpl.class.getDeclaredField(methodName); + + RoleDAOField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(RoleDAOField, RoleDAOField.getModifiers() & ~Modifier.FINAL); + + RoleDAOField.set(RoleDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void setSession(RoleDAOImpl approvalDaoObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(approvalDaoObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_UserRoleDAO.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_UserRoleDAO.java index 8023fa9e..43496fd5 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_UserRoleDAO.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/cass/JU_UserRoleDAO.java @@ -60,349 +60,349 @@ import com.datastax.driver.core.Session; public class JU_UserRoleDAO { - @Mock + @Mock AuthzTrans trans; - @Mock - Cluster cluster; - @Mock - Session session; - - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); - Mockito.doReturn(session).when(cluster).connect("test"); - } + @Mock + Cluster cluster; + @Mock + Session session; + + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).warn(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).init(); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("100").when(trans).getProperty(Config.CADI_LONGITUDE); + Mockito.doReturn(session).when(cluster).connect("test"); + } - @Test - public void testInit() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); - try { - new UserRoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } -// daoObj. - } - @Test - public void testReadByUser() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); - UserRoleDAO daoObj = null; - try { - daoObj = new UserRoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psByUser"); - - Result<List<UserRoleDAO.Data>> rs1 = new Result<List<UserRoleDAO.Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "UserRoleDAO READ", new Object[]{"test"}); - - daoObj.readByUser(trans, "test"); - } - @Test - public void testReadByRole() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); - UserRoleDAO daoObj = null; - try { - daoObj = new UserRoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psByRole"); - - Result<List<UserRoleDAO.Data>> rs1 = new Result<List<UserRoleDAO.Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "UserRoleDAO READ", new Object[]{"test"}); - - daoObj.readByRole(trans, "test"); - } - @Test - public void testReadByUserRole() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); - UserRoleDAO daoObj = null; - try { - daoObj = new UserRoleDAO(trans, cluster, "test"); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - PSInfo psObj = Mockito.mock(PSInfo.class); - setPsByStartAndTarget(daoObj, psObj, "psUserInRole"); - - Result<List<UserRoleDAO.Data>> rs1 = new Result<List<UserRoleDAO.Data>>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(psObj).read(trans, "UserRoleDAO READ", new Object[]{"test"}); - - daoObj.readByUserRole(trans, "test","test"); - } - - - public void setPsByStartAndTarget(UserRoleDAO UserRoleDAOObj, PSInfo psInfoObj, String fieldName) { - Field UserRoleDAOField; - try { - UserRoleDAOField = UserRoleDAO.class.getDeclaredField(fieldName); - - UserRoleDAOField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(UserRoleDAOField, UserRoleDAOField.getModifiers() & ~Modifier.FINAL); - - UserRoleDAOField.set(UserRoleDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testWasMOdified() { - TimeTaken tt = Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); - Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); - Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); - Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); - Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doNothing().when(tt).done(); - UserRoleDAO.Data data = new UserRoleDAO.Data(); - PSInfo createPS = Mockito.mock(PSInfo.class); - - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); - Result<Void> rs2 = new Result<Void>(null,0,"test",new Object[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - - UserRoleDAOImpl daoObj = null; - try { - daoObj = new UserRoleDAOImpl(trans, historyDAO, cacheInfoDAO, createPS ); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); - - daoObj.wasModified(trans, CRUD.update, data, new String[] {}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); - daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); - daoObj.wasModified(trans, CRUD.update, data, new String[] {"test","test"}); + @Test + public void testInit() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); + try { + new UserRoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } +// daoObj. + } + @Test + public void testReadByUser() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); + UserRoleDAO daoObj = null; + try { + daoObj = new UserRoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psByUser"); + + Result<List<UserRoleDAO.Data>> rs1 = new Result<List<UserRoleDAO.Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "UserRoleDAO READ", new Object[]{"test"}); + + daoObj.readByUser(trans, "test"); + } + @Test + public void testReadByRole() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); + UserRoleDAO daoObj = null; + try { + daoObj = new UserRoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psByRole"); + + Result<List<UserRoleDAO.Data>> rs1 = new Result<List<UserRoleDAO.Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "UserRoleDAO READ", new Object[]{"test"}); + + daoObj.readByRole(trans, "test"); + } + @Test + public void testReadByUserRole() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); + UserRoleDAO daoObj = null; + try { + daoObj = new UserRoleDAO(trans, cluster, "test"); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + PSInfo psObj = Mockito.mock(PSInfo.class); + setPsByStartAndTarget(daoObj, psObj, "psUserInRole"); + + Result<List<UserRoleDAO.Data>> rs1 = new Result<List<UserRoleDAO.Data>>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(psObj).read(trans, "UserRoleDAO READ", new Object[]{"test"}); + + daoObj.readByUserRole(trans, "test","test"); + } + + + public void setPsByStartAndTarget(UserRoleDAO UserRoleDAOObj, PSInfo psInfoObj, String fieldName) { + Field UserRoleDAOField; + try { + UserRoleDAOField = UserRoleDAO.class.getDeclaredField(fieldName); + + UserRoleDAOField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(UserRoleDAOField, UserRoleDAOField.getModifiers() & ~Modifier.FINAL); + + UserRoleDAOField.set(UserRoleDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testWasMOdified() { + TimeTaken tt = Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(trans).start("UserRoleDAO CREATE", Env.REMOTE); + Mockito.doReturn(tt).when(trans).start("Clear Reset Deque", Env.SUB); + Mockito.doReturn(tt).when(trans).start("New Cassandra Session", Env.SUB); + Mockito.doReturn(tt).when(trans).start("Preparing PSInfo CREATE on UserRoleDAO", Env.SUB); + Mockito.doReturn(tt).when(trans).start("DELETE Future",Env.REMOTE); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doNothing().when(tt).done(); + UserRoleDAO.Data data = new UserRoleDAO.Data(); + PSInfo createPS = Mockito.mock(PSInfo.class); + + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + Result<ResultSet> rs1 = new Result<ResultSet>(null,0,"test",new Object[0]); + Result<Void> rs2 = new Result<Void>(null,0,"test",new Object[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + + UserRoleDAOImpl daoObj = null; + try { + daoObj = new UserRoleDAOImpl(trans, historyDAO, cacheInfoDAO, createPS ); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test"}); + + daoObj.wasModified(trans, CRUD.update, data, new String[] {}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {null}); + daoObj.wasModified(trans, CRUD.create, data, new String[] {"test",null}); + daoObj.wasModified(trans, CRUD.update, data, new String[] {"test","test"}); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {}); - - rs2 = new Result<Void>(null,1,"test",new Object[0]); - Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); - daoObj.wasModified(trans, CRUD.read, data, new String[] {"test","test"}); - daoObj.wasModified(trans, CRUD.read, data, new String[] {}); - - rs1 = new Result<ResultSet>(null,1,"test",new String[0]); - Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); - daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); - } - - @Test - public void testSecondConstructor() { - HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); - CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {}); + + rs2 = new Result<Void>(null,1,"test",new Object[0]); + Mockito.doReturn(rs2).when(cacheInfoDAO).touch(Mockito.any(AuthzTrans.class),Mockito.anyString(), Mockito.anyVararg()); + daoObj.wasModified(trans, CRUD.read, data, new String[] {"test","test"}); + daoObj.wasModified(trans, CRUD.read, data, new String[] {}); + + rs1 = new Result<ResultSet>(null,1,"test",new String[0]); + Mockito.doReturn(rs1).when(historyDAO).create(Mockito.any(), Mockito.any()); + daoObj.wasModified(trans, CRUD.delete, data, new String[] {"test","test"}); + } + + @Test + public void testSecondConstructor() { + HistoryDAO historyDAO = Mockito.mock(HistoryDAO.class); + CacheInfoDAO cacheInfoDAO = Mockito.mock(CacheInfoDAO.class); - UserRoleDAO daoObj = new UserRoleDAO(trans, historyDAO, cacheInfoDAO); - - } + UserRoleDAO daoObj = new UserRoleDAO(trans, historyDAO, cacheInfoDAO); + + } - @Test - public void testFutureLoader(){ - Class<?> innerClass = null; - Class<?>[] innerClassArr = UserRoleDAO.class.getDeclaredClasses(); - for(Class indCls:innerClassArr) { - if(indCls.getName().contains("URLoader")) { - innerClass = indCls; - break; - } - } - + @Test + public void testFutureLoader(){ + Class<?> innerClass = null; + Class<?>[] innerClassArr = UserRoleDAO.class.getDeclaredClasses(); + for(Class indCls:innerClassArr) { + if(indCls.getName().contains("URLoader")) { + innerClass = indCls; + break; + } + } + Constructor<?> constructor = innerClass.getDeclaredConstructors()[0]; constructor.setAccessible(true); try { - - Object obj = constructor.newInstance(1); - Method innnerClassMtd; - - UserRoleDAO.Data data = new UserRoleDAO.Data(); - Row row = Mockito.mock(Row.class); - ByteBuffer bbObj = ByteBuffer.allocateDirect(10); - bbObj.limit(7); - bbObj.put(0, new Byte("0")); - bbObj.put(1, new Byte("1")); - bbObj.put(2, new Byte("2")); - Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); - - innnerClassMtd = innerClass.getMethod("load", new Class[] {UserRoleDAO.Data.class, Row.class}); - innnerClassMtd.invoke(obj, new Object[] {data, row}); - - innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {UserRoleDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test"} }); -// - innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {UserRoleDAO.Data.class, Integer.TYPE, Object[].class }); - innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - DataOutputStream dos = new DataOutputStream(baos); - innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {UserRoleDAO.Data.class, DataOutputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dos }); + + Object obj = constructor.newInstance(1); + Method innnerClassMtd; + + UserRoleDAO.Data data = new UserRoleDAO.Data(); + Row row = Mockito.mock(Row.class); + ByteBuffer bbObj = ByteBuffer.allocateDirect(10); + bbObj.limit(7); + bbObj.put(0, new Byte("0")); + bbObj.put(1, new Byte("1")); + bbObj.put(2, new Byte("2")); + Mockito.doReturn(bbObj).when(row).getBytesUnsafe(1); + + innnerClassMtd = innerClass.getMethod("load", new Class[] {UserRoleDAO.Data.class, Row.class}); + innnerClassMtd.invoke(obj, new Object[] {data, row}); + + innnerClassMtd = innerClass.getDeclaredMethod("key", new Class[] {UserRoleDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test"} }); +// + innnerClassMtd = innerClass.getDeclaredMethod("body", new Class[] {UserRoleDAO.Data.class, Integer.TYPE, Object[].class }); + innnerClassMtd.invoke(obj, new Object[] {data, 1, new Object[] {"test","test","test","test","test","test","test","test","test","test","test"} }); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + innnerClassMtd = innerClass.getDeclaredMethod("marshal", new Class[] {UserRoleDAO.Data.class, DataOutputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dos }); - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - DataInputStream dis = new DataInputStream(bais); - innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {UserRoleDAO.Data.class, DataInputStream.class }); - innnerClassMtd.invoke(obj, new Object[] {data, dis }); - - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (NoSuchMethodException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testData() { - UserRoleDAO.Data data = new UserRoleDAO.Data(); - NsSplit nss = new NsSplit("test", "test"); - data = new UserRoleDAO.Data(); - - data.toString(); - data.role("test", "test"); - assertTrue("test".equals(data.ns)); - - RoleDAO.Data rdd = new RoleDAO.Data(); - rdd.ns="test"; - data.role(rdd); - assertTrue("test".equals(data.ns)); - - Question q = Mockito.mock( Question.class); - Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); - Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); - - data.role(trans, q, "test"); - - rs = new Result<NsSplit>(nss,1,"test",new Object[0]); - Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); - - data.role(trans, q, "test"); - } - + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + DataInputStream dis = new DataInputStream(bais); + innnerClassMtd = innerClass.getDeclaredMethod("unmarshal", new Class[] {UserRoleDAO.Data.class, DataInputStream.class }); + innnerClassMtd.invoke(obj, new Object[] {data, dis }); + + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (NoSuchMethodException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testData() { + UserRoleDAO.Data data = new UserRoleDAO.Data(); + NsSplit nss = new NsSplit("test", "test"); + data = new UserRoleDAO.Data(); + + data.toString(); + data.role("test", "test"); + assertTrue("test".equals(data.ns)); + + RoleDAO.Data rdd = new RoleDAO.Data(); + rdd.ns="test"; + data.role(rdd); + assertTrue("test".equals(data.ns)); + + Question q = Mockito.mock( Question.class); + Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); + Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); + + data.role(trans, q, "test"); + + rs = new Result<NsSplit>(nss,1,"test",new Object[0]); + Mockito.doReturn(rs).when(q).deriveNsSplit(trans, "test"); + + data.role(trans, q, "test"); + } + } class UserRoleDAOImpl extends UserRoleDAO{ - public UserRoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS) throws APIException, IOException { - super(trans, historyDAO, cacheDao); - setPs(this, readPS, "createPS"); - } - - public UserRoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS, Session session ) throws APIException, IOException { - super(trans, historyDAO, cacheDao); - setPs(this, readPS, "createPS"); - setSession(this, session); - } - + public UserRoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS) throws APIException, IOException { + super(trans, historyDAO, cacheDao); + setPs(this, readPS, "createPS"); + } + + public UserRoleDAOImpl(AuthzTrans trans, HistoryDAO historyDAO,CacheInfoDAO cacheDao, PSInfo readPS, Session session ) throws APIException, IOException { + super(trans, historyDAO, cacheDao); + setPs(this, readPS, "createPS"); + setSession(this, session); + } + - public void setPs(UserRoleDAOImpl UserRoleDAOObj, PSInfo psInfoObj, String methodName) { - Field UserRoleDAOField; - try { - UserRoleDAOField = CassDAOImpl.class.getDeclaredField(methodName); - - UserRoleDAOField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(UserRoleDAOField, UserRoleDAOField.getModifiers() & ~Modifier.FINAL); - - UserRoleDAOField.set(UserRoleDAOObj, psInfoObj); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void setSession(UserRoleDAOImpl approvalDaoObj, Session session) { - Field nsDaoField; - try { - nsDaoField = AbsCassDAO.class.getDeclaredField("session"); - - nsDaoField.setAccessible(true); - // remove final modifier from field - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); -// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); - - nsDaoField.set(approvalDaoObj, session); - } catch (NoSuchFieldException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + public void setPs(UserRoleDAOImpl UserRoleDAOObj, PSInfo psInfoObj, String methodName) { + Field UserRoleDAOField; + try { + UserRoleDAOField = CassDAOImpl.class.getDeclaredField(methodName); + + UserRoleDAOField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(UserRoleDAOField, UserRoleDAOField.getModifiers() & ~Modifier.FINAL); + + UserRoleDAOField.set(UserRoleDAOObj, psInfoObj); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public void setSession(UserRoleDAOImpl approvalDaoObj, Session session) { + Field nsDaoField; + try { + nsDaoField = AbsCassDAO.class.getDeclaredField("session"); + + nsDaoField.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); +// modifiersField.setInt(nsDaoField, nsDaoField.getModifiers() & ~Modifier.FINAL); + + nsDaoField.set(approvalDaoObj, session); + } catch (NoSuchFieldException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_CassExecutor.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_CassExecutor.java index 56cc2b0e..6d029933 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_CassExecutor.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_CassExecutor.java @@ -46,111 +46,111 @@ import org.onap.aaf.cadi.CadiException; @RunWith(MockitoJUnitRunner.class) public class JU_CassExecutor { - - - private static final Object NO_PARAM = new Object[0]; + + + private static final Object NO_PARAM = new Object[0]; - @Mock - AuthzTransImpl trans; - - @Mock - Question q; - - @Mock - Access access; - - Function f; - - @Before - public void setUp() throws Exception { - initMocks(this); - try { - Mockito.doReturn("0.0").when(access).getProperty("aaf_root_ns","org.osaaf.aaf"); - Mockito.doReturn(new Properties()).when(access).getProperties(); - Define.set(access); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - f =new Function(trans, q); - } - - @Test - public void testHasPermission() { - - CassExecutor cassExecutorObj =new CassExecutor(trans, f); - Mockito.doReturn(false).when(q).isGranted(trans, "","","","",""); - boolean retVal = cassExecutorObj.hasPermission("", "", "", "", ""); -// System.out.println(retVal); - assertFalse(retVal); - } - - @Test - public void testInRole() { - - CassExecutor cassExecutorObj =new CassExecutor(trans, f); - Result<NsSplit> retVal1 = new Result<NsSplit>(null,1,"",NO_PARAM); - Mockito.doReturn(retVal1).when(q).deriveNsSplit(trans, "test"); - - boolean retVal = cassExecutorObj.inRole("test"); -// System.out.println(retVal); - assertFalse(retVal); - } - - @Test - public void testNamespace() { - f =new Function(trans, q); - CassExecutor cassExecutorObj =new CassExecutor(trans, f); - Result<Data> retVal1 = new Result<Data>(null,1,"",NO_PARAM); - Mockito.doReturn(retVal1).when(q).validNSOfDomain(trans, null); - - String retVal=""; - try { - retVal = cassExecutorObj.namespace(); - } catch (Exception e) { - System.out.println(e.getMessage()); - assertEquals("33", e.getMessage()); - } - System.out.println(retVal); -// assertFalse(retVal); - } - - @Test - public void testId() { - Mockito.doReturn("").when(trans).user(); - CassExecutor cassExecutorObj =new CassExecutor(trans, f); - String retVal = cassExecutorObj.id(); - assertEquals("", retVal); - } - - @Test - public void testNamespaceSuccess() { - Mockito.doAnswer(new Answer<Object>() { - private int count = 0; + @Mock + AuthzTransImpl trans; + + @Mock + Question q; + + @Mock + Access access; + + Function f; + + @Before + public void setUp() throws Exception { + initMocks(this); + try { + Mockito.doReturn("0.0").when(access).getProperty("aaf_root_ns","org.osaaf.aaf"); + Mockito.doReturn(new Properties()).when(access).getProperties(); + Define.set(access); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + f =new Function(trans, q); + } + + @Test + public void testHasPermission() { + + CassExecutor cassExecutorObj =new CassExecutor(trans, f); + Mockito.doReturn(false).when(q).isGranted(trans, "","","","",""); + boolean retVal = cassExecutorObj.hasPermission("", "", "", "", ""); +// System.out.println(retVal); + assertFalse(retVal); + } + + @Test + public void testInRole() { + + CassExecutor cassExecutorObj =new CassExecutor(trans, f); + Result<NsSplit> retVal1 = new Result<NsSplit>(null,1,"",NO_PARAM); + Mockito.doReturn(retVal1).when(q).deriveNsSplit(trans, "test"); + + boolean retVal = cassExecutorObj.inRole("test"); +// System.out.println(retVal); + assertFalse(retVal); + } + + @Test + public void testNamespace() { + f =new Function(trans, q); + CassExecutor cassExecutorObj =new CassExecutor(trans, f); + Result<Data> retVal1 = new Result<Data>(null,1,"",NO_PARAM); + Mockito.doReturn(retVal1).when(q).validNSOfDomain(trans, null); + + String retVal=""; + try { + retVal = cassExecutorObj.namespace(); + } catch (Exception e) { + System.out.println(e.getMessage()); + assertEquals("33", e.getMessage()); + } + System.out.println(retVal); +// assertFalse(retVal); + } + + @Test + public void testId() { + Mockito.doReturn("").when(trans).user(); + CassExecutor cassExecutorObj =new CassExecutor(trans, f); + String retVal = cassExecutorObj.id(); + assertEquals("", retVal); + } + + @Test + public void testNamespaceSuccess() { + Mockito.doAnswer(new Answer<Object>() { + private int count = 0; - public Object answer(InvocationOnMock invocation) { - if (count++ == 1) - return "test@test.com"; + public Object answer(InvocationOnMock invocation) { + if (count++ == 1) + return "test@test.com"; - return null; - } - }).when(trans).user(); - f =new Function(trans, q); - CassExecutor cassExecutorObj =new CassExecutor(trans, f); - Result<Data> retVal1 = new Result<Data>(null,0,"",NO_PARAM); - Mockito.doReturn(retVal1).when(q).validNSOfDomain(trans, null); - - -// String retVal=""; - try { - /*retVal =*/ cassExecutorObj.namespace(); - } catch (Exception e) { - e.printStackTrace(); - System.out.println(e.getMessage()); -// assertNull( e.getMessage()); - } -// System.out.println(retVal); -// assertFalse(retVal); - } - + return null; + } + }).when(trans).user(); + f =new Function(trans, q); + CassExecutor cassExecutorObj =new CassExecutor(trans, f); + Result<Data> retVal1 = new Result<Data>(null,0,"",NO_PARAM); + Mockito.doReturn(retVal1).when(q).validNSOfDomain(trans, null); + + +// String retVal=""; + try { + /*retVal =*/ cassExecutorObj.namespace(); + } catch (Exception e) { + e.printStackTrace(); + System.out.println(e.getMessage()); +// assertNull( e.getMessage()); + } +// System.out.println(retVal); +// assertFalse(retVal); + } + }
\ No newline at end of file diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_Function.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_Function.java index ab7b2e59..bfa5838c 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_Function.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_Function.java @@ -80,1619 +80,1619 @@ import org.onap.aaf.misc.env.LogTarget; public class JU_Function { - private static final Object NO_PARAM = new Object[0]; - - @Mock + private static final Object NO_PARAM = new Object[0]; + + @Mock AuthzTrans trans; - @Mock - PropAccess access; - - @Mock - Question ques; - - @Mock - Organization org; - - @Mock - CachedNSDAO nsDAO; - - @Mock - CachedRoleDAO roleDAO; + @Mock + PropAccess access; + + @Mock + Question ques; + + @Mock + Organization org; + + @Mock + CachedNSDAO nsDAO; + + @Mock + CachedRoleDAO roleDAO; - @Mock - CachedPermDAO permDAO; + @Mock + CachedPermDAO permDAO; - @Mock - CachedCredDAO credDAO; + @Mock + CachedCredDAO credDAO; - @Mock - CachedUserRoleDAO userRoleDAO; + @Mock + CachedUserRoleDAO userRoleDAO; - @Mock - ApprovalDAO approvalDAO; + @Mock + ApprovalDAO approvalDAO; - @Mock - FutureDAO futureDAO; + @Mock + FutureDAO futureDAO; - @Before - public void setUp() throws APIException, IOException { - initMocks(this); - Mockito.doReturn(org).when(trans).org(); - Mockito.doReturn(nsDAO).when(ques).nsDAO(); - Mockito.doReturn(roleDAO).when(ques).roleDAO(); - Mockito.doReturn(permDAO).when(ques).permDAO(); - Mockito.doReturn(credDAO).when(ques).credDAO(); - Mockito.doReturn(userRoleDAO).when(ques).userRoleDAO(); - Mockito.doReturn(approvalDAO).when(ques).approvalDAO(); - Mockito.doReturn(futureDAO).when(ques).futureDAO(); + @Before + public void setUp() throws APIException, IOException { + initMocks(this); + Mockito.doReturn(org).when(trans).org(); + Mockito.doReturn(nsDAO).when(ques).nsDAO(); + Mockito.doReturn(roleDAO).when(ques).roleDAO(); + Mockito.doReturn(permDAO).when(ques).permDAO(); + Mockito.doReturn(credDAO).when(ques).credDAO(); + Mockito.doReturn(userRoleDAO).when(ques).userRoleDAO(); + Mockito.doReturn(approvalDAO).when(ques).approvalDAO(); + Mockito.doReturn(futureDAO).when(ques).futureDAO(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(Properties.class)).when(access).getProperties(); - Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); - - try { - Define.set(access); - } catch (CadiException e) { - } - } + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).info(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(Properties.class)).when(access).getProperties(); + Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); + + try { + Define.set(access); + } catch (CadiException e) { + } + } - @Test - public void testCreateNs() { - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test.test"; - List<String> owner = new ArrayList<String>(); - namespace.owner = owner; + @Test + public void testCreateNs() { + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test.test"; + List<String> owner = new ArrayList<String>(); + namespace.owner = owner; - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - //setQuestion(ques, cachedNS); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.createNS(trans, namespace, true); - assertTrue(3 == result.status); - } - - @Test - public void testCreateNsReadSuccess() { - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test.test"; - List<String> owner = new ArrayList<String>(); - owner.add("test"); - namespace.owner = owner; - List<String> admin = new ArrayList<String>(); - admin.add("test"); - namespace.admin= admin; - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + //setQuestion(ques, cachedNS); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.createNS(trans, namespace, true); + assertTrue(3 == result.status); + } + + @Test + public void testCreateNsReadSuccess() { + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test.test"; + List<String> owner = new ArrayList<String>(); + owner.add("test"); + namespace.owner = owner; + List<String> admin = new ArrayList<String>(); + admin.add("test"); + namespace.admin= admin; + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.createNS(trans, namespace, true); - assertTrue(3 == result.status); - } - - @Test - public void testCreateNsFromApprovaFalse() { - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test.test"; - List<String> owner = new ArrayList<String>(); - namespace.owner = owner; - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.createNS(trans, namespace, false); - assertTrue(1 == result.status); - - Mockito.doReturn(retVal2).when(ques).deriveNs(trans, "test"); - funcObj = new Function(trans, ques); - result = funcObj.createNS(trans, namespace, false); - assertTrue(1 == result.status); - } - - @Test - public void testCreateNsownerLoop() { - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test.test"; - List<String> owner = new ArrayList<String>(); - owner.add("test"); - namespace.owner = owner; - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - Mockito.doReturn(org).when(trans).org(); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == Status.ERR_Policy); - assertTrue(result.details.contains("is not a valid user at")); - - Identity iden=Mockito.mock(Identity.class); - try { - Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); - Mockito.doReturn("test").when(iden).mayOwn(); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == Status.ERR_Policy); - assertTrue(result.details.contains("is an invalid Identity")); + Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.createNS(trans, namespace, true); + assertTrue(3 == result.status); + } + + @Test + public void testCreateNsFromApprovaFalse() { + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test.test"; + List<String> owner = new ArrayList<String>(); + namespace.owner = owner; + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.createNS(trans, namespace, false); + assertTrue(1 == result.status); + + Mockito.doReturn(retVal2).when(ques).deriveNs(trans, "test"); + funcObj = new Function(trans, ques); + result = funcObj.createNS(trans, namespace, false); + assertTrue(1 == result.status); + } + + @Test + public void testCreateNsownerLoop() { + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test.test"; + List<String> owner = new ArrayList<String>(); + owner.add("test"); + namespace.owner = owner; + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + Mockito.doReturn(org).when(trans).org(); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == Status.ERR_Policy); + assertTrue(result.details.contains("is not a valid user at")); + + Identity iden=Mockito.mock(Identity.class); + try { + Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); + Mockito.doReturn("test").when(iden).mayOwn(); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == Status.ERR_Policy); + assertTrue(result.details.contains("is an invalid Identity")); - Mockito.doReturn(true).when(iden).isFound(); - result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == Status.ERR_Policy); - assertTrue(result.details.contains("cannot be the owner of the namespace ")); - - Mockito.doReturn(true).when(org).isTestEnv(); - try { - Mockito.doReturn("test").when(org).validate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); - result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == Status.ERR_Policy); - assertTrue(result.details.contains("cannot be the owner of the namespace ")); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testCreateNsownerLoopException() { - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test"; - List<String> owner = new ArrayList<String>(); - owner.add("test"); - namespace.owner = owner; - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - - Function funcObj = new Function(trans, ques); - - Identity iden=Mockito.mock(Identity.class); - try { - Mockito.doThrow(new OrganizationException()).when(org).getIdentity(trans, "test"); - Mockito.doReturn("test").when(iden).mayOwn(); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Result<Void> result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == Status.ERR_Security); - assertTrue(result.details.contains("may not create Root Namespaces")); - - Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, null); - - Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - result = funcObj.createNS(trans, namespace, true); - assertTrue(24 == result.status); - - } + Mockito.doReturn(true).when(iden).isFound(); + result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == Status.ERR_Policy); + assertTrue(result.details.contains("cannot be the owner of the namespace ")); + + Mockito.doReturn(true).when(org).isTestEnv(); + try { + Mockito.doReturn("test").when(org).validate(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == Status.ERR_Policy); + assertTrue(result.details.contains("cannot be the owner of the namespace ")); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testCreateNsownerLoopException() { + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test"; + List<String> owner = new ArrayList<String>(); + owner.add("test"); + namespace.owner = owner; + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + + Function funcObj = new Function(trans, ques); + + Identity iden=Mockito.mock(Identity.class); + try { + Mockito.doThrow(new OrganizationException()).when(org).getIdentity(trans, "test"); + Mockito.doReturn("test").when(iden).mayOwn(); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Result<Void> result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == Status.ERR_Security); + assertTrue(result.details.contains("may not create Root Namespaces")); + + Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, null); + + Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + result = funcObj.createNS(trans, namespace, true); + assertTrue(24 == result.status); + + } - @Test - public void testCreateNsAdminLoop() { - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test.test"; - List<String> owner = new ArrayList<String>(); - owner.add("test"); - namespace.owner = owner; - namespace.admin = owner; - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal).when(nsDAO).create(Mockito.any(), Mockito.any()); - List<CredDAO.Data> dataObj = new ArrayList<>(); - CredDAO.Data indData = new CredDAO.Data(); - indData.id = "test"; - indData.notes = "test"; - DateFormat sdf = new SimpleDateFormat("yyyy/mm/dd"); - try { - indData.expires = sdf.parse("2090/01/01"); - } catch (ParseException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - dataObj.add(indData); - Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(dataObj,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); - - Identity iden=Mockito.mock(Identity.class); - try { - Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); - Mockito.doReturn("test").when(iden).mayOwn(); - Mockito.doReturn(true).when(org).isTestEnv(); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); + @Test + public void testCreateNsAdminLoop() { + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test.test"; + List<String> owner = new ArrayList<String>(); + owner.add("test"); + namespace.owner = owner; + namespace.admin = owner; + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal).when(nsDAO).create(Mockito.any(), Mockito.any()); + List<CredDAO.Data> dataObj = new ArrayList<>(); + CredDAO.Data indData = new CredDAO.Data(); + indData.id = "test"; + indData.notes = "test"; + DateFormat sdf = new SimpleDateFormat("yyyy/mm/dd"); + try { + indData.expires = sdf.parse("2090/01/01"); + } catch (ParseException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + dataObj.add(indData); + Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(dataObj,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); + + Identity iden=Mockito.mock(Identity.class); + try { + Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); + Mockito.doReturn("test").when(iden).mayOwn(); + Mockito.doReturn(true).when(org).isTestEnv(); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == 1); - - } - - @Test - public void testCreateNsAdminLoopCreateSucReadChildrenFailure() { - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); - Mockito.doReturn(Mockito.mock(Properties.class)).when(access).getProperties(); - Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); - try { - Define.set(access); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test.test"; - List<String> owner = new ArrayList<String>(); - owner.add("test"); - namespace.owner = owner; - namespace.admin = owner; - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Result<Void> retVal = new Result<Void>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal).when(nsDAO).create(Mockito.any(), Mockito.any()); - List<CredDAO.Data> dataObj = new ArrayList<>(); - CredDAO.Data indData = new CredDAO.Data(); - indData.id = "test"; - indData.notes = "test"; - DateFormat sdf = new SimpleDateFormat("yyyy/mm/dd"); - try { - indData.expires = sdf.parse("2090/01/01"); - } catch (ParseException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - dataObj.add(indData); - List<RoleDAO.Data> dataObj1 = new ArrayList<>(); - RoleDAO.Data indData1 = new RoleDAO.Data(); - indData1.ns = "test"; - indData1.name = "test"; - Set<String> permsSet = new HashSet<>(); - permsSet.add("test|test"); - indData1.perms = permsSet; - dataObj1.add(indData1); - - List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); - UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); - indData4.ns = "test"; - indData4.rname = "test"; - dataObj4.add(indData4); - - List<PermDAO.Data> dataObj5 = new ArrayList<>(); - PermDAO.Data indData5 = new PermDAO.Data(); - indData5.ns = "test"; - indData5.type = "test"; - dataObj5.add(indData5); - - Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(dataObj,0,"test",NO_PARAM); - Result<List<CredDAO.Data>> retVal6 = new Result<List<CredDAO.Data>>(dataObj,1,"test",NO_PARAM); - Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); - Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); - Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal2).when(userRoleDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal6).when(roleDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal6).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(retVal2).when(permDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal5).when(permDAO).readChildren(trans, "test", "test"); - Mockito.doReturn(retVal5).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(retVal3).when(roleDAO).readChildren(trans, "test", "test"); - - Identity iden=Mockito.mock(Identity.class); - try { - Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); - Mockito.doReturn("test").when(iden).mayOwn(); - Mockito.doReturn(true).when(org).isTestEnv(); - Mockito.doReturn(new GregorianCalendar(2010, 01, 01)).when(org).expiration(null, Expiration.UserInRole); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Function funcObj = new Function(trans, ques); - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == 1); + + } + + @Test + public void testCreateNsAdminLoopCreateSucReadChildrenFailure() { + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).debug(); + Mockito.doReturn(Mockito.mock(Properties.class)).when(access).getProperties(); + Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); + try { + Define.set(access); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test.test"; + List<String> owner = new ArrayList<String>(); + owner.add("test"); + namespace.owner = owner; + namespace.admin = owner; + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Result<Void> retVal = new Result<Void>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal).when(nsDAO).create(Mockito.any(), Mockito.any()); + List<CredDAO.Data> dataObj = new ArrayList<>(); + CredDAO.Data indData = new CredDAO.Data(); + indData.id = "test"; + indData.notes = "test"; + DateFormat sdf = new SimpleDateFormat("yyyy/mm/dd"); + try { + indData.expires = sdf.parse("2090/01/01"); + } catch (ParseException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + dataObj.add(indData); + List<RoleDAO.Data> dataObj1 = new ArrayList<>(); + RoleDAO.Data indData1 = new RoleDAO.Data(); + indData1.ns = "test"; + indData1.name = "test"; + Set<String> permsSet = new HashSet<>(); + permsSet.add("test|test"); + indData1.perms = permsSet; + dataObj1.add(indData1); + + List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); + UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); + indData4.ns = "test"; + indData4.rname = "test"; + dataObj4.add(indData4); + + List<PermDAO.Data> dataObj5 = new ArrayList<>(); + PermDAO.Data indData5 = new PermDAO.Data(); + indData5.ns = "test"; + indData5.type = "test"; + dataObj5.add(indData5); + + Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(dataObj,0,"test",NO_PARAM); + Result<List<CredDAO.Data>> retVal6 = new Result<List<CredDAO.Data>>(dataObj,1,"test",NO_PARAM); + Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); + Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); + Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal2).when(userRoleDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal6).when(roleDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal6).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Mockito.doReturn(retVal2).when(permDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal5).when(permDAO).readChildren(trans, "test", "test"); + Mockito.doReturn(retVal5).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Mockito.doReturn(retVal3).when(roleDAO).readChildren(trans, "test", "test"); + + Identity iden=Mockito.mock(Identity.class); + try { + Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); + Mockito.doReturn("test").when(iden).mayOwn(); + Mockito.doReturn(true).when(org).isTestEnv(); + Mockito.doReturn(new GregorianCalendar(2010, 01, 01)).when(org).expiration(null, Expiration.UserInRole); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Function funcObj = new Function(trans, ques); + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); - Result<Void> result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == Status.ERR_ActionNotCompleted); - - } - - @Test - public void testCreateNsAdminLoopCreateSuc() { - Namespace namespace = Mockito.mock(Namespace.class); - namespace.name = "test.test"; - List<String> owner = new ArrayList<String>(); - owner.add("test"); - namespace.owner = owner; - namespace.admin = owner; - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Result<Void> retVal = new Result<Void>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal).when(nsDAO).create(Mockito.any(), Mockito.any()); - List<CredDAO.Data> dataObj = new ArrayList<>(); - CredDAO.Data indData = new CredDAO.Data(); - indData.id = "test"; - indData.notes = "test"; - DateFormat sdf = new SimpleDateFormat("yyyy/mm/dd"); - try { - indData.expires = sdf.parse("2090/01/01"); - } catch (ParseException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - dataObj.add(indData); - List<RoleDAO.Data> dataObj1 = new ArrayList<>(); - RoleDAO.Data indData1 = new RoleDAO.Data(); - indData1.ns = "test"; - indData1.name = "test"; - Set<String> permsSet = new HashSet<>(); - permsSet.add("test|test|test|test"); - indData1.perms = permsSet; - dataObj1.add(indData1); - - List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); - UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); - indData4.ns = "test"; - indData4.rname = "test"; - dataObj4.add(indData4); - - List<PermDAO.Data> dataObj5 = new ArrayList<>(); - PermDAO.Data indData5 = new PermDAO.Data(); - indData5.ns = "test"; - indData5.type = "test"; - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("test|test|test|test"); - indData5.roles = rolesSet; - dataObj5.add(indData5); - - Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(dataObj,0,"test",NO_PARAM); - Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); - Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); - Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal2).when(userRoleDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal2).when(roleDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal2).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(retVal2).when(permDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal5).when(permDAO).readChildren(trans, "test", "test"); - Mockito.doReturn(retVal5).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - Mockito.doReturn(retVal3).when(roleDAO).readChildren(trans, "test", "test"); - - Identity iden=Mockito.mock(Identity.class); - try { - Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); - Mockito.doReturn("test").when(iden).mayOwn(); - Mockito.doReturn(true).when(org).isTestEnv(); - Mockito.doReturn(new GregorianCalendar(2010, 01, 01)).when(org).expiration(null, Expiration.UserInRole); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); - Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); + Result<Void> result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == Status.ERR_ActionNotCompleted); + + } + + @Test + public void testCreateNsAdminLoopCreateSuc() { + Namespace namespace = Mockito.mock(Namespace.class); + namespace.name = "test.test"; + List<String> owner = new ArrayList<String>(); + owner.add("test"); + namespace.owner = owner; + namespace.admin = owner; + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Result<Void> retVal = new Result<Void>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal).when(nsDAO).create(Mockito.any(), Mockito.any()); + List<CredDAO.Data> dataObj = new ArrayList<>(); + CredDAO.Data indData = new CredDAO.Data(); + indData.id = "test"; + indData.notes = "test"; + DateFormat sdf = new SimpleDateFormat("yyyy/mm/dd"); + try { + indData.expires = sdf.parse("2090/01/01"); + } catch (ParseException e1) { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + dataObj.add(indData); + List<RoleDAO.Data> dataObj1 = new ArrayList<>(); + RoleDAO.Data indData1 = new RoleDAO.Data(); + indData1.ns = "test"; + indData1.name = "test"; + Set<String> permsSet = new HashSet<>(); + permsSet.add("test|test|test|test"); + indData1.perms = permsSet; + dataObj1.add(indData1); + + List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); + UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); + indData4.ns = "test"; + indData4.rname = "test"; + dataObj4.add(indData4); + + List<PermDAO.Data> dataObj5 = new ArrayList<>(); + PermDAO.Data indData5 = new PermDAO.Data(); + indData5.ns = "test"; + indData5.type = "test"; + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("test|test|test|test"); + indData5.roles = rolesSet; + dataObj5.add(indData5); + + Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(dataObj,0,"test",NO_PARAM); + Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); + Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); + Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal2).when(userRoleDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal2).when(roleDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal2).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Mockito.doReturn(retVal2).when(permDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal5).when(permDAO).readChildren(trans, "test", "test"); + Mockito.doReturn(retVal5).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Mockito.doReturn(retVal3).when(roleDAO).readChildren(trans, "test", "test"); + + Identity iden=Mockito.mock(Identity.class); + try { + Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); + Mockito.doReturn("test").when(iden).mayOwn(); + Mockito.doReturn(true).when(org).isTestEnv(); + Mockito.doReturn(new GregorianCalendar(2010, 01, 01)).when(org).expiration(null, Expiration.UserInRole); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(roleDAO).read(trans, "test","test"); + Mockito.doReturn(Result.err(Result.ERR_NotFound, "Not Found")).when(permDAO).readByType(trans, "test","test"); - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.createNS(trans, namespace, true); - assertTrue(result.status == 0); - - } - - @Test - public void test4DeleteNs() { - Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deleteNS(trans, "test"); - - assertTrue(result.status == Status.ERR_NsNotFound); - } - - @Test - public void test4DeleteCanMoveFail() { - List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); - NsDAO.Data dataObj = new NsDAO.Data(); - dataObj.type=1; - dataAl.add(dataObj); - Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - Mockito.doReturn(false).when(ques).canMove(Mockito.any()); - Mockito.doReturn(retVal).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == Status.ERR_Security); - - } - - @Test - public void test4DeleteNsReadSuc() { - List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); - NsDAO.Data dataObj = new NsDAO.Data(); - dataObj.type=1; - dataAl.add(dataObj); - Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == 1); - - } - - @Test - public void test4DeleteNsMayUserSuc() { - List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); - NsDAO.Data dataObj = new NsDAO.Data(); - dataObj.type=1; - dataAl.add(dataObj); - Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == 1); + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.createNS(trans, namespace, true); + assertTrue(result.status == 0); + + } + + @Test + public void test4DeleteNs() { + Result<Void> retVal = new Result<Void>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deleteNS(trans, "test"); + + assertTrue(result.status == Status.ERR_NsNotFound); + } + + @Test + public void test4DeleteCanMoveFail() { + List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); + NsDAO.Data dataObj = new NsDAO.Data(); + dataObj.type=1; + dataAl.add(dataObj); + Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + Mockito.doReturn(false).when(ques).canMove(Mockito.any()); + Mockito.doReturn(retVal).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == Status.ERR_Security); + + } + + @Test + public void test4DeleteNsReadSuc() { + List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); + NsDAO.Data dataObj = new NsDAO.Data(); + dataObj.type=1; + dataAl.add(dataObj); + Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == 1); + + } + + @Test + public void test4DeleteNsMayUserSuc() { + List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); + NsDAO.Data dataObj = new NsDAO.Data(); + dataObj.type=1; + dataAl.add(dataObj); + Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == 1); - Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(retVal2).when(credDAO).readNS(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal2).when(credDAO).readNS(Mockito.any(), Mockito.anyString()); - Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test"); - - List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); - UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); - indData4.ns = "test"; - indData4.rname = "test"; - dataObj4.add(indData4); - Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); - Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(trans, "test"); - - List<RoleDAO.Data> dataObj1 = new ArrayList<>(); - RoleDAO.Data indData1 = new RoleDAO.Data(); - indData1.ns = "test"; - indData1.name = "test"; - Set<String> permsSet = new HashSet<>(); - permsSet.add("test|test"); - indData1.perms = permsSet; - dataObj1.add(indData1); - Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test"); - Mockito.doReturn(retVal3).when(roleDAO).read(trans, indData1); - - funcObj = new Function(trans, ques); - result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == Status.ERR_DependencyExists); - - Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - - Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); - funcObj = new Function(trans, ques); - result = funcObj.deleteNS(trans, "test"); - assertNull(result); - } - @Test - public void test4DeleteNsDrivensFailure() { - List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); - NsDAO.Data dataObj = new NsDAO.Data(); - dataObj.type=1; - dataAl.add(dataObj); - Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == 1); + Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test"); + + List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); + UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); + indData4.ns = "test"; + indData4.rname = "test"; + dataObj4.add(indData4); + Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); + Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(trans, "test"); + + List<RoleDAO.Data> dataObj1 = new ArrayList<>(); + RoleDAO.Data indData1 = new RoleDAO.Data(); + indData1.ns = "test"; + indData1.name = "test"; + Set<String> permsSet = new HashSet<>(); + permsSet.add("test|test"); + indData1.perms = permsSet; + dataObj1.add(indData1); + Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test"); + Mockito.doReturn(retVal3).when(roleDAO).read(trans, indData1); + + funcObj = new Function(trans, ques); + result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == Status.ERR_DependencyExists); + + Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + + Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); + funcObj = new Function(trans, ques); + result = funcObj.deleteNS(trans, "test"); + assertNull(result); + } + @Test + public void test4DeleteNsDrivensFailure() { + List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); + NsDAO.Data dataObj = new NsDAO.Data(); + dataObj.type=1; + dataAl.add(dataObj); + Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == 1); - Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(retVal2).when(credDAO).readNS(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal2).when(credDAO).readNS(Mockito.any(), Mockito.anyString()); - List<PermDAO.Data> dataObj5 = new ArrayList<>(); - PermDAO.Data indData5 = new PermDAO.Data(); - indData5.ns = "test"; - indData5.type = "test"; - dataObj5.add(indData5); - Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); - Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test"); - Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test.test"); - Mockito.doReturn(retVal5).when(permDAO).read(trans, indData5); - - - List<RoleDAO.Data> dataObj1 = new ArrayList<>(); - RoleDAO.Data indData1 = new RoleDAO.Data(); - indData1.ns = "test"; - indData1.name = "test"; - Set<String> permsSet = new HashSet<>(); - permsSet.add("test|test"); - indData1.perms = permsSet; - dataObj1.add(indData1); - Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test"); - Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test.test"); - Mockito.doReturn(retVal3).when(roleDAO).read(trans, indData1); - - funcObj = new Function(trans, ques); - result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == Status.ERR_DependencyExists); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); - funcObj = new Function(trans, ques); - result = funcObj.deleteNS(trans, "test.test"); - assertTrue(result.status == 1); - } + List<PermDAO.Data> dataObj5 = new ArrayList<>(); + PermDAO.Data indData5 = new PermDAO.Data(); + indData5.ns = "test"; + indData5.type = "test"; + dataObj5.add(indData5); + Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); + Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test"); + Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test.test"); + Mockito.doReturn(retVal5).when(permDAO).read(trans, indData5); + + + List<RoleDAO.Data> dataObj1 = new ArrayList<>(); + RoleDAO.Data indData1 = new RoleDAO.Data(); + indData1.ns = "test"; + indData1.name = "test"; + Set<String> permsSet = new HashSet<>(); + permsSet.add("test|test"); + indData1.perms = permsSet; + dataObj1.add(indData1); + Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test"); + Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test.test"); + Mockito.doReturn(retVal3).when(roleDAO).read(trans, indData1); + + funcObj = new Function(trans, ques); + result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == Status.ERR_DependencyExists); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); + funcObj = new Function(trans, ques); + result = funcObj.deleteNS(trans, "test.test"); + assertTrue(result.status == 1); + } - @Test - public void test4DeleteNsWithDot() { - List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); - NsDAO.Data dataObj = new NsDAO.Data(); - dataObj.type=1; - dataAl.add(dataObj); - Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); - - List<CredDAO.Data> nsDataList = new ArrayList<CredDAO.Data>(); - CredDAO.Data nsData = new CredDAO.Data(); - nsData.id="test"; - nsDataList.add(nsData); - Result<List<CredDAO.Data>> retVal21 = new Result<List<CredDAO.Data>>(nsDataList,0,"test",NO_PARAM); - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == 1); + @Test + public void test4DeleteNsWithDot() { + List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); + NsDAO.Data dataObj = new NsDAO.Data(); + dataObj.type=1; + dataAl.add(dataObj); + Result<List<NsDAO.Data>> retVal = new Result<List<NsDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(nsDAO).read(Mockito.any(), Mockito.anyString()); + + List<CredDAO.Data> nsDataList = new ArrayList<CredDAO.Data>(); + CredDAO.Data nsData = new CredDAO.Data(); + nsData.id="test"; + nsDataList.add(nsData); + Result<List<CredDAO.Data>> retVal21 = new Result<List<CredDAO.Data>>(nsDataList,0,"test",NO_PARAM); + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == 1); - Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(true).when(ques).isGranted(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(retVal21).when(credDAO).readNS(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal21).when(credDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Mockito.doReturn(retVal21).when(credDAO).readNS(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal21).when(credDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - List<PermDAO.Data> dataObj5 = new ArrayList<>(); - PermDAO.Data indData5 = new PermDAO.Data(); - indData5.ns = "test"; - indData5.type = "test"; - dataObj5.add(indData5); - Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",new Object[0]); - Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test"); - Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test.test"); - Mockito.doReturn(retVal5).when(permDAO).read(trans, indData5); - - List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); - UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); - indData4.ns = "test"; - indData4.rname = "test"; - dataObj4.add(indData4); - Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); - Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal4).when(userRoleDAO).readByUser(Mockito.any(), Mockito.anyString()); - - List<RoleDAO.Data> dataObj1 = new ArrayList<>(); - RoleDAO.Data indData1 = new RoleDAO.Data(); - indData1.ns = "test"; - indData1.name = "admin"; - Set<String> permsSet = new HashSet<>(); - permsSet.add("test|test"); - indData1.perms = permsSet; - dataObj1.add(indData1); - Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test"); - Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test.test"); - Mockito.doReturn(retVal3).when(roleDAO).read(trans, indData1); - - funcObj = new Function(trans, ques); - result = funcObj.deleteNS(trans, "test"); - assertTrue(result.status == Status.ERR_DependencyExists); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); - funcObj = new Function(trans, ques); - result = funcObj.deleteNS(trans, "test.test"); - assertNull(result); - } - - @Test - public void testGetOwners() { -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); -// -// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); -// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); -// - Function funcObj = new Function(trans, ques); - Result<List<String>> result = funcObj.getOwners(trans, "test", false); - assertTrue(result.status == 1); -// - } - - @Test - public void testDelOwner() { - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); + List<PermDAO.Data> dataObj5 = new ArrayList<>(); + PermDAO.Data indData5 = new PermDAO.Data(); + indData5.ns = "test"; + indData5.type = "test"; + dataObj5.add(indData5); + Result<List<PermDAO.Data>> retVal5 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",new Object[0]); + Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test"); + Mockito.doReturn(retVal5).when(permDAO).readNS(trans, "test.test"); + Mockito.doReturn(retVal5).when(permDAO).read(trans, indData5); + + List<UserRoleDAO.Data> dataObj4 = new ArrayList<>(); + UserRoleDAO.Data indData4 = new UserRoleDAO.Data(); + indData4.ns = "test"; + indData4.rname = "test"; + dataObj4.add(indData4); + Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(dataObj4,0,"test",NO_PARAM); + Mockito.doReturn(retVal4).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal4).when(userRoleDAO).readByUser(Mockito.any(), Mockito.anyString()); + + List<RoleDAO.Data> dataObj1 = new ArrayList<>(); + RoleDAO.Data indData1 = new RoleDAO.Data(); + indData1.ns = "test"; + indData1.name = "admin"; + Set<String> permsSet = new HashSet<>(); + permsSet.add("test|test"); + indData1.perms = permsSet; + dataObj1.add(indData1); + Result<List<RoleDAO.Data>> retVal3 = new Result<List<RoleDAO.Data>>(dataObj1,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test"); + Mockito.doReturn(retVal3).when(roleDAO).readNS(trans, "test.test"); + Mockito.doReturn(retVal3).when(roleDAO).read(trans, indData1); + + funcObj = new Function(trans, ques); + result = funcObj.deleteNS(trans, "test"); + assertTrue(result.status == Status.ERR_DependencyExists); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); + funcObj = new Function(trans, ques); + result = funcObj.deleteNS(trans, "test.test"); + assertNull(result); + } + + @Test + public void testGetOwners() { +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); +// +// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); +// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); +// + Function funcObj = new Function(trans, ques); + Result<List<String>> result = funcObj.getOwners(trans, "test", false); + assertTrue(result.status == 1); +// + } + + @Test + public void testDelOwner() { + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.delOwner(trans, "test", "test"); - assertTrue(result.status == 1); - - retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - result = funcObj.delOwner(trans, "test", "test"); - assertTrue(result.status == 1); - - retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - result = funcObj.delOwner(trans, "test", "test"); - retVal2 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); - result = funcObj.delOwner(trans, "test", "test"); -// - } - - @Test - public void testGetAdmins() { -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); -// -// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); -// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); -// - Function funcObj = new Function(trans, ques); - Result<List<String>> result = funcObj.getAdmins(trans, "test", false); - assertTrue(result.status == 1); -// - } - - @Test - public void testDelAdmin() { - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readUserInRole(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.delOwner(trans, "test", "test"); + assertTrue(result.status == 1); + + retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + result = funcObj.delOwner(trans, "test", "test"); + assertTrue(result.status == 1); + + retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + result = funcObj.delOwner(trans, "test", "test"); + retVal2 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); + result = funcObj.delOwner(trans, "test", "test"); +// + } + + @Test + public void testGetAdmins() { +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); +// +// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); +// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); +// + Function funcObj = new Function(trans, ques); + Result<List<String>> result = funcObj.getAdmins(trans, "test", false); + assertTrue(result.status == 1); +// + } + + @Test + public void testDelAdmin() { + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readUserInRole(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.delAdmin(trans, "test", "test"); - assertTrue(result.status == 1); - - retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - result = funcObj.delAdmin(trans, "test", "test"); - assertTrue(result.status == 1); - - retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - result = funcObj.delOwner(trans, "test", "test"); - retVal2 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); - result = funcObj.delAdmin(trans, "test", "test"); -// - } - - @Test - public void testMovePerms() { -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - - Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); - - Mockito.doReturn(retVal).when(permDAO).create(Mockito.any(), Mockito.any()); - - NsDAO.Data nsDataObj = new NsDAO.Data(); - nsDataObj.name="test"; - StringBuilder sb = new StringBuilder(); - Result<List<PermDAO.Data>> retVal1 = new Result<List<PermDAO.Data>>(null,1,"test",NO_PARAM); - - invokeMovePerms(nsDataObj, sb, retVal1); - - List<PermDAO.Data> dataObj5 = new ArrayList<>(); - PermDAO.Data indData5 = new PermDAO.Data(); - indData5.ns = "test"; - indData5.type = "test"; - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("testRole"); - indData5.roles = rolesSet; - dataObj5.add(indData5); - indData5 = new PermDAO.Data(); - indData5.ns = "test"; - indData5.type = "access"; - dataObj5.add(indData5); - retVal1 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.delAdmin(trans, "test", "test"); + assertTrue(result.status == 1); + + retVal1 = new Result<NsDAO.Data>(data,1,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + result = funcObj.delAdmin(trans, "test", "test"); + assertTrue(result.status == 1); + + retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + result = funcObj.delOwner(trans, "test", "test"); + retVal2 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal1.value, Access.write); + result = funcObj.delAdmin(trans, "test", "test"); +// + } + + @Test + public void testMovePerms() { +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + + Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); + + Mockito.doReturn(retVal).when(permDAO).create(Mockito.any(), Mockito.any()); + + NsDAO.Data nsDataObj = new NsDAO.Data(); + nsDataObj.name="test"; + StringBuilder sb = new StringBuilder(); + Result<List<PermDAO.Data>> retVal1 = new Result<List<PermDAO.Data>>(null,1,"test",NO_PARAM); + + invokeMovePerms(nsDataObj, sb, retVal1); + + List<PermDAO.Data> dataObj5 = new ArrayList<>(); + PermDAO.Data indData5 = new PermDAO.Data(); + indData5.ns = "test"; + indData5.type = "test"; + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("testRole"); + indData5.roles = rolesSet; + dataObj5.add(indData5); + indData5 = new PermDAO.Data(); + indData5.ns = "test"; + indData5.type = "access"; + dataObj5.add(indData5); + retVal1 = new Result<List<PermDAO.Data>>(dataObj5,0,"test",NO_PARAM); - Result<List<UserRoleDAO.Data>> retVal3 = new Result<List<UserRoleDAO.Data>>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(permDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal3).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + Result<List<UserRoleDAO.Data>> retVal3 = new Result<List<UserRoleDAO.Data>>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(permDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal3).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - NsSplit splitObj = new NsSplit("test", "test"); - Result<NsSplit> retVal2 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); - - invokeMovePerms(nsDataObj, sb, retVal1); - - Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal4).when(permDAO).create(Mockito.any(), Mockito.any()); - invokeMovePerms(nsDataObj, sb, retVal1); - - Mockito.doReturn(retVal3).when(permDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal4).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - invokeMovePerms(nsDataObj, sb, retVal1); - - } - - private void invokeMovePerms(NsDAO.Data nsDataObj, StringBuilder sb,Result<List<PermDAO.Data>> retVal1) { - Function funcObj = new Function(trans, ques); - Method met; - try { - met = Function.class.getDeclaredMethod("movePerms", AuthzTrans.class, NsDAO.Data.class, StringBuilder.class, Result.class); - met.setAccessible(true); - met.invoke(funcObj, trans, nsDataObj, sb, retVal1); - } catch (NoSuchMethodException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testMoveRoles() { -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - - Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); - - Mockito.doReturn(retVal).when(roleDAO).create(Mockito.any(), Mockito.any()); - - NsDAO.Data nsDataObj = new NsDAO.Data(); - nsDataObj.name="test"; - StringBuilder sb = new StringBuilder(); - Result<List<RoleDAO.Data>> retVal1 = new Result<List<RoleDAO.Data>>(null,1,"test",NO_PARAM); - - invokeMoveRoles(nsDataObj, sb, retVal1); - - List<RoleDAO.Data> dataObj5 = new ArrayList<>(); - RoleDAO.Data indData5 = new RoleDAO.Data(); - indData5.ns = "test"; - indData5.name = "test"; - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("testRole"); - indData5.perms = rolesSet; - dataObj5.add(indData5); - indData5 = new RoleDAO.Data(); - indData5.ns = "test"; - indData5.name = "admin"; - dataObj5.add(indData5); - retVal1 = new Result<List<RoleDAO.Data>>(dataObj5,0,"test",NO_PARAM); - - Result<List<UserRoleDAO.Data>> retVal3 = new Result<List<UserRoleDAO.Data>>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(roleDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal3).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + NsSplit splitObj = new NsSplit("test", "test"); + Result<NsSplit> retVal2 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); + + invokeMovePerms(nsDataObj, sb, retVal1); + + Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal4).when(permDAO).create(Mockito.any(), Mockito.any()); + invokeMovePerms(nsDataObj, sb, retVal1); + + Mockito.doReturn(retVal3).when(permDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal4).when(permDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + invokeMovePerms(nsDataObj, sb, retVal1); + + } + + private void invokeMovePerms(NsDAO.Data nsDataObj, StringBuilder sb,Result<List<PermDAO.Data>> retVal1) { + Function funcObj = new Function(trans, ques); + Method met; + try { + met = Function.class.getDeclaredMethod("movePerms", AuthzTrans.class, NsDAO.Data.class, StringBuilder.class, Result.class); + met.setAccessible(true); + met.invoke(funcObj, trans, nsDataObj, sb, retVal1); + } catch (NoSuchMethodException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testMoveRoles() { +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + + Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); + + Mockito.doReturn(retVal).when(roleDAO).create(Mockito.any(), Mockito.any()); + + NsDAO.Data nsDataObj = new NsDAO.Data(); + nsDataObj.name="test"; + StringBuilder sb = new StringBuilder(); + Result<List<RoleDAO.Data>> retVal1 = new Result<List<RoleDAO.Data>>(null,1,"test",NO_PARAM); + + invokeMoveRoles(nsDataObj, sb, retVal1); + + List<RoleDAO.Data> dataObj5 = new ArrayList<>(); + RoleDAO.Data indData5 = new RoleDAO.Data(); + indData5.ns = "test"; + indData5.name = "test"; + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("testRole"); + indData5.perms = rolesSet; + dataObj5.add(indData5); + indData5 = new RoleDAO.Data(); + indData5.ns = "test"; + indData5.name = "admin"; + dataObj5.add(indData5); + retVal1 = new Result<List<RoleDAO.Data>>(dataObj5,0,"test",NO_PARAM); + + Result<List<UserRoleDAO.Data>> retVal3 = new Result<List<UserRoleDAO.Data>>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(roleDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal3).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - NsSplit splitObj = new NsSplit("test", "test"); - Result<NsSplit> retVal2 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); - - invokeMoveRoles(nsDataObj, sb, retVal1); - - Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal4).when(roleDAO).create(Mockito.any(), Mockito.any()); - invokeMoveRoles(nsDataObj, sb, retVal1); - - Mockito.doReturn(retVal3).when(roleDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal4).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - invokeMoveRoles(nsDataObj, sb, retVal1); - - } - - private void invokeMoveRoles(NsDAO.Data nsDataObj, StringBuilder sb,Result<List<RoleDAO.Data>> retVal1) { - Function funcObj = new Function(trans, ques); - Method met; - try { - met = Function.class.getDeclaredMethod("moveRoles", AuthzTrans.class, NsDAO.Data.class, StringBuilder.class, Result.class); - met.setAccessible(true); - met.invoke(funcObj, trans, nsDataObj, sb, retVal1); - } catch (NoSuchMethodException | SecurityException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalAccessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IllegalArgumentException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (InvocationTargetException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testCreatePerm() { - try { - Define.set(access); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - List<PermDAO.Data> dataAl = new ArrayList<PermDAO.Data>(); - PermDAO.Data perm = new PermDAO.Data(); - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("testRole"); - perm.roles = rolesSet; -// perm.type=1 - dataAl.add(perm); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); - - Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); - Mockito.doReturn(retVal).when(userRoleDAO).create(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); - - Mockito.doReturn(retVal).when(permDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal).when(permDAO).read(trans, perm); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.createPerm(trans, perm, false); - assertTrue(result.status == 1); - - retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); - result = funcObj.createPerm(trans, perm, false); - assertTrue(result.status == 1); + NsSplit splitObj = new NsSplit("test", "test"); + Result<NsSplit> retVal2 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); + + invokeMoveRoles(nsDataObj, sb, retVal1); + + Result<List<UserRoleDAO.Data>> retVal4 = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal4).when(roleDAO).create(Mockito.any(), Mockito.any()); + invokeMoveRoles(nsDataObj, sb, retVal1); + + Mockito.doReturn(retVal3).when(roleDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal4).when(roleDAO).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + invokeMoveRoles(nsDataObj, sb, retVal1); + + } + + private void invokeMoveRoles(NsDAO.Data nsDataObj, StringBuilder sb,Result<List<RoleDAO.Data>> retVal1) { + Function funcObj = new Function(trans, ques); + Method met; + try { + met = Function.class.getDeclaredMethod("moveRoles", AuthzTrans.class, NsDAO.Data.class, StringBuilder.class, Result.class); + met.setAccessible(true); + met.invoke(funcObj, trans, nsDataObj, sb, retVal1); + } catch (NoSuchMethodException | SecurityException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalAccessException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (InvocationTargetException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testCreatePerm() { + try { + Define.set(access); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + List<PermDAO.Data> dataAl = new ArrayList<PermDAO.Data>(); + PermDAO.Data perm = new PermDAO.Data(); + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("testRole"); + perm.roles = rolesSet; +// perm.type=1 + dataAl.add(perm); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); + + Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); + Mockito.doReturn(retVal).when(userRoleDAO).create(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); + + Mockito.doReturn(retVal).when(permDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal).when(permDAO).read(trans, perm); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.createPerm(trans, perm, false); + assertTrue(result.status == 1); + + retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); + result = funcObj.createPerm(trans, perm, false); + assertTrue(result.status == 1); - NsSplit nsObj = new NsSplit("test","test"); - Result<NsSplit> retValNs = new Result<NsSplit>(nsObj,0,"test",NO_PARAM); - Mockito.doReturn(retValNs).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal2).when(ques).mayUser(Mockito.any(), Mockito.anyString(),Mockito.any(RoleDAO.Data.class), Mockito.any()); - Result<List<RoleDAO.Data>> retVal3 = Result.ok(new ArrayList<>()); - Mockito.doReturn(retVal3).when(roleDAO).read(Mockito.any(),Mockito.any(RoleDAO.Data.class)); - Result<List<RoleDAO.Data>> retVal4 = Result.err(Result.ERR_NotFound,""); - Mockito.doReturn(retVal4).when(roleDAO).create(Mockito.any(),Mockito.any(RoleDAO.Data.class)); - result = funcObj.createPerm(trans, perm, false); - - Mockito.doReturn(retVal).when(permDAO).read(trans, perm); - result = funcObj.createPerm(trans, perm, true); - assertTrue(result.status == 1); + NsSplit nsObj = new NsSplit("test","test"); + Result<NsSplit> retValNs = new Result<NsSplit>(nsObj,0,"test",NO_PARAM); + Mockito.doReturn(retValNs).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal2).when(ques).mayUser(Mockito.any(), Mockito.anyString(),Mockito.any(RoleDAO.Data.class), Mockito.any()); + Result<List<RoleDAO.Data>> retVal3 = Result.ok(new ArrayList<>()); + Mockito.doReturn(retVal3).when(roleDAO).read(Mockito.any(),Mockito.any(RoleDAO.Data.class)); + Result<List<RoleDAO.Data>> retVal4 = Result.err(Result.ERR_NotFound,""); + Mockito.doReturn(retVal4).when(roleDAO).create(Mockito.any(),Mockito.any(RoleDAO.Data.class)); + result = funcObj.createPerm(trans, perm, false); + + Mockito.doReturn(retVal).when(permDAO).read(trans, perm); + result = funcObj.createPerm(trans, perm, true); + assertTrue(result.status == 1); - Mockito.doReturn(retVal2).when(permDAO).create(Mockito.any(), Mockito.any()); - result = funcObj.createPerm(trans, perm, true); - assertTrue(result.status == 0); - - Mockito.doReturn(false).when(trans).requested(REQD_TYPE.force); - Result<List<PermDAO.Data>> retVal1 = new Result<List<PermDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(permDAO).read(trans, perm); - result = funcObj.createPerm(trans, perm, true); - assertTrue(result.status == Status.ERR_ConflictAlreadyExists); - - } - @Test - public void testDeletePerm() { - try { - Define.set(access); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - List<PermDAO.Data> dataAl = new ArrayList<PermDAO.Data>(); - PermDAO.Data perm = new PermDAO.Data(); - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("testRole"); - perm.roles = rolesSet; -// perm.type=1 - dataAl.add(perm); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); - -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<PermDAO.Data>> retVal = new Result<List<PermDAO.Data>>(dataAl,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deletePerm(trans, perm, true,false); - assertTrue(result.status == 1); + Mockito.doReturn(retVal2).when(permDAO).create(Mockito.any(), Mockito.any()); + result = funcObj.createPerm(trans, perm, true); + assertTrue(result.status == 0); + + Mockito.doReturn(false).when(trans).requested(REQD_TYPE.force); + Result<List<PermDAO.Data>> retVal1 = new Result<List<PermDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(permDAO).read(trans, perm); + result = funcObj.createPerm(trans, perm, true); + assertTrue(result.status == Status.ERR_ConflictAlreadyExists); + + } + @Test + public void testDeletePerm() { + try { + Define.set(access); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + List<PermDAO.Data> dataAl = new ArrayList<PermDAO.Data>(); + PermDAO.Data perm = new PermDAO.Data(); + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("testRole"); + perm.roles = rolesSet; +// perm.type=1 + dataAl.add(perm); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); + +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<PermDAO.Data>> retVal = new Result<List<PermDAO.Data>>(dataAl,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deletePerm(trans, perm, true,false); + assertTrue(result.status == 1); -// Mockito.doReturn(retVal).when(cachedPermDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal).when(permDAO).read(trans, perm); - - result = funcObj.deletePerm(trans, perm, true,true); - assertTrue(result.status == Status.ERR_PermissionNotFound); +// Mockito.doReturn(retVal).when(cachedPermDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal).when(permDAO).read(trans, perm); + + result = funcObj.deletePerm(trans, perm, true,true); + assertTrue(result.status == Status.ERR_PermissionNotFound); - retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); - Result<List<PermDAO.Data>> retVal3 = new Result<List<PermDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(permDAO).read(trans, perm); - - NsSplit nsObj = new NsSplit("test","test"); - Result<NsSplit> retValNs = new Result<NsSplit>(nsObj,0,"test",NO_PARAM); - Mockito.doReturn(retValNs).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); - - Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); - - result = funcObj.deletePerm(trans, perm, true,false); - assertNull(result); - - Mockito.doReturn(retVal2).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); - result = funcObj.deletePerm(trans, perm, true,false); - assertNull(result); - - result = funcObj.deletePerm(trans, perm, false,false); -// assertTrue(result.status == 1); - } - - @Test - public void testDeleteRole() { - try { - Define.set(access); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,perm, Access.write); + Result<List<PermDAO.Data>> retVal3 = new Result<List<PermDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(permDAO).read(trans, perm); + + NsSplit nsObj = new NsSplit("test","test"); + Result<NsSplit> retValNs = new Result<NsSplit>(nsObj,0,"test",NO_PARAM); + Mockito.doReturn(retValNs).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); + + Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); + + result = funcObj.deletePerm(trans, perm, true,false); + assertNull(result); + + Mockito.doReturn(retVal2).when(roleDAO).delPerm(Mockito.any(), Mockito.any(), Mockito.any()); + result = funcObj.deletePerm(trans, perm, true,false); + assertNull(result); + + result = funcObj.deletePerm(trans, perm, false,false); +// assertTrue(result.status == 1); + } + + @Test + public void testDeleteRole() { + try { + Define.set(access); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } - List<UserRoleDAO.Data> dataAlUser = new ArrayList<UserRoleDAO.Data>(); - UserRoleDAO.Data roleUser = new UserRoleDAO.Data(); - Set<String> rolesSetUser = new HashSet<>(); - rolesSetUser.add("testRole|test|test"); -// perm.roles = rolesSet; -// perm.type=1 - dataAlUser.add(roleUser); - - List<RoleDAO.Data> dataAl = new ArrayList<RoleDAO.Data>(); - RoleDAO.Data role = new RoleDAO.Data(); - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("testRole|test|test"); - role.perms = rolesSet; -// perm.roles = rolesSet; -// perm.type=1 - dataAl.add(role); - - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,role, Access.write); - -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); -// -// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); -// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); -// - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.deleteRole(trans, role, true, false); - assertTrue(result.status == 1); + List<UserRoleDAO.Data> dataAlUser = new ArrayList<UserRoleDAO.Data>(); + UserRoleDAO.Data roleUser = new UserRoleDAO.Data(); + Set<String> rolesSetUser = new HashSet<>(); + rolesSetUser.add("testRole|test|test"); +// perm.roles = rolesSet; +// perm.type=1 + dataAlUser.add(roleUser); + + List<RoleDAO.Data> dataAl = new ArrayList<RoleDAO.Data>(); + RoleDAO.Data role = new RoleDAO.Data(); + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("testRole|test|test"); + role.perms = rolesSet; +// perm.roles = rolesSet; +// perm.type=1 + dataAl.add(role); + + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,role, Access.write); + +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); +// +// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); +// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); +// + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.deleteRole(trans, role, true, false); + assertTrue(result.status == 1); - Result<List<RoleDAO.Data>> retVal1 = new Result<List<RoleDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); - NsSplit splitObj = new NsSplit("test", "test"); - Result<NsSplit> retVal3 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); -// Mockito.doReturn(retVal).when(cachedPermDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any()); - result = funcObj.deleteRole(trans, role, true, true); - assertNull(result); - - Mockito.doReturn(retVal1).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any()); - result = funcObj.deleteRole(trans, role, true, true); - assertNull(result); + Result<List<RoleDAO.Data>> retVal1 = new Result<List<RoleDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); + NsSplit splitObj = new NsSplit("test", "test"); + Result<NsSplit> retVal3 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); +// Mockito.doReturn(retVal).when(cachedPermDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any()); + result = funcObj.deleteRole(trans, role, true, true); + assertNull(result); + + Mockito.doReturn(retVal1).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any()); + result = funcObj.deleteRole(trans, role, true, true); + assertNull(result); - Mockito.doReturn(retVal).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); - result = funcObj.deleteRole(trans, role, true, true); - assertTrue(result.status == Status.ERR_RoleNotFound); - - retVal = new Result<List<UserRoleDAO.Data>>(dataAlUser,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - result = funcObj.deleteRole(trans, role, false, true); - assertTrue(result.status == Status.ERR_DependencyExists); - } - - @Test - public void testAddPermToRole() { - List<PermDAO.Data> dataAlPerm = new ArrayList<PermDAO.Data>(); - PermDAO.Data rolePerm = new PermDAO.Data(); - Set<String> rolesSetUser = new HashSet<>(); - rolesSetUser.add("testRole|test|test"); -// perm.roles = rolesSet; -// perm.type=1 - dataAlPerm.add(rolePerm); - - List<RoleDAO.Data> dataAl = new ArrayList<RoleDAO.Data>(); - RoleDAO.Data role = new RoleDAO.Data(); - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("17623"); - role.perms = rolesSet; -// perm.roles = rolesSet; -// perm.type=1 - dataAl.add(role); - - NsDAO.Data nsObj = new NsDAO.Data(); - nsObj.name="test"; - NsDAO.Data nsObj1 = new NsDAO.Data(); - nsObj1.name="test12"; - -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); + result = funcObj.deleteRole(trans, role, true, true); + assertTrue(result.status == Status.ERR_RoleNotFound); + + retVal = new Result<List<UserRoleDAO.Data>>(dataAlUser,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + result = funcObj.deleteRole(trans, role, false, true); + assertTrue(result.status == Status.ERR_DependencyExists); + } + + @Test + public void testAddPermToRole() { + List<PermDAO.Data> dataAlPerm = new ArrayList<PermDAO.Data>(); + PermDAO.Data rolePerm = new PermDAO.Data(); + Set<String> rolesSetUser = new HashSet<>(); + rolesSetUser.add("testRole|test|test"); +// perm.roles = rolesSet; +// perm.type=1 + dataAlPerm.add(rolePerm); + + List<RoleDAO.Data> dataAl = new ArrayList<RoleDAO.Data>(); + RoleDAO.Data role = new RoleDAO.Data(); + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("17623"); + role.perms = rolesSet; +// perm.roles = rolesSet; +// perm.type=1 + dataAl.add(role); + + NsDAO.Data nsObj = new NsDAO.Data(); + nsObj.name="test"; + NsDAO.Data nsObj1 = new NsDAO.Data(); + nsObj1.name="test12"; + +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(nsObj,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); - - Result<NsDAO.Data> retVal3 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,rolePerm, Access.write); - Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,role, Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.addPermToRole(trans, role, rolePerm, false); - assertTrue(result.status == 1); + Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(nsObj,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); + + Result<NsDAO.Data> retVal3 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,rolePerm, Access.write); + Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,role, Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.addPermToRole(trans, role, rolePerm, false); + assertTrue(result.status == 1); - retVal2 = new Result<NsDAO.Data>(nsObj,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); - result = funcObj.addPermToRole(trans, role, rolePerm, false); - assertTrue(result.status == 1); - - role.ns="test2"; - retVal2 = new Result<NsDAO.Data>(nsObj,0,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - result = funcObj.addPermToRole(trans, role, rolePerm, false); - assertTrue(result.status == 1); - - retVal2 = new Result<NsDAO.Data>(nsObj,0,"test1",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - Result<NsDAO.Data> retVal21 = new Result<NsDAO.Data>(nsObj1,0,"test1",NO_PARAM); - Mockito.doReturn(retVal21).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); - result = funcObj.addPermToRole(trans, role, rolePerm, false); - assertTrue(result.status == 1); - - retVal3 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,rolePerm, Access.write); - retVal2 = new Result<NsDAO.Data>(nsObj,0,"test1",NO_PARAM); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); - Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); - -// Mockito.doReturn(retVal).when(cachedPermDAO).create(Mockito.any(), Mockito.any()); - Mockito.doReturn(retVal).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); - - result = funcObj.addPermToRole(trans, role, rolePerm, false); - assertTrue(result.status == Status.ERR_PermissionNotFound); - - Result<List<PermDAO.Data>> retValPerm= new Result<List<PermDAO.Data>>(dataAlPerm,0,"test1",NO_PARAM); - Mockito.doReturn(retValPerm).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); - - Mockito.doReturn(retVal3).when(roleDAO).read(trans, role); - - result = funcObj.addPermToRole(trans, role, rolePerm, true); - assertTrue(result.status == 22); + retVal2 = new Result<NsDAO.Data>(nsObj,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); + result = funcObj.addPermToRole(trans, role, rolePerm, false); + assertTrue(result.status == 1); + + role.ns="test2"; + retVal2 = new Result<NsDAO.Data>(nsObj,0,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); + result = funcObj.addPermToRole(trans, role, rolePerm, false); + assertTrue(result.status == 1); + + retVal2 = new Result<NsDAO.Data>(nsObj,0,"test1",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); + Result<NsDAO.Data> retVal21 = new Result<NsDAO.Data>(nsObj1,0,"test1",NO_PARAM); + Mockito.doReturn(retVal21).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); + result = funcObj.addPermToRole(trans, role, rolePerm, false); + assertTrue(result.status == 1); + + retVal3 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,rolePerm, Access.write); + retVal2 = new Result<NsDAO.Data>(nsObj,0,"test1",NO_PARAM); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, role.ns, NsType.COMPANY); + Mockito.doReturn(retVal2).when(ques).deriveFirstNsForType(trans, rolePerm.ns, NsType.COMPANY); + +// Mockito.doReturn(retVal).when(cachedPermDAO).create(Mockito.any(), Mockito.any()); + Mockito.doReturn(retVal).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); + + result = funcObj.addPermToRole(trans, role, rolePerm, false); + assertTrue(result.status == Status.ERR_PermissionNotFound); + + Result<List<PermDAO.Data>> retValPerm= new Result<List<PermDAO.Data>>(dataAlPerm,0,"test1",NO_PARAM); + Mockito.doReturn(retValPerm).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); + + Mockito.doReturn(retVal3).when(roleDAO).read(trans, role); + + result = funcObj.addPermToRole(trans, role, rolePerm, true); + assertTrue(result.status == 22); - Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); - result = funcObj.addPermToRole(trans, role, rolePerm, true); - assertTrue(result.status == 2); - - retVal3 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,role, Access.write); - Mockito.doReturn(retVal3).when(roleDAO).create(trans, role); - result = funcObj.addPermToRole(trans, role, rolePerm, true); -// System.out.println(result.status); - assertNull(result); - - retVal3 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(roleDAO).create(trans, role); - result = funcObj.addPermToRole(trans, role, rolePerm, true); - assertTrue(result.status == 1); - - Result<List<RoleDAO.Data>> retVal31 = new Result<List<RoleDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal31).when(roleDAO).read(trans, role); - result = funcObj.addPermToRole(trans, role, rolePerm, true); - assertTrue(result.status == 7); - } - - @Test - public void testDelPermFromRole() { - List<PermDAO.Data> dataAlPerm = new ArrayList<PermDAO.Data>(); - PermDAO.Data rolePerm = new PermDAO.Data(); - Set<String> rolesSetUser = new HashSet<>(); - rolesSetUser.add("testRole|test|test"); -// perm.roles = rolesSet; -// perm.type=1 - dataAlPerm.add(rolePerm); - - List<RoleDAO.Data> dataAl = new ArrayList<RoleDAO.Data>(); - RoleDAO.Data role = new RoleDAO.Data(); - Set<String> rolesSet = new HashSet<>(); - rolesSet.add("17623"); - role.perms = rolesSet; - dataAl.add(role); - -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); + result = funcObj.addPermToRole(trans, role, rolePerm, true); + assertTrue(result.status == 2); + + retVal3 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(ques).mayUser(trans, null,role, Access.write); + Mockito.doReturn(retVal3).when(roleDAO).create(trans, role); + result = funcObj.addPermToRole(trans, role, rolePerm, true); +// System.out.println(result.status); + assertNull(result); + + retVal3 = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(roleDAO).create(trans, role); + result = funcObj.addPermToRole(trans, role, rolePerm, true); + assertTrue(result.status == 1); + + Result<List<RoleDAO.Data>> retVal31 = new Result<List<RoleDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal31).when(roleDAO).read(trans, role); + result = funcObj.addPermToRole(trans, role, rolePerm, true); + assertTrue(result.status == 7); + } + + @Test + public void testDelPermFromRole() { + List<PermDAO.Data> dataAlPerm = new ArrayList<PermDAO.Data>(); + PermDAO.Data rolePerm = new PermDAO.Data(); + Set<String> rolesSetUser = new HashSet<>(); + rolesSetUser.add("testRole|test|test"); +// perm.roles = rolesSet; +// perm.type=1 + dataAlPerm.add(rolePerm); + + List<RoleDAO.Data> dataAl = new ArrayList<RoleDAO.Data>(); + RoleDAO.Data role = new RoleDAO.Data(); + Set<String> rolesSet = new HashSet<>(); + rolesSet.add("17623"); + role.perms = rolesSet; + dataAl.add(role); + +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Result<NsDAO.Data> retValFail = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); - Result<NsDAO.Data> retValSuc = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); - Mockito.doReturn(retValFail).when(ques).mayUser(trans, null,rolePerm, Access.write); - Mockito.doReturn(retValFail).when(ques).mayUser(trans, null,role, Access.write); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.delPermFromRole(trans, role, rolePerm, false); - assertTrue(result.status == Status.ERR_Denied); - - Mockito.doReturn(retValFail).when(ques).mayUser(trans, null,rolePerm, Access.write); - Mockito.doReturn(retValSuc).when(ques).mayUser(trans, null,role, Access.write); - - Mockito.doReturn(retValFail).when(roleDAO).read(trans, role); - - Mockito.doReturn(retVal).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); - - result = funcObj.delPermFromRole(trans, role, rolePerm, false); - assertTrue(result.status == 1); - - Result<List<PermDAO.Data>> retValPermSuc = new Result<List<PermDAO.Data>>(dataAlPerm,0,"test",NO_PARAM); - Mockito.doReturn(retValPermSuc).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); - result = funcObj.delPermFromRole(trans, role, rolePerm, false); - assertTrue(result.status == 1); - - Result<List<RoleDAO.Data>> retValRoleSuc = new Result<List<RoleDAO.Data>>(dataAl,0,"test",NO_PARAM); - Mockito.doReturn(retValRoleSuc).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); - result = funcObj.delPermFromRole(trans, role, rolePerm, true); - assertTrue(result.status == Status.ERR_PermissionNotFound); - - role.perms = null; - dataAl.add(role); - rolesSet.add("null|null|null|null"); - role.perms = rolesSet; - dataAl.add(role); - Mockito.doReturn(retValRoleSuc).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); - Mockito.doReturn(retVal).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any(RoleDAO.Data.class)); - result = funcObj.delPermFromRole(trans, role, rolePerm, true); - assertTrue(result.status == 1); - - Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); - result = funcObj.delPermFromRole(trans, role, rolePerm, true); - assertTrue(result.status == 1); - - Mockito.doReturn(retValRoleSuc).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any(RoleDAO.Data.class)); - Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(),Mockito.any(PermDAO.Data.class)); - result = funcObj.delPermFromRole(trans, role, rolePerm, true); - assertTrue(result.status == 1); - - Mockito.doReturn(retValPermSuc).when(roleDAO).delPerm(Mockito.any(), Mockito.any(),Mockito.any(PermDAO.Data.class)); - result = funcObj.delPermFromRole(trans, role, rolePerm, true); - assertTrue(result.status == 0); - - Mockito.doReturn(retVal).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); - result = funcObj.delPermFromRole(trans, role, rolePerm, true); - assertTrue(result.status == 0); - - Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(),Mockito.any(PermDAO.Data.class)); - result = funcObj.delPermFromRole(trans, role, rolePerm, true); - assertTrue(result.status == 1); + Result<NsDAO.Data> retValFail = new Result<NsDAO.Data>(null,1,"test",NO_PARAM); + Result<NsDAO.Data> retValSuc = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); + Mockito.doReturn(retValFail).when(ques).mayUser(trans, null,rolePerm, Access.write); + Mockito.doReturn(retValFail).when(ques).mayUser(trans, null,role, Access.write); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.delPermFromRole(trans, role, rolePerm, false); + assertTrue(result.status == Status.ERR_Denied); + + Mockito.doReturn(retValFail).when(ques).mayUser(trans, null,rolePerm, Access.write); + Mockito.doReturn(retValSuc).when(ques).mayUser(trans, null,role, Access.write); + + Mockito.doReturn(retValFail).when(roleDAO).read(trans, role); + + Mockito.doReturn(retVal).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); + + result = funcObj.delPermFromRole(trans, role, rolePerm, false); + assertTrue(result.status == 1); + + Result<List<PermDAO.Data>> retValPermSuc = new Result<List<PermDAO.Data>>(dataAlPerm,0,"test",NO_PARAM); + Mockito.doReturn(retValPermSuc).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); + result = funcObj.delPermFromRole(trans, role, rolePerm, false); + assertTrue(result.status == 1); + + Result<List<RoleDAO.Data>> retValRoleSuc = new Result<List<RoleDAO.Data>>(dataAl,0,"test",NO_PARAM); + Mockito.doReturn(retValRoleSuc).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); + result = funcObj.delPermFromRole(trans, role, rolePerm, true); + assertTrue(result.status == Status.ERR_PermissionNotFound); + + role.perms = null; + dataAl.add(role); + rolesSet.add("null|null|null|null"); + role.perms = rolesSet; + dataAl.add(role); + Mockito.doReturn(retValRoleSuc).when(roleDAO).read(Mockito.any(), Mockito.any(RoleDAO.Data.class)); + Mockito.doReturn(retVal).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any(RoleDAO.Data.class)); + result = funcObj.delPermFromRole(trans, role, rolePerm, true); + assertTrue(result.status == 1); + + Mockito.doReturn(true).when(trans).requested(REQD_TYPE.force); + result = funcObj.delPermFromRole(trans, role, rolePerm, true); + assertTrue(result.status == 1); + + Mockito.doReturn(retValRoleSuc).when(permDAO).delRole(Mockito.any(), Mockito.any(),Mockito.any(RoleDAO.Data.class)); + Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(),Mockito.any(PermDAO.Data.class)); + result = funcObj.delPermFromRole(trans, role, rolePerm, true); + assertTrue(result.status == 1); + + Mockito.doReturn(retValPermSuc).when(roleDAO).delPerm(Mockito.any(), Mockito.any(),Mockito.any(PermDAO.Data.class)); + result = funcObj.delPermFromRole(trans, role, rolePerm, true); + assertTrue(result.status == 0); + + Mockito.doReturn(retVal).when(permDAO).read(Mockito.any(), Mockito.any(PermDAO.Data.class)); + result = funcObj.delPermFromRole(trans, role, rolePerm, true); + assertTrue(result.status == 0); + + Mockito.doReturn(retVal).when(roleDAO).delPerm(Mockito.any(), Mockito.any(),Mockito.any(PermDAO.Data.class)); + result = funcObj.delPermFromRole(trans, role, rolePerm, true); + assertTrue(result.status == 1); - NsSplit splitObj = new NsSplit("test", "test"); - Result<NsSplit> retVal3 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retValFail).when(ques).mayUser(Mockito.any(), Mockito.anyString(),Mockito.any(RoleDAO.Data.class), Mockito.any()); - Mockito.doReturn(retValFail).when(ques).mayUser(Mockito.any(), Mockito.anyString(),Mockito.any(PermDAO.Data.class), Mockito.any()); - result = funcObj.delPermFromRole(trans, "test", rolePerm); - assertTrue(result.status == 2); - - retVal3 = new Result<NsSplit>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal3).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); - result = funcObj.delPermFromRole(trans, "test", rolePerm); - assertTrue(result.status == 1); - } - @Test - public void testAddUserRole() { - List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); - UserRoleDAO.Data urData = new UserRoleDAO.Data(); - urData.ns="test"; - urData.rname="test"; - urData.user="test"; - urDataAl.add(urData); - - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - Mockito.doReturn(Mockito.mock(GregorianCalendar.class)).when(org).expiration(Mockito.any(), Mockito.any(), Mockito.anyString()); - - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Result<List<UserRoleDAO.Data>> retValSuc = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); - Mockito.doReturn(retVal).when(userRoleDAO).create(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); - Mockito.doReturn(retValSuc).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + NsSplit splitObj = new NsSplit("test", "test"); + Result<NsSplit> retVal3 = new Result<NsSplit>(splitObj,0,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retValFail).when(ques).mayUser(Mockito.any(), Mockito.anyString(),Mockito.any(RoleDAO.Data.class), Mockito.any()); + Mockito.doReturn(retValFail).when(ques).mayUser(Mockito.any(), Mockito.anyString(),Mockito.any(PermDAO.Data.class), Mockito.any()); + result = funcObj.delPermFromRole(trans, "test", rolePerm); + assertTrue(result.status == 2); + + retVal3 = new Result<NsSplit>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal3).when(ques).deriveNsSplit(Mockito.any(), Mockito.anyString()); + result = funcObj.delPermFromRole(trans, "test", rolePerm); + assertTrue(result.status == 1); + } + @Test + public void testAddUserRole() { + List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); + UserRoleDAO.Data urData = new UserRoleDAO.Data(); + urData.ns="test"; + urData.rname="test"; + urData.user="test"; + urDataAl.add(urData); + + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + Mockito.doReturn(Mockito.mock(GregorianCalendar.class)).when(org).expiration(Mockito.any(), Mockito.any(), Mockito.anyString()); + + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Result<List<UserRoleDAO.Data>> retValSuc = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); + Mockito.doReturn(retVal).when(userRoleDAO).create(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); + Mockito.doReturn(retValSuc).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.addUserRole(trans, urData); - assertTrue(result.status == 1); - - urData.rname=Question.ADMIN; - result = funcObj.addUserRole(trans, urData); - assertTrue(result.status == 1); - - NsDAO.Data data = new NsDAO.Data(); - data.name="test"; - Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); - Mockito.doReturn(retVal1).when(ques).mayUser(trans, null,retVal1.value, Access.write); - Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); - try { - Mockito.doReturn(Mockito.mock(Identity.class)).when(org).getIdentity(trans, "test"); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - urData.rname=Question.OWNER; - result = funcObj.addUserRole(trans, urData); - assertTrue(result.status == 1); + Result<List<CredDAO.Data>> retVal2 = new Result<List<CredDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal2).when(credDAO).readID(Mockito.any(), Mockito.anyString()); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.addUserRole(trans, urData); + assertTrue(result.status == 1); + + urData.rname=Question.ADMIN; + result = funcObj.addUserRole(trans, urData); + assertTrue(result.status == 1); + + NsDAO.Data data = new NsDAO.Data(); + data.name="test"; + Result<NsDAO.Data> retVal1 = new Result<NsDAO.Data>(data,0,"test",NO_PARAM); + Mockito.doReturn(retVal1).when(ques).mayUser(trans, null,retVal1.value, Access.write); + Mockito.doReturn(retVal1).when(ques).deriveNs(trans, "test"); + try { + Mockito.doReturn(Mockito.mock(Identity.class)).when(org).getIdentity(trans, "test"); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + urData.rname=Question.OWNER; + result = funcObj.addUserRole(trans, urData); + assertTrue(result.status == 1); - Mockito.doReturn(retValSuc).when(userRoleDAO).create(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); - result = funcObj.addUserRole(trans, urData); - assertTrue(result.status == 0); + Mockito.doReturn(retValSuc).when(userRoleDAO).create(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); + result = funcObj.addUserRole(trans, urData); + assertTrue(result.status == 0); - Mockito.doReturn(retVal).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - result = funcObj.addUserRole(trans, urData); - assertTrue(result.status == Status.ERR_RoleNotFound); - - Mockito.doReturn(retValSuc).when(userRoleDAO).read(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); - result = funcObj.addUserRole(trans, urData); - assertTrue(result.status == Status.ERR_ConflictAlreadyExists); - - result = funcObj.addUserRole(trans, "test", "test", "test"); - assertTrue(result.status == 1); - - try { - Mockito.doReturn(null).when(org).getIdentity(trans, "test"); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - result = funcObj.addUserRole(trans, "test", "test", "test"); - assertTrue(result.status == Result.ERR_BadData); - - try { - Mockito.doThrow(OrganizationException.class).when(org).getIdentity(trans, "test"); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - result = funcObj.addUserRole(trans, "test", "test", "test"); - assertTrue(result.status == 20); - } - - @Test - public void testExtendUserRole() { - List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); - UserRoleDAO.Data urData = new UserRoleDAO.Data(); - urData.ns="test"; - urData.rname="test"; - urData.user="test"; - urData.expires=new Date(); - urDataAl.add(urData); - -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Result<List<UserRoleDAO.Data>> retValSuc = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Mockito.doReturn(retValSuc).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(retVal).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + result = funcObj.addUserRole(trans, urData); + assertTrue(result.status == Status.ERR_RoleNotFound); + + Mockito.doReturn(retValSuc).when(userRoleDAO).read(Mockito.any(), Mockito.any(UserRoleDAO.Data.class)); + result = funcObj.addUserRole(trans, urData); + assertTrue(result.status == Status.ERR_ConflictAlreadyExists); + + result = funcObj.addUserRole(trans, "test", "test", "test"); + assertTrue(result.status == 1); + + try { + Mockito.doReturn(null).when(org).getIdentity(trans, "test"); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + result = funcObj.addUserRole(trans, "test", "test", "test"); + assertTrue(result.status == Result.ERR_BadData); + + try { + Mockito.doThrow(OrganizationException.class).when(org).getIdentity(trans, "test"); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + result = funcObj.addUserRole(trans, "test", "test", "test"); + assertTrue(result.status == 20); + } + + @Test + public void testExtendUserRole() { + List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); + UserRoleDAO.Data urData = new UserRoleDAO.Data(); + urData.ns="test"; + urData.rname="test"; + urData.user="test"; + urData.expires=new Date(); + urDataAl.add(urData); + +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Result<List<UserRoleDAO.Data>> retValSuc = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Mockito.doReturn(retValSuc).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Organization org = Mockito.mock(Organization.class); - Mockito.doReturn(org).when(trans).org(); - Mockito.doReturn(Mockito.mock(GregorianCalendar.class)).when(org).expiration(Mockito.any(), Mockito.any()); - - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.extendUserRole(trans, urData, false); - assertNull(result); - - Mockito.doReturn(retVal).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); - Mockito.doReturn(retValSuc).when(userRoleDAO).read(trans, urData); - result = funcObj.extendUserRole(trans, urData, true); - assertTrue(result.status == Status.ERR_RoleNotFound); - - Mockito.doReturn(retVal).when(userRoleDAO).read(trans, urData); - result = funcObj.extendUserRole(trans, urData, true); - assertTrue(result.status == Status.ERR_UserRoleNotFound); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetUsersByRole() { - List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); - UserRoleDAO.Data urData = new UserRoleDAO.Data(); - urData.ns="test"; - urData.rname="test"; - urData.user="test"; - urData.expires=new Date(); - urDataAl.add(urData); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + Organization org = Mockito.mock(Organization.class); + Mockito.doReturn(org).when(trans).org(); + Mockito.doReturn(Mockito.mock(GregorianCalendar.class)).when(org).expiration(Mockito.any(), Mockito.any()); + + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.extendUserRole(trans, urData, false); + assertNull(result); + + Mockito.doReturn(retVal).when(roleDAO).read(Mockito.any(), Mockito.anyString(), Mockito.anyString()); + Mockito.doReturn(retValSuc).when(userRoleDAO).read(trans, urData); + result = funcObj.extendUserRole(trans, urData, true); + assertTrue(result.status == Status.ERR_RoleNotFound); + + Mockito.doReturn(retVal).when(userRoleDAO).read(trans, urData); + result = funcObj.extendUserRole(trans, urData, true); + assertTrue(result.status == Status.ERR_UserRoleNotFound); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetUsersByRole() { + List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); + UserRoleDAO.Data urData = new UserRoleDAO.Data(); + urData.ns="test"; + urData.rname="test"; + urData.user="test"; + urData.expires=new Date(); + urDataAl.add(urData); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - Function funcObj = new Function(trans, ques); - Result<List<String>> result = funcObj.getUsersByRole(trans, "test", false); - assertTrue(result.status == 0); + Function funcObj = new Function(trans, ques); + Result<List<String>> result = funcObj.getUsersByRole(trans, "test", false); + assertTrue(result.status == 0); - result = funcObj.getUsersByRole(trans, "test", true); - assertTrue(result.status == 0); - - urData.expires=new Date(130,1,1); - result = funcObj.getUsersByRole(trans, "test", true); - assertTrue(result.status == 0); -// - } - @Test - public void testDelUserRole() { - List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); - UserRoleDAO.Data urData = new UserRoleDAO.Data(); - urData.ns="test"; - urData.rname="test"; - urData.user="test"; - urData.expires=new Date(); - urDataAl.add(urData); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); + result = funcObj.getUsersByRole(trans, "test", true); + assertTrue(result.status == 0); + + urData.expires=new Date(130,1,1); + result = funcObj.getUsersByRole(trans, "test", true); + assertTrue(result.status == 0); +// + } + @Test + public void testDelUserRole() { + List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); + UserRoleDAO.Data urData = new UserRoleDAO.Data(); + urData.ns="test"; + urData.rname="test"; + urData.user="test"; + urData.expires=new Date(); + urDataAl.add(urData); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); - Function funcObj = new Function(trans, ques); - Result<Void> result = funcObj.delUserRole(trans, "test", "test", "test"); - assertNull(result); - - retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); - result = funcObj.delUserRole(trans, "test", "test", "test"); -// assertTrue(result.status ==1); -// - } - - @Test - public void testCreateFuture() { - FutureDAO.Data data = new FutureDAO.Data(); - data.memo = "test"; - NsDAO.Data nsd = new NsDAO.Data(); - nsd.name = "test"; - - List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); - UserRoleDAO.Data urData = new UserRoleDAO.Data(); - urData.ns="test"; - urData.rname="test"; - urData.user="test"; - urData.expires=new Date(); - urDataAl.add(urData); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); - Result<List<UserRoleDAO.Data>> retValFail = new Result<List<UserRoleDAO.Data>>(urDataAl,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); + Function funcObj = new Function(trans, ques); + Result<Void> result = funcObj.delUserRole(trans, "test", "test", "test"); + assertNull(result); + + retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); + result = funcObj.delUserRole(trans, "test", "test", "test"); +// assertTrue(result.status ==1); +// + } + + @Test + public void testCreateFuture() { + FutureDAO.Data data = new FutureDAO.Data(); + data.memo = "test"; + NsDAO.Data nsd = new NsDAO.Data(); + nsd.name = "test"; + + List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); + UserRoleDAO.Data urData = new UserRoleDAO.Data(); + urData.ns="test"; + urData.rname="test"; + urData.user="test"; + urData.expires=new Date(); + urDataAl.add(urData); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); + Result<List<UserRoleDAO.Data>> retValFail = new Result<List<UserRoleDAO.Data>>(urDataAl,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).read(Mockito.any(), Mockito.any( UserRoleDAO.Data.class)); - Function funcObj = new Function(trans, ques); - Result<String> result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); - assertTrue(result.status == 20); + Function funcObj = new Function(trans, ques); + Result<String> result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); + assertTrue(result.status == 20); - Identity iden=Mockito.mock(Identity.class); - try { - Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); - Mockito.doReturn("test").when(iden).mayOwn(); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - FutureDAO.Data futureData = new FutureDAO.Data(); - data.memo = "test"; - Result<FutureDAO.Data> retValFuture = new Result<FutureDAO.Data>(futureData,0,"test",NO_PARAM); - Mockito.doReturn(retValFuture).when(futureDAO).create(Mockito.any(), Mockito.any( FutureDAO.Data.class), Mockito.anyString()); - - ApprovalDAO.Data approvalData = new ApprovalDAO.Data(); - data.memo = "test"; - Result<ApprovalDAO.Data> retValApproval = new Result<ApprovalDAO.Data>(approvalData,0,"test",NO_PARAM); - Mockito.doReturn(retValApproval).when(approvalDAO).create(Mockito.any(), Mockito.any( ApprovalDAO.Data.class)); - - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); - assertTrue(result.status == 0); - - result = funcObj.createFuture(trans, data, "test", "test", null, FUTURE_OP.A); - assertTrue(result.status == 20); + Identity iden=Mockito.mock(Identity.class); + try { + Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); + Mockito.doReturn("test").when(iden).mayOwn(); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + FutureDAO.Data futureData = new FutureDAO.Data(); + data.memo = "test"; + Result<FutureDAO.Data> retValFuture = new Result<FutureDAO.Data>(futureData,0,"test",NO_PARAM); + Mockito.doReturn(retValFuture).when(futureDAO).create(Mockito.any(), Mockito.any( FutureDAO.Data.class), Mockito.anyString()); + + ApprovalDAO.Data approvalData = new ApprovalDAO.Data(); + data.memo = "test"; + Result<ApprovalDAO.Data> retValApproval = new Result<ApprovalDAO.Data>(approvalData,0,"test",NO_PARAM); + Mockito.doReturn(retValApproval).when(approvalDAO).create(Mockito.any(), Mockito.any( ApprovalDAO.Data.class)); + + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); + assertTrue(result.status == 0); + + result = funcObj.createFuture(trans, data, "test", "test", null, FUTURE_OP.A); + assertTrue(result.status == 20); - Mockito.doReturn(retValFail).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); - assertTrue(result.status == Result.ERR_NotFound); - - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); - try { - Mockito.doReturn(null).when(org).getIdentity(trans, "test"); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); - assertTrue(result.status == Result.ERR_NotFound); - - try { - Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); - } catch (OrganizationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.C); - assertTrue(result.status == 0); - - retValApproval = new Result<ApprovalDAO.Data>(null,1,"test",NO_PARAM); - Mockito.doReturn(retValApproval).when(approvalDAO).create(Mockito.any(), Mockito.any( ApprovalDAO.Data.class)); - result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); - assertTrue(result.status == 8); - } - @Test - public void testUbLookup() { - Object[] objArr = new Object[10]; - List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); - UserRoleDAO.Data urData = new UserRoleDAO.Data(); - urData.ns="test"; - urData.rname="test"; - urData.user="test"; - urData.expires=new Date(); - urDataAl.add(urData); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); - Result<List<UserRoleDAO.Data>> retValFail = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).read(trans, objArr); - - Function funcObj = new Function(trans, ques); - funcObj.urDBLookup.get(trans, objArr); - - Mockito.doReturn(retValFail).when(userRoleDAO).read(trans, objArr); - funcObj.urDBLookup.get(trans, objArr); - } - - @Test - public void testPerformFutureOp() { - FutureDAO.Data futureDataDaoObj = new FutureDAO.Data(); - futureDataDaoObj.memo="test"; - futureDataDaoObj.target = "test"; - futureDataDaoObj.id = new UUID(10L,10L); - - final List<ApprovalDAO.Data> apprs = new ArrayList<>(); - ApprovalDAO.Data approvalObj = new ApprovalDAO.Data(); - approvalObj.status = "approved"; - approvalObj.type = "owner"; - apprs.add(approvalObj); - Lookup<List<ApprovalDAO.Data>> lookupApprovalObj = new Lookup<List<ApprovalDAO.Data>>() { + Mockito.doReturn(retValFail).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); + assertTrue(result.status == Result.ERR_NotFound); + + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); + try { + Mockito.doReturn(null).when(org).getIdentity(trans, "test"); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); + assertTrue(result.status == Result.ERR_NotFound); + + try { + Mockito.doReturn(iden).when(org).getIdentity(trans, "test"); + } catch (OrganizationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.C); + assertTrue(result.status == 0); + + retValApproval = new Result<ApprovalDAO.Data>(null,1,"test",NO_PARAM); + Mockito.doReturn(retValApproval).when(approvalDAO).create(Mockito.any(), Mockito.any( ApprovalDAO.Data.class)); + result = funcObj.createFuture(trans, data, "test", "test", nsd, FUTURE_OP.A); + assertTrue(result.status == 8); + } + @Test + public void testUbLookup() { + Object[] objArr = new Object[10]; + List<UserRoleDAO.Data> urDataAl = new ArrayList<>(); + UserRoleDAO.Data urData = new UserRoleDAO.Data(); + urData.ns="test"; + urData.rname="test"; + urData.user="test"; + urData.expires=new Date(); + urDataAl.add(urData); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(urDataAl,0,"test",NO_PARAM); + Result<List<UserRoleDAO.Data>> retValFail = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).read(trans, objArr); + + Function funcObj = new Function(trans, ques); + funcObj.urDBLookup.get(trans, objArr); + + Mockito.doReturn(retValFail).when(userRoleDAO).read(trans, objArr); + funcObj.urDBLookup.get(trans, objArr); + } + + @Test + public void testPerformFutureOp() { + FutureDAO.Data futureDataDaoObj = new FutureDAO.Data(); + futureDataDaoObj.memo="test"; + futureDataDaoObj.target = "test"; + futureDataDaoObj.id = new UUID(10L,10L); + + final List<ApprovalDAO.Data> apprs = new ArrayList<>(); + ApprovalDAO.Data approvalObj = new ApprovalDAO.Data(); + approvalObj.status = "approved"; + approvalObj.type = "owner"; + apprs.add(approvalObj); + Lookup<List<ApprovalDAO.Data>> lookupApprovalObj = new Lookup<List<ApprovalDAO.Data>>() { @Override public List<ApprovalDAO.Data> get(AuthzTrans trans, Object ... keys) { return apprs; @@ -1706,61 +1706,61 @@ public class JU_Function { return userObj; } }; - + FutureDAO.Data futureData = new FutureDAO.Data(); -// data.memo = "test"; - Result<FutureDAO.Data> retValFuture = new Result<FutureDAO.Data>(futureData,0,"test",NO_PARAM); - Mockito.doReturn(retValFuture).when(futureDAO).delete(Mockito.any(), Mockito.any( FutureDAO.Data.class), Mockito.anyBoolean()); - -// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); -// NsDAO.Data dataObj = new NsDAO.Data(); -// dataObj.type=1; -// dataAl.add(dataObj); - Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); - Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); -// -// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); -// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); -// - Function funcObj = new Function(trans, ques); - Result<Function.OP_STATUS> result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - assertTrue(result.status == 0); - - approvalObj.status = "approved"; - approvalObj.type = "supervisor"; - result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - assertTrue(result.status == 0); - - approvalObj.status = "approved"; - approvalObj.type = ""; - result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - assertTrue(result.status == 0); - - approvalObj.status = "pending"; - approvalObj.type = "supervisor"; - result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - assertTrue(result.status == 0); - - approvalObj.status = "pending"; - approvalObj.type = "owner"; - result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - assertTrue(result.status == 0); - - approvalObj.status = "pending"; - approvalObj.type = ""; - result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - assertTrue(result.status == 0); - - approvalObj.status = "denied"; - approvalObj.type = ""; - result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - assertTrue(result.status == 0); - - retValFuture = new Result<FutureDAO.Data>(futureData,1,"test",NO_PARAM); - Mockito.doReturn(retValFuture).when(futureDAO).delete(Mockito.any(), Mockito.any( FutureDAO.Data.class), Mockito.anyBoolean()); - result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); - System.out.println(result); - assertTrue(result.status == 0); -// - } +// data.memo = "test"; + Result<FutureDAO.Data> retValFuture = new Result<FutureDAO.Data>(futureData,0,"test",NO_PARAM); + Mockito.doReturn(retValFuture).when(futureDAO).delete(Mockito.any(), Mockito.any( FutureDAO.Data.class), Mockito.anyBoolean()); + +// List<NsDAO.Data> dataAl = new ArrayList<NsDAO.Data>(); +// NsDAO.Data dataObj = new NsDAO.Data(); +// dataObj.type=1; +// dataAl.add(dataObj); + Result<List<UserRoleDAO.Data>> retVal = new Result<List<UserRoleDAO.Data>>(null,1,"test",NO_PARAM); + Mockito.doReturn(retVal).when(userRoleDAO).readByRole(Mockito.any(), Mockito.anyString()); +// +// Result<NsDAO.Data> retVal2 = new Result<NsDAO.Data>(null,0,"test",NO_PARAM); +// Mockito.doReturn(retVal2).when(ques).mayUser(trans, null,retVal.value.get(0), Access.write); +// + Function funcObj = new Function(trans, ques); + Result<Function.OP_STATUS> result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + assertTrue(result.status == 0); + + approvalObj.status = "approved"; + approvalObj.type = "supervisor"; + result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + assertTrue(result.status == 0); + + approvalObj.status = "approved"; + approvalObj.type = ""; + result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + assertTrue(result.status == 0); + + approvalObj.status = "pending"; + approvalObj.type = "supervisor"; + result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + assertTrue(result.status == 0); + + approvalObj.status = "pending"; + approvalObj.type = "owner"; + result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + assertTrue(result.status == 0); + + approvalObj.status = "pending"; + approvalObj.type = ""; + result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + assertTrue(result.status == 0); + + approvalObj.status = "denied"; + approvalObj.type = ""; + result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + assertTrue(result.status == 0); + + retValFuture = new Result<FutureDAO.Data>(futureData,1,"test",NO_PARAM); + Mockito.doReturn(retValFuture).when(futureDAO).delete(Mockito.any(), Mockito.any( FutureDAO.Data.class), Mockito.anyBoolean()); + result = funcObj.performFutureOp(trans, FUTURE_OP.A, futureDataDaoObj, lookupApprovalObj, lookupUserObj); + System.out.println(result); + assertTrue(result.status == 0); +// + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_PermLookup.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_PermLookup.java index 9313af7a..7e1abeba 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_PermLookup.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/dao/hl/JU_PermLookup.java @@ -54,335 +54,335 @@ import org.onap.aaf.misc.env.LogTarget; @RunWith(MockitoJUnitRunner.class) public class JU_PermLookup { - - - @Mock - AuthzTrans trans; - - @Mock - Question q; - - @Mock - Access access; + + + @Mock + AuthzTrans trans; + + @Mock + Question q; + + @Mock + Access access; - @Mock - CachedRoleDAO roleDAO; + @Mock + CachedRoleDAO roleDAO; - @Mock - CachedUserRoleDAO userRoleDAO; - - Function f; - - @Before - public void setUp() throws Exception { - initMocks(this); - Mockito.doReturn(userRoleDAO).when(q).userRoleDAO(); - Mockito.doReturn(roleDAO).when(q).roleDAO(); - - try { - Mockito.doReturn("0.0").when(access).getProperty("aaf_root_ns","org.osaaf.aaf"); - Mockito.doReturn(new Properties()).when(access).getProperties(); - Define.set(access); - - when(trans.error()).thenReturn(new LogTarget() { - - @Override - public void printf(String fmt, Object... vars) {} - - @Override - public void log(Throwable e, Object... msgs) { - e.getMessage(); - e.printStackTrace(); - msgs.toString(); - - } - - @Override - public void log(Object... msgs) { - } - - @Override - public boolean isLoggable() { - - return true; - } - }); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - f =new Function(trans, q); - } - - -// @Test -// public void testPerm() { -// -// PermLookup cassExecutorObj =PermLookup.get(trans, q,""); -// -//// System.out.println(cassExecutorObj); -//// assertFalse(retVal); -// } - - @Test - public void testGetUserRole() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - dataObj.expires = new Date(); - - retVal1.value.add(dataObj); - Mockito.doReturn(true).when(retVal1).isOKhasData(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<List<UserRoleDAO.Data>> userRoles = cassExecutorObj.getUserRoles(); - - //System.out.println(""+userRoles.status); - assertEquals(24,userRoles.status); - } - - @Test - public void testGetUserRolesFirstIf() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - - Mockito.doReturn(false).when(retVal1).isOKhasData(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<List<UserRoleDAO.Data>> userRoles = cassExecutorObj.getUserRoles(); - -// System.out.println("output is"+userRoles.status); - assertEquals(0,userRoles.status); - } - - @Test - public void testGetUserRolesSecondIf() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - Date dt = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(dt); - c.add(Calendar.DATE, 1); - dataObj.expires = c.getTime(); - - retVal1.value.add(dataObj); - Mockito.doReturn(true).when(retVal1).isOKhasData(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<List<UserRoleDAO.Data>> userRoles = cassExecutorObj.getUserRoles(); - - //System.out.println(userRoles.status); - assertEquals("Success",userRoles.details); - Result<List<UserRoleDAO.Data>> userRoles1 = cassExecutorObj.getUserRoles(); + @Mock + CachedUserRoleDAO userRoleDAO; + + Function f; + + @Before + public void setUp() throws Exception { + initMocks(this); + Mockito.doReturn(userRoleDAO).when(q).userRoleDAO(); + Mockito.doReturn(roleDAO).when(q).roleDAO(); + + try { + Mockito.doReturn("0.0").when(access).getProperty("aaf_root_ns","org.osaaf.aaf"); + Mockito.doReturn(new Properties()).when(access).getProperties(); + Define.set(access); + + when(trans.error()).thenReturn(new LogTarget() { + + @Override + public void printf(String fmt, Object... vars) {} + + @Override + public void log(Throwable e, Object... msgs) { + e.getMessage(); + e.printStackTrace(); + msgs.toString(); + + } + + @Override + public void log(Object... msgs) { + } + + @Override + public boolean isLoggable() { + + return true; + } + }); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + f =new Function(trans, q); + } + + +// @Test +// public void testPerm() { +// +// PermLookup cassExecutorObj =PermLookup.get(trans, q,""); +// +//// System.out.println(cassExecutorObj); +//// assertFalse(retVal); +// } + + @Test + public void testGetUserRole() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + dataObj.expires = new Date(); + + retVal1.value.add(dataObj); + Mockito.doReturn(true).when(retVal1).isOKhasData(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<List<UserRoleDAO.Data>> userRoles = cassExecutorObj.getUserRoles(); + + //System.out.println(""+userRoles.status); + assertEquals(24,userRoles.status); + } + + @Test + public void testGetUserRolesFirstIf() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + + Mockito.doReturn(false).when(retVal1).isOKhasData(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<List<UserRoleDAO.Data>> userRoles = cassExecutorObj.getUserRoles(); + +// System.out.println("output is"+userRoles.status); + assertEquals(0,userRoles.status); + } + + @Test + public void testGetUserRolesSecondIf() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + Date dt = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dataObj.expires = c.getTime(); + + retVal1.value.add(dataObj); + Mockito.doReturn(true).when(retVal1).isOKhasData(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<List<UserRoleDAO.Data>> userRoles = cassExecutorObj.getUserRoles(); + + //System.out.println(userRoles.status); + assertEquals("Success",userRoles.details); + Result<List<UserRoleDAO.Data>> userRoles1 = cassExecutorObj.getUserRoles(); - //System.out.println(userRoles1.status); - assertEquals(0, userRoles1.status); - } - - @Test - public void testGetRole() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - dataObj.expires = new Date(); - - retVal1.value.add(dataObj); - Mockito.doReturn(false).when(retVal1).isOKhasData(); - Mockito.doReturn(true).when(retVal1).isOK(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<List<RoleDAO.Data>> userRoles = cassExecutorObj.getRoles(); - - //System.out.println(""+userRoles.status); - assertEquals(4,userRoles.status); - } - - @Test - public void testGetRoleFirstIf() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - dataObj.expires = new Date(); - dataObj.ns=""; - dataObj.rname=""; - - retVal1.value.add(dataObj); - Mockito.doReturn(false).when(retVal1).isOKhasData(); - Mockito.doReturn(false).when(retVal1).isOK(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - Mockito.doReturn(retVal1).when(roleDAO).read(trans,"",""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<List<RoleDAO.Data>> userRoles = cassExecutorObj.getRoles(); - -// System.out.println(""+userRoles.status); - assertEquals(0,userRoles.status); - } - - @Test - public void testGetRoleSecondIf() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - dataObj.expires = new Date(); - dataObj.ns=""; - dataObj.rname=""; - - retVal1.value.add(dataObj); - Mockito.doReturn(false).when(retVal1).isOKhasData(); - Mockito.doReturn(true).when(retVal1).isOK(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - Mockito.doReturn(retVal1).when(roleDAO).read(trans,"",""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<List<RoleDAO.Data>> userRoles = cassExecutorObj.getRoles(); - userRoles = cassExecutorObj.getRoles(); - -// System.out.println(""+userRoles.status); - assertEquals(0,userRoles.status); - } - @Test - public void testGetPerms() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - Mockito.doReturn(false).when(retVal1).isOKhasData(); - Mockito.doReturn(true).when(retVal1).isOK(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<Set<String>> userRoles = cassExecutorObj.getPermNames(); - userRoles = cassExecutorObj.getPermNames(); - - //System.out.println(""+userRoles.status); - assertEquals(0,userRoles.status); - } - @Test - public void testGetPermsRrldOk() { - @SuppressWarnings("unchecked") - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - dataObj.expires = new Date(); - - retVal1.value.add(dataObj); - Mockito.doReturn(false).when(retVal1).isOKhasData(); - Mockito.doReturn(true).when(retVal1).isOK(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); - Result<Set<String>> userRoles = cassExecutorObj.getPermNames(); - - //System.out.println(""+userRoles.status); - assertEquals(4,userRoles.status); - } + //System.out.println(userRoles1.status); + assertEquals(0, userRoles1.status); + } + + @Test + public void testGetRole() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + dataObj.expires = new Date(); + + retVal1.value.add(dataObj); + Mockito.doReturn(false).when(retVal1).isOKhasData(); + Mockito.doReturn(true).when(retVal1).isOK(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<List<RoleDAO.Data>> userRoles = cassExecutorObj.getRoles(); + + //System.out.println(""+userRoles.status); + assertEquals(4,userRoles.status); + } + + @Test + public void testGetRoleFirstIf() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + dataObj.expires = new Date(); + dataObj.ns=""; + dataObj.rname=""; + + retVal1.value.add(dataObj); + Mockito.doReturn(false).when(retVal1).isOKhasData(); + Mockito.doReturn(false).when(retVal1).isOK(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + Mockito.doReturn(retVal1).when(roleDAO).read(trans,"",""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<List<RoleDAO.Data>> userRoles = cassExecutorObj.getRoles(); + +// System.out.println(""+userRoles.status); + assertEquals(0,userRoles.status); + } + + @Test + public void testGetRoleSecondIf() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + dataObj.expires = new Date(); + dataObj.ns=""; + dataObj.rname=""; + + retVal1.value.add(dataObj); + Mockito.doReturn(false).when(retVal1).isOKhasData(); + Mockito.doReturn(true).when(retVal1).isOK(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + Mockito.doReturn(retVal1).when(roleDAO).read(trans,"",""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<List<RoleDAO.Data>> userRoles = cassExecutorObj.getRoles(); + userRoles = cassExecutorObj.getRoles(); + +// System.out.println(""+userRoles.status); + assertEquals(0,userRoles.status); + } + @Test + public void testGetPerms() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + Mockito.doReturn(false).when(retVal1).isOKhasData(); + Mockito.doReturn(true).when(retVal1).isOK(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<Set<String>> userRoles = cassExecutorObj.getPermNames(); + userRoles = cassExecutorObj.getPermNames(); + + //System.out.println(""+userRoles.status); + assertEquals(0,userRoles.status); + } + @Test + public void testGetPermsRrldOk() { + @SuppressWarnings("unchecked") + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + dataObj.expires = new Date(); + + retVal1.value.add(dataObj); + Mockito.doReturn(false).when(retVal1).isOKhasData(); + Mockito.doReturn(true).when(retVal1).isOK(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); + Result<Set<String>> userRoles = cassExecutorObj.getPermNames(); + + //System.out.println(""+userRoles.status); + assertEquals(4,userRoles.status); + } - @SuppressWarnings("unchecked") - @Test - public void testGetPerm() { - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - Result<List<RoleDAO.Data>> retVal2 = Mockito.mock(Result.class); - - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - retVal2.value = new ArrayList<RoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - Date dt = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(dt); - c.add(Calendar.DATE, 1); - dataObj.expires = c.getTime(); - dataObj.ns = ""; - dataObj.rname=""; - - RoleDAO.Data dataObj1 = Mockito.mock( RoleDAO.Data.class); - Set<String> permSet = new HashSet<String>(); - permSet.add("test"); - Mockito.doReturn(permSet).when(dataObj1).perms(false); - - dt = new Date(); - c = Calendar.getInstance(); - c.setTime(dt); - c.add(Calendar.DATE, 1); - dataObj1.ns = "test"; - dataObj1.perms = permSet; - - retVal1.value.add(dataObj); - retVal2.value.add(dataObj1); - Mockito.doReturn(true).when(retVal1).isOKhasData(); - Mockito.doReturn(true).when(retVal1).isOK(); - Mockito.doReturn(true).when(retVal2).isOK(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - Mockito.doReturn(retVal2).when(roleDAO).read(trans,"",""); + @SuppressWarnings("unchecked") + @Test + public void testGetPerm() { + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + Result<List<RoleDAO.Data>> retVal2 = Mockito.mock(Result.class); + + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + retVal2.value = new ArrayList<RoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + Date dt = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dataObj.expires = c.getTime(); + dataObj.ns = ""; + dataObj.rname=""; + + RoleDAO.Data dataObj1 = Mockito.mock( RoleDAO.Data.class); + Set<String> permSet = new HashSet<String>(); + permSet.add("test"); + Mockito.doReturn(permSet).when(dataObj1).perms(false); + + dt = new Date(); + c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dataObj1.ns = "test"; + dataObj1.perms = permSet; + + retVal1.value.add(dataObj); + retVal2.value.add(dataObj1); + Mockito.doReturn(true).when(retVal1).isOKhasData(); + Mockito.doReturn(true).when(retVal1).isOK(); + Mockito.doReturn(true).when(retVal2).isOK(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + Mockito.doReturn(retVal2).when(roleDAO).read(trans,"",""); - - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); -// -// Mockito.doReturn(retVal2).when(cassExecutorObj).getPermNames(); - Result<List<Data>> userRoles = cassExecutorObj.getPerms(true); -// userRoles = cassExecutorObj.getPerms(false); - -// System.out.println(""+userRoles.status); - assertEquals(0,userRoles.status); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetPermFalse() { - Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); - Result<List<RoleDAO.Data>> retVal2 = Mockito.mock(Result.class); - - retVal1.value = new ArrayList<UserRoleDAO.Data>(); - retVal2.value = new ArrayList<RoleDAO.Data>(); - UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); - - Date dt = new Date(); - Calendar c = Calendar.getInstance(); - c.setTime(dt); - c.add(Calendar.DATE, 1); - dataObj.expires = c.getTime(); - dataObj.ns = ""; - dataObj.rname=""; - - RoleDAO.Data dataObj1 = Mockito.mock( RoleDAO.Data.class); - Set<String> permSet = new HashSet<String>(); - permSet.add("test"); - Mockito.doReturn(permSet).when(dataObj1).perms(false); - - dt = new Date(); - c = Calendar.getInstance(); - c.setTime(dt); - c.add(Calendar.DATE, 1); - dataObj1.ns = "test"; - dataObj1.perms = permSet; - - retVal1.value.add(dataObj); - retVal2.value.add(dataObj1); - Mockito.doReturn(true).when(retVal1).isOKhasData(); - Mockito.doReturn(true).when(retVal1).isOK(); - Mockito.doReturn(true).when(retVal2).isOK(); - Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); - Mockito.doReturn(retVal2).when(roleDAO).read(trans,"",""); + + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); +// +// Mockito.doReturn(retVal2).when(cassExecutorObj).getPermNames(); + Result<List<Data>> userRoles = cassExecutorObj.getPerms(true); +// userRoles = cassExecutorObj.getPerms(false); + +// System.out.println(""+userRoles.status); + assertEquals(0,userRoles.status); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetPermFalse() { + Result<List<UserRoleDAO.Data>> retVal1 = Mockito.mock(Result.class); + Result<List<RoleDAO.Data>> retVal2 = Mockito.mock(Result.class); + + retVal1.value = new ArrayList<UserRoleDAO.Data>(); + retVal2.value = new ArrayList<RoleDAO.Data>(); + UserRoleDAO.Data dataObj = Mockito.mock( UserRoleDAO.Data.class); + + Date dt = new Date(); + Calendar c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dataObj.expires = c.getTime(); + dataObj.ns = ""; + dataObj.rname=""; + + RoleDAO.Data dataObj1 = Mockito.mock( RoleDAO.Data.class); + Set<String> permSet = new HashSet<String>(); + permSet.add("test"); + Mockito.doReturn(permSet).when(dataObj1).perms(false); + + dt = new Date(); + c = Calendar.getInstance(); + c.setTime(dt); + c.add(Calendar.DATE, 1); + dataObj1.ns = "test"; + dataObj1.perms = permSet; + + retVal1.value.add(dataObj); + retVal2.value.add(dataObj1); + Mockito.doReturn(true).when(retVal1).isOKhasData(); + Mockito.doReturn(true).when(retVal1).isOK(); + Mockito.doReturn(true).when(retVal2).isOK(); + Mockito.doReturn(retVal1).when(userRoleDAO).readByUser(trans,""); + Mockito.doReturn(retVal2).when(roleDAO).read(trans,"",""); - - PermLookup cassExecutorObj =PermLookup.get(trans, q,""); -// -// Mockito.doReturn(retVal2).when(cassExecutorObj).getPermNames(); - Result<List<Data>> userRoles = cassExecutorObj.getPerms(false); - userRoles = cassExecutorObj.getPerms(false); - -// System.out.println(""+userRoles.status); - assertEquals(0,userRoles.status); - } - + + PermLookup cassExecutorObj =PermLookup.get(trans, q,""); +// +// Mockito.doReturn(retVal2).when(cassExecutorObj).getPermNames(); + Result<List<Data>> userRoles = cassExecutorObj.getPerms(false); + userRoles = cassExecutorObj.getPerms(false); + +// System.out.println(""+userRoles.status); + assertEquals(0,userRoles.status); + } + }
\ No newline at end of file diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLocator.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLocator.java index f6d2a593..5a7d4959 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLocator.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLocator.java @@ -51,144 +51,144 @@ import junit.framework.Assert; @RunWith(MockitoJUnitRunner.class) public class JU_DirectAAFLocator { - @Mock - LocateDAO ldao; - - @Mock - AuthzEnv env; - - @Mock - AuthzTrans trans; - - @Mock - PropAccess access; - - @Before - public void setUp() throws Exception { - initMocks(this); - } - - @Test - public void testConstructorVersionExcpetion() { - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); - try { - DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","test"); - } catch (LocatorException e) { -// System.out.println(e.getMessage()); - assertEquals("Invalid Version String: test", e.getMessage()); - } - try { - DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","20.test"); - } catch (LocatorException e) { -// System.out.println(e.getMessage()); - assertEquals("Invalid Version String: 20.test", e.getMessage()); - }try { - DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","20.20.test"); - } catch (LocatorException e) { -// System.out.println(e.getMessage()); - assertEquals("Invalid Version String: 20.20.test", e.getMessage()); - }try { - DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","20.20.20.test"); - } catch (LocatorException e) { -// System.out.println(e.getMessage()); - assertEquals("Invalid Version String: 20.20.20.test", e.getMessage()); - } - } - - @Test - public void testConstructorExcpetion() { - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); - Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_APP_NS,"AAF_NS"); - try { - DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test",null); - } catch (LocatorException e) { -// System.out.println(e.getMessage()); - } - } - - // NOTE: These mocks to not well represent the DirectAAFLocator Class. - @Test - public void testConstructorUriExcpetion() { - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); - Mockito.doReturn("20 30").when(access).getProperty(Config.AAF_URL,null); - try { - DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","192.0.0.1"); - } catch (LocatorException e) { -// System.out.println(e.getMessage()); - assertTrue(e.getMessage().contains("Illegal character in path at index 2:")); - } - } + @Mock + LocateDAO ldao; + + @Mock + AuthzEnv env; + + @Mock + AuthzTrans trans; + + @Mock + PropAccess access; + + @Before + public void setUp() throws Exception { + initMocks(this); + } + + @Test + public void testConstructorVersionExcpetion() { + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); + try { + DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","test"); + } catch (LocatorException e) { +// System.out.println(e.getMessage()); + assertEquals("Invalid Version String: test", e.getMessage()); + } + try { + DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","20.test"); + } catch (LocatorException e) { +// System.out.println(e.getMessage()); + assertEquals("Invalid Version String: 20.test", e.getMessage()); + }try { + DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","20.20.test"); + } catch (LocatorException e) { +// System.out.println(e.getMessage()); + assertEquals("Invalid Version String: 20.20.test", e.getMessage()); + }try { + DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","20.20.20.test"); + } catch (LocatorException e) { +// System.out.println(e.getMessage()); + assertEquals("Invalid Version String: 20.20.20.test", e.getMessage()); + } + } + + @Test + public void testConstructorExcpetion() { + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); + Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_APP_NS,"AAF_NS"); + try { + DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test",null); + } catch (LocatorException e) { +// System.out.println(e.getMessage()); + } + } + + // NOTE: These mocks to not well represent the DirectAAFLocator Class. + @Test + public void testConstructorUriExcpetion() { + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); + Mockito.doReturn("20 30").when(access).getProperty(Config.AAF_URL,null); + try { + DirectAAFLocator aafLocatorObj=new DirectAAFLocator(env, ldao,"test","192.0.0.1"); + } catch (LocatorException e) { +// System.out.println(e.getMessage()); + assertTrue(e.getMessage().contains("Illegal character in path at index 2:")); + } + } - @Test - public void testRefresh() { - - DirectAAFLocator aafLocatorObj=null; - PropAccess access = Mockito.mock(PropAccess.class); - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); - Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); - try { - aafLocatorObj = new DirectAAFLocator(env, ldao,"test","30.20.30.30"); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"",new Object[0]); - - Data data= new Data(); - data.major=30; - data.minor=30; - data.patch=30; - data.pkg=30; - retVal1.value = new ArrayList<Data>(); - retVal1.value.add(data); - - Mockito.doReturn(retVal1).when(ldao).readByName(trans,"test"); - boolean retVal = aafLocatorObj.refresh(); -// System.out.println(retVal); - assertTrue(retVal); - } - - @Test - public void testRefreshNOK() { - - DirectAAFLocator aafLocatorObj=null; - PropAccess access = Mockito.mock(PropAccess.class); - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); - Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); - try { - aafLocatorObj = new DirectAAFLocator(env, ldao,"test","30.20.30.30"); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"",new String[0]); - - Mockito.doReturn(retVal1).when(ldao).readByName(trans,"test"); - boolean retVal = aafLocatorObj.refresh(); -// System.out.println(retVal); - assertFalse(retVal); - } - + @Test + public void testRefresh() { + + DirectAAFLocator aafLocatorObj=null; + PropAccess access = Mockito.mock(PropAccess.class); + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); + Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); + try { + aafLocatorObj = new DirectAAFLocator(env, ldao,"test","30.20.30.30"); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Result<List<Data>> retVal1 = new Result<List<Data>>(null,0,"",new Object[0]); + + Data data= new Data(); + data.major=30; + data.minor=30; + data.patch=30; + data.pkg=30; + retVal1.value = new ArrayList<Data>(); + retVal1.value.add(data); + + Mockito.doReturn(retVal1).when(ldao).readByName(trans,"test"); + boolean retVal = aafLocatorObj.refresh(); +// System.out.println(retVal); + assertTrue(retVal); + } + + @Test + public void testRefreshNOK() { + + DirectAAFLocator aafLocatorObj=null; + PropAccess access = Mockito.mock(PropAccess.class); + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); + Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); + try { + aafLocatorObj = new DirectAAFLocator(env, ldao,"test","30.20.30.30"); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Result<List<Data>> retVal1 = new Result<List<Data>>(null,1,"",new String[0]); + + Mockito.doReturn(retVal1).when(ldao).readByName(trans,"test"); + boolean retVal = aafLocatorObj.refresh(); +// System.out.println(retVal); + assertFalse(retVal); + } + }
\ No newline at end of file diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLur.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLur.java index f0f3c5d0..0ed6e60c 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLur.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFLur.java @@ -54,190 +54,190 @@ import org.onap.aaf.misc.env.Trans; @RunWith(MockitoJUnitRunner.class) public class JU_DirectAAFLur { - @Mock - AuthzEnv env; - - @Mock - Question question; - - @Mock - Principal bait; - - @Mock - Permission pond; - - @Mock - AuthzTrans trans; - - @Before - public void setUp() throws Exception { - initMocks(this); - Mockito.when(env.newTransNoAvg()).thenReturn(trans); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); - } - - public void testFish() { - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - - List<PermDAO.Data> rsVal = new ArrayList<PermDAO.Data>(); - Result<List<Data>> rs = new Result<List<Data>>(rsVal,0,"test",new Object[0]); - Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fish(bait, pond); - } + @Mock + AuthzEnv env; + + @Mock + Question question; + + @Mock + Principal bait; + + @Mock + Permission pond; + + @Mock + AuthzTrans trans; + + @Before + public void setUp() throws Exception { + initMocks(this); + Mockito.when(env.newTransNoAvg()).thenReturn(trans); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(trans).error(); + } + + public void testFish() { + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + + List<PermDAO.Data> rsVal = new ArrayList<PermDAO.Data>(); + Result<List<Data>> rs = new Result<List<Data>>(rsVal,0,"test",new Object[0]); + Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fish(bait, pond); + } - @Test - public void testFishSecondMtd() { - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - - List<PermDAO.Data> rsVal = new ArrayList<PermDAO.Data>(); - PermDAO.Data pd = new PermDAO.Data(); - pd.ns = "ns"; - pd.type = "name"; - pd.instance = null; - rsVal.add(pd); - pd = new PermDAO.Data(); - pd.ns = "ns"; - pd.type = "name"; - pd.instance = "instance"; - pd.action = null; - rsVal.add(pd); - - pd = new PermDAO.Data(); - pd.ns = "ns"; - pd.type = "name"; - pd.instance = "instance1"; - rsVal.add(pd); - pd = new PermDAO.Data(); - pd.ns = "ns1"; - pd.type = "name"; - rsVal.add(pd); - pd = new PermDAO.Data(); - pd.ns = "ns"; - pd.type = "name1"; - rsVal.add(pd); - - pd = new PermDAO.Data(); - pd.ns = "ns"; - pd.type = "name"; - pd.instance = "instance"; - pd.action = "action"; - rsVal.add(pd); - - pond = new DirectAAFLur.PermPermission("ns", "name", "instance", "action"); - - Result<List<Data>> rs = new Result<List<Data>>(rsVal,0,"test",new Object[0]); - Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fish(bait, pond); - - pond = new AAFPermission("ns", "name", "instance", "action"); - - Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fish(bait, pond); - - rs = new Result<List<Data>>(rsVal,1,"test",new Object[0]); - Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fish(bait, pond); - rs = new Result<List<Data>>(rsVal,4,"test",new Object[0]); - Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fish(bait, pond); - rs = new Result<List<Data>>(rsVal,25,"test",new Object[0]); - Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fish(bait, pond); - } - - @Test - public void testFishAll() { - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(env).error(); - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - - List<PermDAO.Data> rsVal = new ArrayList<PermDAO.Data>(); - PermDAO.Data pd = new PermDAO.Data(); - pd.ns = "ns"; - pd.type = "name"; - pd.instance = null; - rsVal.add(pd); - - pond = new DirectAAFLur.PermPermission("ns", "name", "instance", "action"); - List<Permission> permissions = new ArrayList<>(); - permissions.add(pond); - - Result<List<Data>> rs = new Result<List<Data>>(rsVal,0,"test",new Object[0]); - Mockito.when(question.getPermsByUser(env.newTrans(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fishAll(bait, permissions); - assertTrue(permissions.size() == 2); - - rs = new Result<List<Data>>(rsVal,1,"test",new Object[0]); - Mockito.when(question.getPermsByUser(env.newTrans(), bait.getName(), false)).thenReturn(rs); - aafLurObj.fishAll(bait, permissions); - } - - @Test - public void testDestroy() { - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - aafLurObj.destroy(); - } - - @Test - public void testHandlesExclusively() { - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - pond = new DirectAAFLur.PermPermission("ns", "name", "instance", "action"); - assertFalse(aafLurObj.handlesExclusively(pond)); - } - - @Test - public void testToString() { - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - assertTrue(aafLurObj.toString().contains("DirectAAFLur is enabled")); - } - - @Test - public void testHandles() { - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - assertTrue(aafLurObj.handles(null)); - } - - @Test - public void testCreatePerm() { - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - Permission retVal = aafLurObj.createPerm("test"); - assertTrue(retVal instanceof LocalPermission); - - NsSplit nss = new NsSplit("test", "test"); - Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); - Mockito.when(question.deriveNsSplit(NullTrans.singleton() , "test")).thenReturn(rs); - retVal = aafLurObj.createPerm("test|1|2"); - assertTrue(retVal instanceof PermPermission); - - rs = new Result<NsSplit>(null,1,"test",new Object[0]); - Mockito.when(question.deriveNsSplit(NullTrans.singleton() , "test")).thenReturn(rs); - retVal = aafLurObj.createPerm("test|1|2"); - assertTrue(retVal instanceof LocalPermission); - } - - @Test - public void testClear() { - AuthzTransImpl trans = Mockito.mock(AuthzTransImpl.class); - Mockito.when(env.newTrans()).thenReturn(trans); - DirectAAFLur aafLurObj = new DirectAAFLur(env, question); - StringBuilder sb = new StringBuilder(); - Mockito.when(trans.auditTrail(0, sb)).thenReturn(Mockito.mock(Trans.Metric.class)); - aafLurObj.clear(bait, sb); - } - - @Test - public void testPermPermission() { - AuthzTransImpl trans = Mockito.mock(AuthzTransImpl.class); - NsSplit nss = new NsSplit("test", "test"); - Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); - Mockito.when(question.deriveNsSplit(trans , "test")).thenReturn(rs); - PermPermission pp = new PermPermission(trans, question, "test|test|test|test"); - - assertTrue("test".equalsIgnoreCase(pp.getKey())); - assertTrue("AAFLUR".equalsIgnoreCase(pp.permType())); - - assertFalse(pp.match(null)); - - pond = new AAFPermission("test.test", "test", "test", "test"); - assertTrue(pp.match(pond)); - } + @Test + public void testFishSecondMtd() { + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + + List<PermDAO.Data> rsVal = new ArrayList<PermDAO.Data>(); + PermDAO.Data pd = new PermDAO.Data(); + pd.ns = "ns"; + pd.type = "name"; + pd.instance = null; + rsVal.add(pd); + pd = new PermDAO.Data(); + pd.ns = "ns"; + pd.type = "name"; + pd.instance = "instance"; + pd.action = null; + rsVal.add(pd); + + pd = new PermDAO.Data(); + pd.ns = "ns"; + pd.type = "name"; + pd.instance = "instance1"; + rsVal.add(pd); + pd = new PermDAO.Data(); + pd.ns = "ns1"; + pd.type = "name"; + rsVal.add(pd); + pd = new PermDAO.Data(); + pd.ns = "ns"; + pd.type = "name1"; + rsVal.add(pd); + + pd = new PermDAO.Data(); + pd.ns = "ns"; + pd.type = "name"; + pd.instance = "instance"; + pd.action = "action"; + rsVal.add(pd); + + pond = new DirectAAFLur.PermPermission("ns", "name", "instance", "action"); + + Result<List<Data>> rs = new Result<List<Data>>(rsVal,0,"test",new Object[0]); + Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fish(bait, pond); + + pond = new AAFPermission("ns", "name", "instance", "action"); + + Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fish(bait, pond); + + rs = new Result<List<Data>>(rsVal,1,"test",new Object[0]); + Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fish(bait, pond); + rs = new Result<List<Data>>(rsVal,4,"test",new Object[0]); + Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fish(bait, pond); + rs = new Result<List<Data>>(rsVal,25,"test",new Object[0]); + Mockito.when(question.getPermsByUser(env.newTransNoAvg(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fish(bait, pond); + } + + @Test + public void testFishAll() { + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(env).error(); + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + + List<PermDAO.Data> rsVal = new ArrayList<PermDAO.Data>(); + PermDAO.Data pd = new PermDAO.Data(); + pd.ns = "ns"; + pd.type = "name"; + pd.instance = null; + rsVal.add(pd); + + pond = new DirectAAFLur.PermPermission("ns", "name", "instance", "action"); + List<Permission> permissions = new ArrayList<>(); + permissions.add(pond); + + Result<List<Data>> rs = new Result<List<Data>>(rsVal,0,"test",new Object[0]); + Mockito.when(question.getPermsByUser(env.newTrans(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fishAll(bait, permissions); + assertTrue(permissions.size() == 2); + + rs = new Result<List<Data>>(rsVal,1,"test",new Object[0]); + Mockito.when(question.getPermsByUser(env.newTrans(), bait.getName(), false)).thenReturn(rs); + aafLurObj.fishAll(bait, permissions); + } + + @Test + public void testDestroy() { + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + aafLurObj.destroy(); + } + + @Test + public void testHandlesExclusively() { + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + pond = new DirectAAFLur.PermPermission("ns", "name", "instance", "action"); + assertFalse(aafLurObj.handlesExclusively(pond)); + } + + @Test + public void testToString() { + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + assertTrue(aafLurObj.toString().contains("DirectAAFLur is enabled")); + } + + @Test + public void testHandles() { + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + assertTrue(aafLurObj.handles(null)); + } + + @Test + public void testCreatePerm() { + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + Permission retVal = aafLurObj.createPerm("test"); + assertTrue(retVal instanceof LocalPermission); + + NsSplit nss = new NsSplit("test", "test"); + Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); + Mockito.when(question.deriveNsSplit(NullTrans.singleton() , "test")).thenReturn(rs); + retVal = aafLurObj.createPerm("test|1|2"); + assertTrue(retVal instanceof PermPermission); + + rs = new Result<NsSplit>(null,1,"test",new Object[0]); + Mockito.when(question.deriveNsSplit(NullTrans.singleton() , "test")).thenReturn(rs); + retVal = aafLurObj.createPerm("test|1|2"); + assertTrue(retVal instanceof LocalPermission); + } + + @Test + public void testClear() { + AuthzTransImpl trans = Mockito.mock(AuthzTransImpl.class); + Mockito.when(env.newTrans()).thenReturn(trans); + DirectAAFLur aafLurObj = new DirectAAFLur(env, question); + StringBuilder sb = new StringBuilder(); + Mockito.when(trans.auditTrail(0, sb)).thenReturn(Mockito.mock(Trans.Metric.class)); + aafLurObj.clear(bait, sb); + } + + @Test + public void testPermPermission() { + AuthzTransImpl trans = Mockito.mock(AuthzTransImpl.class); + NsSplit nss = new NsSplit("test", "test"); + Result<NsSplit> rs = new Result<NsSplit>(nss,0,"test",new Object[0]); + Mockito.when(question.deriveNsSplit(trans , "test")).thenReturn(rs); + PermPermission pp = new PermPermission(trans, question, "test|test|test|test"); + + assertTrue("test".equalsIgnoreCase(pp.getKey())); + assertTrue("AAFLUR".equalsIgnoreCase(pp.permType())); + + assertFalse(pp.match(null)); + + pond = new AAFPermission("test.test", "test", "test", "test"); + assertTrue(pp.match(pond)); + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFUserPass.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFUserPass.java index c767aeb5..241d407b 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFUserPass.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectAAFUserPass.java @@ -47,23 +47,23 @@ import org.onap.aaf.misc.env.LogTarget; @RunWith(MockitoJUnitRunner.class) public class JU_DirectAAFUserPass { - @Mock - Question question; - - @Mock - AuthzEnv env; - - @Mock - AuthzTrans trans; - - @Mock - HttpServletRequest request; - - - @Before - public void setUp() throws Exception { - initMocks(this); - when(env.warn()).thenReturn(new LogTarget() { + @Mock + Question question; + + @Mock + AuthzEnv env; + + @Mock + AuthzTrans trans; + + @Mock + HttpServletRequest request; + + + @Before + public void setUp() throws Exception { + initMocks(this); + when(env.warn()).thenReturn(new LogTarget() { @Override public void printf(String fmt, Object... vars) {} @@ -86,7 +86,7 @@ public class JU_DirectAAFUserPass { return true; } }); - when(env.error()).thenReturn(new LogTarget() { + when(env.error()).thenReturn(new LogTarget() { @Override public void printf(String fmt, Object... vars) {} @@ -109,115 +109,115 @@ public class JU_DirectAAFUserPass { return true; } }); - } - - @Test - public void testUserPass() { - - DirectAAFUserPass aafLocatorObj=null; - aafLocatorObj = new DirectAAFUserPass(env, question); - Result<Date> retVal1 = new Result<Date>(null,0,"",new String[0]); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - try { - Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); - } catch (DAOException e) { - e.printStackTrace(); - } - boolean retVal = aafLocatorObj.validate(null, null, null, null); - - assertFalse(retVal); - } - - @Test - public void testUserPassStateisRequest() { - - DirectAAFUserPass aafLocatorObj=null; - aafLocatorObj = new DirectAAFUserPass(env, question); - Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - try { - Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); - } catch (DAOException e) { - e.printStackTrace(); - } - boolean retVal = aafLocatorObj.validate(null, null, null, request); - -// System.out.println(retVal); - assertFalse(retVal); - } - - @Test - public void testUserPassStateNotNull() { - - DirectAAFUserPass aafLocatorObj=null; - aafLocatorObj = new DirectAAFUserPass(env, question); - Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - try { - Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); - } catch (DAOException e) { - e.printStackTrace(); - } - boolean retVal = aafLocatorObj.validate(null, null, null, "test"); - -// System.out.println(retVal); - assertFalse(retVal); - } - - @Test - public void testUserPassTransChk() { - - DirectAAFUserPass aafLocatorObj=null; - aafLocatorObj = new DirectAAFUserPass(env, question); - Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - try { - Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); - } catch (DAOException e) { - e.printStackTrace(); - } - boolean retVal = aafLocatorObj.validate(null, null, null, trans); - -// System.out.println(retVal); - assertFalse(retVal); - } - - @Test - public void testUserPassTransIpNotNull() { - - DirectAAFUserPass aafLocatorObj=null; - aafLocatorObj = new DirectAAFUserPass(env, question); - Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); - Mockito.doReturn("test").when(trans).ip(); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - try { - Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); - } catch (DAOException e) { - e.printStackTrace(); - } - boolean retVal = aafLocatorObj.validate(null, null, null, trans); - -// System.out.println(retVal); - assertFalse(retVal); - } - - @Test - public void testUserExceptionChk() { - - DirectAAFUserPass aafLocatorObj=null; - aafLocatorObj = new DirectAAFUserPass(env, question); - Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - try { - Mockito.doThrow(DAOException.class).when(question).doesUserCredMatch(trans, null, null); - } catch (DAOException e) { - // TODO Auto-generated catch block -// e.printStackTrace(); - } - boolean retVal = aafLocatorObj.validate(null, null, null, trans); - -// System.out.println(retVal); - assertFalse(retVal); - } - + } + + @Test + public void testUserPass() { + + DirectAAFUserPass aafLocatorObj=null; + aafLocatorObj = new DirectAAFUserPass(env, question); + Result<Date> retVal1 = new Result<Date>(null,0,"",new String[0]); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + try { + Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); + } catch (DAOException e) { + e.printStackTrace(); + } + boolean retVal = aafLocatorObj.validate(null, null, null, null); + + assertFalse(retVal); + } + + @Test + public void testUserPassStateisRequest() { + + DirectAAFUserPass aafLocatorObj=null; + aafLocatorObj = new DirectAAFUserPass(env, question); + Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + try { + Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); + } catch (DAOException e) { + e.printStackTrace(); + } + boolean retVal = aafLocatorObj.validate(null, null, null, request); + +// System.out.println(retVal); + assertFalse(retVal); + } + + @Test + public void testUserPassStateNotNull() { + + DirectAAFUserPass aafLocatorObj=null; + aafLocatorObj = new DirectAAFUserPass(env, question); + Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + try { + Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); + } catch (DAOException e) { + e.printStackTrace(); + } + boolean retVal = aafLocatorObj.validate(null, null, null, "test"); + +// System.out.println(retVal); + assertFalse(retVal); + } + + @Test + public void testUserPassTransChk() { + + DirectAAFUserPass aafLocatorObj=null; + aafLocatorObj = new DirectAAFUserPass(env, question); + Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + try { + Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); + } catch (DAOException e) { + e.printStackTrace(); + } + boolean retVal = aafLocatorObj.validate(null, null, null, trans); + +// System.out.println(retVal); + assertFalse(retVal); + } + + @Test + public void testUserPassTransIpNotNull() { + + DirectAAFUserPass aafLocatorObj=null; + aafLocatorObj = new DirectAAFUserPass(env, question); + Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); + Mockito.doReturn("test").when(trans).ip(); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + try { + Mockito.doReturn(retVal1).when(question).doesUserCredMatch(trans, null, null); + } catch (DAOException e) { + e.printStackTrace(); + } + boolean retVal = aafLocatorObj.validate(null, null, null, trans); + +// System.out.println(retVal); + assertFalse(retVal); + } + + @Test + public void testUserExceptionChk() { + + DirectAAFUserPass aafLocatorObj=null; + aafLocatorObj = new DirectAAFUserPass(env, question); + Result<Date> retVal1 = new Result<Date>(null,1,"",new String[0]); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + try { + Mockito.doThrow(DAOException.class).when(question).doesUserCredMatch(trans, null, null); + } catch (DAOException e) { + // TODO Auto-generated catch block +// e.printStackTrace(); + } + boolean retVal = aafLocatorObj.validate(null, null, null, trans); + +// System.out.println(retVal); + assertFalse(retVal); + } + }
\ No newline at end of file diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectCertIdentity.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectCertIdentity.java index 2f64e099..81195e5d 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectCertIdentity.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectCertIdentity.java @@ -48,53 +48,53 @@ import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) public class JU_DirectCertIdentity { - public DirectCertIdentity directCertIdentity; + public DirectCertIdentity directCertIdentity; - @Before - public void setUp() { - directCertIdentity = new DirectCertIdentity(); - } + @Before + public void setUp() { + directCertIdentity = new DirectCertIdentity(); + } - @Mock - HttpServletRequest req; - X509Certificate cert; - byte[] _certBytes; + @Mock + HttpServletRequest req; + X509Certificate cert; + byte[] _certBytes; - @Test - public void testidentity() { + @Test + public void testidentity() { - try { - Principal p = directCertIdentity.identity(req, cert, _certBytes); - assertEquals(((p) == null), true); - - cert = Mockito.mock(X509Certificate.class); - Mockito.when(cert.getEncoded()).thenReturn(new byte[128]); - - Result<List<CertDAO.Data>> rs = new Result<List<CertDAO.Data>>(null, 1, "test", new Object[0]); - - CachedCertDAO cacheDao = Mockito.mock(CachedCertDAO.class); - Mockito.when(cacheDao.read(Mockito.any(AuthzTrans.class),Mockito.any(Object[].class))).thenReturn(rs); - DirectCertIdentity.set(cacheDao); - p = directCertIdentity.identity(req, cert, _certBytes); - - _certBytes = new byte[128]; - List<CertDAO.Data> dataAL = new ArrayList<>(); - CertDAO.Data data = new CertDAO.Data(); - dataAL.add(data); - rs = new Result<List<CertDAO.Data>>(dataAL, 0, "test", new Object[0]); - Mockito.when(cacheDao.read(Mockito.any(AuthzTrans.class),Mockito.any(Object[].class))).thenReturn(rs); - DirectCertIdentity.set(cacheDao); - p = directCertIdentity.identity(req, cert, _certBytes); - assertTrue(p.toString().contains("X509 Authentication for null")); - - cert = null; - directCertIdentity.identity(req, cert, _certBytes); - } catch (CertificateException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // assertTrue(true); + try { + Principal p = directCertIdentity.identity(req, cert, _certBytes); + assertEquals(((p) == null), true); + + cert = Mockito.mock(X509Certificate.class); + Mockito.when(cert.getEncoded()).thenReturn(new byte[128]); + + Result<List<CertDAO.Data>> rs = new Result<List<CertDAO.Data>>(null, 1, "test", new Object[0]); + + CachedCertDAO cacheDao = Mockito.mock(CachedCertDAO.class); + Mockito.when(cacheDao.read(Mockito.any(AuthzTrans.class),Mockito.any(Object[].class))).thenReturn(rs); + DirectCertIdentity.set(cacheDao); + p = directCertIdentity.identity(req, cert, _certBytes); + + _certBytes = new byte[128]; + List<CertDAO.Data> dataAL = new ArrayList<>(); + CertDAO.Data data = new CertDAO.Data(); + dataAL.add(data); + rs = new Result<List<CertDAO.Data>>(dataAL, 0, "test", new Object[0]); + Mockito.when(cacheDao.read(Mockito.any(AuthzTrans.class),Mockito.any(Object[].class))).thenReturn(rs); + DirectCertIdentity.set(cacheDao); + p = directCertIdentity.identity(req, cert, _certBytes); + assertTrue(p.toString().contains("X509 Authentication for null")); + + cert = null; + directCertIdentity.identity(req, cert, _certBytes); + } catch (CertificateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // assertTrue(true); - } + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectLocatorCreator.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectLocatorCreator.java index 0eb75fcb..7ac4ed1b 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectLocatorCreator.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectLocatorCreator.java @@ -38,52 +38,52 @@ import org.onap.aaf.cadi.config.Config; @RunWith(MockitoJUnitRunner.class) public class JU_DirectLocatorCreator { - @Mock - AuthzEnv env; - - @Mock - LocateDAO locateDAO; - - @Mock - PropAccess access; - - @Before - public void setUp() throws Exception { - initMocks(this); - } - - @Test - public void testCreate() { - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); - Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); - Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); - DirectLocatorCreator directLocObj = new DirectLocatorCreator(env, locateDAO); - try { - directLocObj.create("test", "30.20.30.20"); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - directLocObj.setSelf("30.20.30.10", 8080); - try { - directLocObj.create("test", "30.20.30.20"); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @Mock + AuthzEnv env; + + @Mock + LocateDAO locateDAO; + + @Mock + PropAccess access; + + @Before + public void setUp() throws Exception { + initMocks(this); + } + + @Test + public void testCreate() { + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); + Mockito.doReturn("").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); + Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); + DirectLocatorCreator directLocObj = new DirectLocatorCreator(env, locateDAO); + try { + directLocObj.create("test", "30.20.30.20"); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + directLocObj.setSelf("30.20.30.10", 8080); + try { + directLocObj.create("test", "30.20.30.20"); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - @Test - public void testSetSelf() { - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); - Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); - Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); - DirectLocatorCreator directLocObj = new DirectLocatorCreator(env, locateDAO); - directLocObj.setSelf("30.20.30.10", 8080); - } + @Test + public void testSetSelf() { + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE,null); + Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER,""); + Mockito.doReturn("http://aafurl.com").when(access).getProperty(Config.AAF_URL,null); + DirectLocatorCreator directLocObj = new DirectLocatorCreator(env, locateDAO); + directLocObj.setSelf("30.20.30.10", 8080); + } } diff --git a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectRegistrar.java b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectRegistrar.java index f4bbd277..cf1bd9d4 100644 --- a/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectRegistrar.java +++ b/auth/auth-cass/src/test/java/org/onap/aaf/auth/direct/test/JU_DirectRegistrar.java @@ -41,73 +41,73 @@ import org.onap.aaf.cadi.config.Config; @RunWith(MockitoJUnitRunner.class) public class JU_DirectRegistrar { - @Mock - LocateDAO ldao; + @Mock + LocateDAO ldao; - // @Mock - // Data locate; + // @Mock + // Data locate; - @Mock - Access access; + @Mock + Access access; - @Mock - AuthzEnv env; + @Mock + AuthzEnv env; - // @Mock - AuthzTrans trans; + // @Mock + AuthzTrans trans; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void testUpdate() { - DirectRegistrar registrarObj = null; - org.onap.aaf.auth.layer.Result<Void> rs = null; - try { - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE, null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE, null); - Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER, ""); - Mockito.doReturn("20,test,test").when(access).getProperty(Config.AAF_LOCATOR_ENTRIES, ""); - rs = new org.onap.aaf.auth.layer.Result<Void>(null, 0, "test", new Object[0]); - Mockito.doReturn(rs).when(ldao).update(Mockito.any(), Mockito.any()); - registrarObj = new DirectRegistrar(access, ldao, 9080); + @Test + public void testUpdate() { + DirectRegistrar registrarObj = null; + org.onap.aaf.auth.layer.Result<Void> rs = null; + try { + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE, null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE, null); + Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER, ""); + Mockito.doReturn("20,test,test").when(access).getProperty(Config.AAF_LOCATOR_ENTRIES, ""); + rs = new org.onap.aaf.auth.layer.Result<Void>(null, 0, "test", new Object[0]); + Mockito.doReturn(rs).when(ldao).update(Mockito.any(), Mockito.any()); + registrarObj = new DirectRegistrar(access, ldao, 9080); - - org.onap.aaf.auth.layer.Result<Void> retVal1 = new Result<Void>(null, 0, "test", new Object[0]); - Mockito.doReturn(trans).when(env).newTransNoAvg(); - // Mockito.doReturn(retVal1).when(ldao).update(trans,locate); - registrarObj.update(env); - - rs = new org.onap.aaf.auth.layer.Result<Void>(null, 1, "test", new Object[0]); - Mockito.doReturn(rs).when(ldao).update(Mockito.any(), Mockito.any()); - registrarObj = new DirectRegistrar(access, ldao, 9080); - registrarObj.update(env); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - // System.out.println(retVal1); - } + + org.onap.aaf.auth.layer.Result<Void> retVal1 = new Result<Void>(null, 0, "test", new Object[0]); + Mockito.doReturn(trans).when(env).newTransNoAvg(); + // Mockito.doReturn(retVal1).when(ldao).update(trans,locate); + registrarObj.update(env); + + rs = new org.onap.aaf.auth.layer.Result<Void>(null, 1, "test", new Object[0]); + Mockito.doReturn(rs).when(ldao).update(Mockito.any(), Mockito.any()); + registrarObj = new DirectRegistrar(access, ldao, 9080); + registrarObj.update(env); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + // System.out.println(retVal1); + } - @Test - public void testCancel() { - DirectRegistrar registrarObj = null; - try { - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE, null); - Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE, null); - Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER, ""); - Mockito.doReturn("20,test,test").when(access).getProperty(Config.AAF_LOCATOR_ENTRIES, ""); - registrarObj = new DirectRegistrar(access, ldao, 9080); - - org.onap.aaf.auth.layer.Result<Void> rs = new org.onap.aaf.auth.layer.Result<Void>(null, 1, "test", new Object[0]); - Mockito.doReturn(rs).when(ldao).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); - } catch (CadiException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - registrarObj.cancel(env); - } + @Test + public void testCancel() { + DirectRegistrar registrarObj = null; + try { + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LATITUDE, null); + Mockito.doReturn("20").when(access).getProperty(Config.CADI_LONGITUDE, null); + Mockito.doReturn("20").when(access).getProperty(Config.AAF_LOCATOR_CONTAINER, ""); + Mockito.doReturn("20,test,test").when(access).getProperty(Config.AAF_LOCATOR_ENTRIES, ""); + registrarObj = new DirectRegistrar(access, ldao, 9080); + + org.onap.aaf.auth.layer.Result<Void> rs = new org.onap.aaf.auth.layer.Result<Void>(null, 1, "test", new Object[0]); + Mockito.doReturn(rs).when(ldao).delete(Mockito.any(), Mockito.any(), Mockito.anyBoolean()); + } catch (CadiException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + registrarObj.cancel(env); + } }
\ No newline at end of file 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 aa5c1daf..cf912fa4 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 @@ -73,7 +73,7 @@ import com.datastax.driver.core.Cluster; public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { private static final String USER_PERMS = "userPerms"; - private static final String CM_ALLOW_TMP = "cm_allow_tmp"; + private static final String CM_ALLOW_TMP = "cm_allow_tmp"; private static final Map<String,CA> certAuths = new TreeMap<>(); public static Facade1_0 facade1_0; // this is the default Facade public static Facade1_0 facade1_0_XML; // this is the XML Facade @@ -87,7 +87,7 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { //Added for junits public CMService getService() { - return null; + return null; } /** * Construct AuthzAPI with all the Context Supporting Routes that Authz needs @@ -112,7 +112,7 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { // Check for allowing /tmp in Properties String allowTmp = env.getProperty(CM_ALLOW_TMP); if("true".equalsIgnoreCase(allowTmp)) { - CertmanValidator.allowTmp(); + CertmanValidator.allowTmp(); } @@ -150,10 +150,10 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { pinst[2]= aafEnv; pinst[3] = multiParams; try { - CA ca = cons.newInstance(pinst); + CA ca = cons.newInstance(pinst); certAuths.put(ca.getName(),ca); } catch (InvocationTargetException e) { - access.log(e, "Loading", segs[0]); + access.log(e, "Loading", segs[0]); } } } @@ -165,7 +165,7 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { service = getService(); if(service == null) { - service = new CMService(trans, this); + service = new CMService(trans, this); } // note: Service knows how to shutdown Cluster on Shutdown, etc. See Constructor facade1_0 = FacadeFactory.v1_0(this,trans, service,Data.TYPE.JSON); // Default Facade @@ -254,14 +254,14 @@ public class AAF_CM extends AbsService<AuthzEnv, AuthzTrans> { Log4JLogIt logIt = new Log4JLogIt(args, "cm"); PropAccess propAccess = new PropAccess(logIt,args); try { - new JettyServiceStarter<AuthzEnv,AuthzTrans>( - new AAF_CM(new AuthzEnv(propAccess)),true) - .start(); - } catch (Exception e) { - propAccess.log(e); - } + new JettyServiceStarter<AuthzEnv,AuthzTrans>( + new AAF_CM(new AuthzEnv(propAccess)),true) + .start(); + } catch (Exception e) { + propAccess.log(e); + } } catch (APIException e) { - e.printStackTrace(System.err); + e.printStackTrace(System.err); } } } diff --git a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/LocalCAImpl.java b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/LocalCAImpl.java index 632e719e..d32b67a3 100644 --- a/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/LocalCAImpl.java +++ b/auth/auth-certman/src/main/java/org/onap/aaf/auth/cm/LocalCAImpl.java @@ -31,18 +31,18 @@ import org.onap.aaf.misc.env.Trans; public class LocalCAImpl extends CA { - protected LocalCAImpl(Access access, String caName, String env) throws IOException, CertException { - super(access, caName, env); - // TODO Auto-generated constructor stub - } - - public LocalCAImpl(Access access, final String name, final String env, final String[][] params) throws IOException, CertException { - super(access, name, env); - } + protected LocalCAImpl(Access access, String caName, String env) throws IOException, CertException { + super(access, caName, env); + // TODO Auto-generated constructor stub + } + + public LocalCAImpl(Access access, final String name, final String env, final String[][] params) throws IOException, CertException { + super(access, name, env); + } - @Override - public X509andChain sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException { - // TODO Auto-generated method stub - return null; - } + @Override + public X509andChain sign(Trans trans, CSRMeta csrmeta) throws IOException, CertException { + // TODO Auto-generated method stub + return null; + } }
\ No newline at end of file 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 26b4e2aa..ab304629 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 @@ -72,7 +72,7 @@ public abstract class CA { this.name = caName; this.env = env; this.env_tag = env==null || env.isEmpty()?false: - Boolean.parseBoolean(access.getProperty(CM_CA_ENV_TAG, Boolean.FALSE.toString())); + Boolean.parseBoolean(access.getProperty(CM_CA_ENV_TAG, Boolean.FALSE.toString())); permNS=null; String prefix = CM_CA_PREFIX + name; permType = access.getProperty(prefix + ".perm_type",null); @@ -195,7 +195,7 @@ public abstract class CA { } public boolean shouldAddEnvTag() { - return env_tag; + return env_tag; } public String getEnv() { 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 22243ae4..82639e21 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 @@ -223,10 +223,10 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { data.mechid = trim(arti.getMechid()); data.machine = trim(arti.getMachine()); if(arti.getType()!=null) { - Set<String> ss = data.type(true); - for(String t : arti.getType()) { - ss.add(trim(t)); - } + Set<String> ss = data.type(true); + for(String t : arti.getType()) { + ss.add(trim(t)); + } } data.ca = trim(arti.getCa()); data.dir = trim(arti.getDir()); @@ -240,9 +240,9 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { data.sponsor = (arti.getSponsor()); if(arti.getSans()!=null) { Set<String> ls = data.sans(true); - for(String t : arti.getSans()) { - ls.add(trim(t)); - } + for(String t : arti.getSans()) { + ls.add(trim(t)); + } } data.expires = null; ladd.add(data); @@ -266,13 +266,13 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { a.setCa(trim(arti.ca)); a.setDir(trim(arti.dir)); for(String t : arti.type(false)) { - a.getType().add(trim(t)); + a.getType().add(trim(t)); } a.setOsUser(trim(arti.os_user)); a.setRenewDays(arti.renewDays); a.setNotification(trim(arti.notify)); for(String t : arti.sans(false)) { - a.getSans().add(trim(t)); + a.getSans().add(trim(t)); } artis.getArtifact().add(a); } @@ -285,10 +285,10 @@ public class Mapper1_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { private String trim(String s) { - if(s==null) { - return s; - } else { - return s.trim(); - } - } + if(s==null) { + return s; + } else { + return s.trim(); + } + } }
\ No newline at end of file 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 53388f67..283c828a 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 @@ -212,9 +212,9 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { data.machine = trim(arti.getMachine()); if(arti.getType()!=null) { Set<String> ss = data.type(true); - for(String t : arti.getType()) { - ss.add(t.trim()); - } + for(String t : arti.getType()) { + ss.add(t.trim()); + } } data.type(true).addAll(arti.getType()); data.ca = trim(arti.getCa()); @@ -231,7 +231,7 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { if(arti.getSans()!=null) { Set<String> ss = data.sans(true); for(String s : arti.getSans()) { - ss.add(s.trim()); + ss.add(s.trim()); } } ladd.add(data); @@ -240,14 +240,14 @@ public class Mapper2_0 implements Mapper<BaseRequest,CertInfo,Artifacts,Error> { } private String trim(String s) { - if(s==null) { - return s; - } else { - return s.trim(); - } - } + if(s==null) { + return s; + } else { + return s.trim(); + } + } - /* (non-Javadoc) + /* (non-Javadoc) * @see org.onap.aaf.auth.cm.mapper.Mapper#fromArtifacts(org.onap.aaf.auth.layer.test.Result) */ @Override 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 26b3a22a..48fe8d81 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 @@ -89,8 +89,8 @@ public class CMService { private final CredDAO credDAO; private final ArtiDAO artiDAO; private AAF_CM certManager; - private Boolean allowIgnoreIPs; - private Boolean alwaysIgnoreIPs; + private Boolean allowIgnoreIPs; + private Boolean alwaysIgnoreIPs; // @SuppressWarnings("unchecked") public CMService(final AuthzTrans trans, AAF_CM certman) throws APIException, IOException { @@ -113,12 +113,12 @@ public class CMService { ); alwaysIgnoreIPs = Boolean.valueOf(certman.access.getProperty(Config.CM_ALWAYS_IGNORE_IPS, "false")); if(alwaysIgnoreIPs) { - trans.env().access().log(Level.INIT, "DNS Evaluation for Cert Creation is turned off with " + Config.CM_ALWAYS_IGNORE_IPS ); + trans.env().access().log(Level.INIT, "DNS Evaluation for Cert Creation is turned off with " + Config.CM_ALWAYS_IGNORE_IPS ); } else { - allowIgnoreIPs = Boolean.valueOf(certman.access.getProperty(Config.CM_ALLOW_IGNORE_IPS, "false")); - if(allowIgnoreIPs) { - trans.env().access().log(Level.INIT, "Allowing DNS Evaluation to be turned off with <ns>.certman|<ca name>|"+IGNORE_IPS); - } + allowIgnoreIPs = Boolean.valueOf(certman.access.getProperty(Config.CM_ALLOW_IGNORE_IPS, "false")); + if(allowIgnoreIPs) { + trans.env().access().log(Level.INIT, "Allowing DNS Evaluation to be turned off with <ns>.certman|<ca name>|"+IGNORE_IPS); + } } } @@ -147,11 +147,11 @@ public class CMService { boolean ignoreIPs; if(alwaysIgnoreIPs) { - ignoreIPs=true; + ignoreIPs=true; } else if(allowIgnoreIPs) { - ignoreIPs = trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), IGNORE_IPS)); + ignoreIPs = trans.fish(new AAFPermission(mechNS,CERTMAN, ca.getName(), IGNORE_IPS)); } else { - ignoreIPs = false; + ignoreIPs = false; } @@ -185,7 +185,7 @@ public class CMService { } else { if (!ignoreIPs) { - for (String cn : req.value.fqdns) { + for (String cn : req.value.fqdns) { try { InetAddress[] ias = InetAddress.getAllByName(cn); Set<String> potentialSanNames = new HashSet<>(); 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 5835b31f..cdd501ce 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 @@ -48,13 +48,13 @@ public class CertmanValidator extends Validator{ private static final String MUST_HAVE_AT_LEAST = " must have at least "; private static final String IS_NULL = " is null."; private static final String ARTIFACTS_MUST_HAVE_AT_LEAST = "Artifacts must have at least "; - private static final Pattern ALPHA_NUM = Pattern.compile("[a-zA-Z0-9]*"); - - private static boolean disallowTmp = true; - public static void allowTmp() { - disallowTmp=false; - } - + private static final Pattern ALPHA_NUM = Pattern.compile("[a-zA-Z0-9]*"); + + private static boolean disallowTmp = true; + public static void allowTmp() { + disallowTmp=false; + } + public CertmanValidator nullBlankMin(String name, List<String> list, int min) { if (list==null) { msg(name + IS_NULL); @@ -80,7 +80,7 @@ public class CertmanValidator extends Validator{ for (ArtiDAO.Data a : list) { allRequired(a); if(disallowTmp && a.dir!=null && a.dir.startsWith("/tmp")) { - msg("Certificates may not be deployed into /tmp directory (they will be removed at a random time by O/S)"); + msg("Certificates may not be deployed into /tmp directory (they will be removed at a random time by O/S)"); } } } @@ -106,7 +106,7 @@ public class CertmanValidator extends Validator{ nullOrBlank(MACHINE, a.machine); nullOrBlank("ca",a.ca); nullOrBlank("dir",a.dir); - match("NS must be dot separated AlphaNumeric",a.ns,NAME_CHARS); + match("NS must be dot separated AlphaNumeric",a.ns,NAME_CHARS); match("O/S User must be AlphaNumeric",a.os_user,ALPHA_NUM); // Note: AppName, Notify & Sponsor are currently not required } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/JU_AAF_CM.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/JU_AAF_CM.java index 1bee730a..9f7497e0 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/JU_AAF_CM.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/JU_AAF_CM.java @@ -63,163 +63,163 @@ import org.powermock.modules.junit4.PowerMockRunner; @PrepareForTest(FacadeFactory.class) public class JU_AAF_CM { - @Mock - AuthzEnv env; - - BasicEnv baseEnv; - - @Mock - PropAccess access; - - AuthzTransImpl1 trans; - - AAF_CMImpl rosettaObj = null; - - @Before - public void setUp() { - initMocks(this); - - try { - Mockito.doReturn(access).when(env).access(); - Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); - Properties props=new Properties(); - Mockito.doReturn(props).when(access).getProperties(); - props.setProperty("cm_ca.props", "test"); - Mockito.doReturn("test:2.1").when(access).getProperty(Config.AAF_LOCATOR_ENTRIES, null); - Mockito.doReturn("test").when(access).getProperty("https.protocols","TLSv1.1,TLSv1.2"); - Mockito.doReturn("test").when(env).getProperty("cm_ca.props.perm_type",null); - Mockito.doReturn("test").when(env).getProperty("cm_ca.props.baseSubject",null); - Mockito.doReturn("10").when(env).getProperty("CACHE_CLEAN_INTERVAL","60000"); - Mockito.doReturn("10").when(env).getProperty("CACHE_HIGH_COUNT","5000"); - trans = new AuthzTransImpl1(env); - Mockito.doReturn(trans).when(env).newTrans(); -// Mockito.doReturn("test").when(trans).getProperty("cm_ca.props.baseSubject",null); -// Mockito.doReturn(Mockito.mock(TimeTaken.class)).when(trans).start("Clear Reset Deque",8); - - Mockito.doReturn("TLSv1.1").when(access).getProperty("cadi_protocols","test"); - Mockito.doReturn("https://www.google.com").when(access).getProperty(Config.AAF_URL,null); - Mockito.doReturn("test").when(env).getProperty(Config.AAF_ENV); - Mockito.doReturn("10").when(env).getProperty(Config.CADI_LATITUDE); - Mockito.doReturn("10").when(env).getProperty(Config.CADI_LONGITUDE); - Mockito.doReturn("org.onap.aaf.auth.cm.LocalCAImpl,test;test").when(env).getProperty("cm_ca.props"); - Mockito.doReturn("google.com").when(env).getProperty("cassandra.clusters",null); -// Mockito.doReturn(Mockito.mock(AuthzTransImpl.class)).when(env).newTrans(); - Mockito.doReturn(Mockito.mock(LogTarget.class)).when(env).init(); - AAF_CM tempObj = Mockito.mock(AAF_CM.class); - Field envField = tempObj.getClass().getField("env"); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(envField, envField.getModifiers() & ~Modifier.FINAL); - envField.setAccessible(true); - envField.set(tempObj, env); - RosettaDF rosettaObjTemp = Mockito.mock(RosettaDF.class); - Mockito.doReturn(rosettaObjTemp).when(rosettaObjTemp).in(Data.TYPE.JSON); - Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(aaf.v2_0.Error.class); - Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertificateRequest.class); - Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertificateRenew.class); - Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertificateDrop.class); - Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertInfo.class); - Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.Artifacts.class); - Mockito.doReturn(Data.TYPE.XML).when(rosettaObjTemp).getOutType(); + @Mock + AuthzEnv env; + + BasicEnv baseEnv; + + @Mock + PropAccess access; + + AuthzTransImpl1 trans; + + AAF_CMImpl rosettaObj = null; + + @Before + public void setUp() { + initMocks(this); + + try { + Mockito.doReturn(access).when(env).access(); + Mockito.doReturn("test.test").when(access).getProperty(Config.AAF_ROOT_NS,"org.osaaf.aaf"); + Properties props=new Properties(); + Mockito.doReturn(props).when(access).getProperties(); + props.setProperty("cm_ca.props", "test"); + Mockito.doReturn("test:2.1").when(access).getProperty(Config.AAF_LOCATOR_ENTRIES, null); + Mockito.doReturn("test").when(access).getProperty("https.protocols","TLSv1.1,TLSv1.2"); + Mockito.doReturn("test").when(env).getProperty("cm_ca.props.perm_type",null); + Mockito.doReturn("test").when(env).getProperty("cm_ca.props.baseSubject",null); + Mockito.doReturn("10").when(env).getProperty("CACHE_CLEAN_INTERVAL","60000"); + Mockito.doReturn("10").when(env).getProperty("CACHE_HIGH_COUNT","5000"); + trans = new AuthzTransImpl1(env); + Mockito.doReturn(trans).when(env).newTrans(); +// Mockito.doReturn("test").when(trans).getProperty("cm_ca.props.baseSubject",null); +// Mockito.doReturn(Mockito.mock(TimeTaken.class)).when(trans).start("Clear Reset Deque",8); + + Mockito.doReturn("TLSv1.1").when(access).getProperty("cadi_protocols","test"); + Mockito.doReturn("https://www.google.com").when(access).getProperty(Config.AAF_URL,null); + Mockito.doReturn("test").when(env).getProperty(Config.AAF_ENV); + Mockito.doReturn("10").when(env).getProperty(Config.CADI_LATITUDE); + Mockito.doReturn("10").when(env).getProperty(Config.CADI_LONGITUDE); + Mockito.doReturn("org.onap.aaf.auth.cm.LocalCAImpl,test;test").when(env).getProperty("cm_ca.props"); + Mockito.doReturn("google.com").when(env).getProperty("cassandra.clusters",null); +// Mockito.doReturn(Mockito.mock(AuthzTransImpl.class)).when(env).newTrans(); + Mockito.doReturn(Mockito.mock(LogTarget.class)).when(env).init(); + AAF_CM tempObj = Mockito.mock(AAF_CM.class); + Field envField = tempObj.getClass().getField("env"); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(envField, envField.getModifiers() & ~Modifier.FINAL); + envField.setAccessible(true); + envField.set(tempObj, env); + RosettaDF rosettaObjTemp = Mockito.mock(RosettaDF.class); + Mockito.doReturn(rosettaObjTemp).when(rosettaObjTemp).in(Data.TYPE.JSON); + Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(aaf.v2_0.Error.class); + Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertificateRequest.class); + Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertificateRenew.class); + Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertificateDrop.class); + Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.CertInfo.class); + Mockito.doReturn(rosettaObjTemp).when(env).newDataFactory(certman.v1_0.Artifacts.class); + Mockito.doReturn(Data.TYPE.XML).when(rosettaObjTemp).getOutType(); - Facade1_0 facadeObj = Mockito.mock(Facade1_0.class); - PowerMockito.mockStatic(FacadeFactory.class); - FacadeFactory factObj = PowerMockito.mock(FacadeFactory.class); - PowerMockito.when(factObj.v1_0(tempObj,trans, null,Data.TYPE.JSON)).thenReturn(facadeObj); - -// Mockito.doReturn(Mockito.mock(Mapper.class)).when(facadeObj).mapper(); + Facade1_0 facadeObj = Mockito.mock(Facade1_0.class); + PowerMockito.mockStatic(FacadeFactory.class); + FacadeFactory factObj = PowerMockito.mock(FacadeFactory.class); + PowerMockito.when(factObj.v1_0(tempObj,trans, null,Data.TYPE.JSON)).thenReturn(facadeObj); + +// Mockito.doReturn(Mockito.mock(Mapper.class)).when(facadeObj).mapper(); - - rosettaObj = new AAF_CMImpl(env); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - assertTrue(e instanceof NullPointerException); - } - } - - @Test - public void testTestCA() { - CA obj = rosettaObj.getCA("props"); - assertTrue(obj instanceof CA); - } - -// @Test -// public void testRoute() { -// try { -// rosettaObj.route(null, "", null, null); -// } catch (Exception e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); -// } -//// System.out.println(obj); -//// assertTrue(obj instanceof CA); -// } - - @Test - public void testFilters() { - try { - Filter[] obj = rosettaObj._filters(new Object[] {"props"}); - System.out.println(obj); - } catch (CadiException | LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - assertTrue(e.getMessage().contains("Error initializing Context: TLS")); - } -// assertTrue(obj instanceof CA); - } - - class AAF_CMImpl extends AAF_CM{ + + rosettaObj = new AAF_CMImpl(env); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertTrue(e instanceof NullPointerException); + } + } + + @Test + public void testTestCA() { + CA obj = rosettaObj.getCA("props"); + assertTrue(obj instanceof CA); + } + +// @Test +// public void testRoute() { +// try { +// rosettaObj.route(null, "", null, null); +// } catch (Exception e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } +//// System.out.println(obj); +//// assertTrue(obj instanceof CA); +// } + + @Test + public void testFilters() { + try { + Filter[] obj = rosettaObj._filters(new Object[] {"props"}); + System.out.println(obj); + } catch (CadiException | LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertTrue(e.getMessage().contains("Error initializing Context: TLS")); + } +// assertTrue(obj instanceof CA); + } + + class AAF_CMImpl extends AAF_CM{ - public AAF_CMImpl(AuthzEnv env) throws Exception { - super(env); - // TODO Auto-generated constructor stub - } - - @Override - public synchronized AAFConHttp aafCon() throws CadiException, LocatorException { - return Mockito.mock(AAFConHttp.class); - } - - public CMService getService() { - return Mockito.mock(CMService.class); - } - - @Override - public void route(HttpMethods meth, String path, API api, Code code) throws Exception { - - } - } - - - - class AuthzTransImpl1 extends AuthzTransImpl{ + public AAF_CMImpl(AuthzEnv env) throws Exception { + super(env); + // TODO Auto-generated constructor stub + } + + @Override + public synchronized AAFConHttp aafCon() throws CadiException, LocatorException { + return Mockito.mock(AAFConHttp.class); + } + + public CMService getService() { + return Mockito.mock(CMService.class); + } + + @Override + public void route(HttpMethods meth, String path, API api, Code code) throws Exception { + + } + } + + + + class AuthzTransImpl1 extends AuthzTransImpl{ - public AuthzTransImpl1(AuthzEnv env) { - super(env); - // TODO Auto-generated constructor stub - } + public AuthzTransImpl1(AuthzEnv env) { + super(env); + // TODO Auto-generated constructor stub + } - @Override - protected TimeTaken newTimeTaken(String name, int flag, Object ... values) { - // TODO Auto-generated method stub - TimeTaken tt= new TimeTaken("nameTest", Env.XML) { - - @Override - public void output(StringBuilder sb) { - // TODO Auto-generated method stub - - } - }; - return tt; - } - - @Override - public Metric auditTrail(int indent, StringBuilder sb, int ... flag) { - return null; - } - - } - + @Override + protected TimeTaken newTimeTaken(String name, int flag, Object ... values) { + // TODO Auto-generated method stub + TimeTaken tt= new TimeTaken("nameTest", Env.XML) { + + @Override + public void output(StringBuilder sb) { + // TODO Auto-generated method stub + + } + }; + return tt; + } + + @Override + public Metric auditTrail(int indent, StringBuilder sb, int ... flag) { + return null; + } + + } + } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/api/JU_API_Artifact.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/api/JU_API_Artifact.java index 4ef85aa2..31ee0727 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/api/JU_API_Artifact.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/api/JU_API_Artifact.java @@ -69,7 +69,7 @@ public class JU_API_Artifact { @Test public void placeholder() { - Assert.assertTrue(true); + Assert.assertTrue(true); } /* diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainTest.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainTest.java index 06ea9e6e..4c6f7585 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainTest.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainTest.java @@ -39,34 +39,34 @@ import org.onap.aaf.cadi.configure.CertException; public class JU_X509ChainTest { - @Mock - X509Certificate x509; + @Mock + X509Certificate x509; - @Mock - X509ChainWithIssuer orig; - @Mock - Principal subject; - @Mock - Reader reader; - @Mock - X509Certificate cert; + @Mock + X509ChainWithIssuer orig; + @Mock + Principal subject; + @Mock + Reader reader; + @Mock + X509Certificate cert; - @Before - public void setUp() throws Exception { - initMocks(this); - // when(subject.get) - // when(x509.getSubjectDN()).thenReturn(subject); - when(cert.getEncoded()).thenReturn("x509".getBytes()); - } + @Before + public void setUp() throws Exception { + initMocks(this); + // when(subject.get) + // when(x509.getSubjectDN()).thenReturn(subject); + when(cert.getEncoded()).thenReturn("x509".getBytes()); + } - @Test - public void test() throws IOException, CertException { - Certificate[] certs = { x509 }; - X509andChain x509Chain = new X509andChain(cert, new ArrayList<String>()); - x509Chain.addTrustChainEntry(cert); + @Test + public void test() throws IOException, CertException { + Certificate[] certs = { x509 }; + X509andChain x509Chain = new X509andChain(cert, new ArrayList<String>()); + x509Chain.addTrustChainEntry(cert); - assertNotNull(x509Chain.getX509()); - assertEquals(2, x509Chain.getTrustChain().length); - } + assertNotNull(x509Chain.getX509()); + assertEquals(2, x509Chain.getTrustChain().length); + } } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainWithIssuerTest.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainWithIssuerTest.java index 7b6afce7..dbae3fcd 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainWithIssuerTest.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/ca/JU_X509ChainWithIssuerTest.java @@ -39,36 +39,36 @@ import org.onap.aaf.cadi.configure.CertException; public class JU_X509ChainWithIssuerTest { - @Mock - X509Certificate x509; + @Mock + X509Certificate x509; - @Mock - X509ChainWithIssuer orig; - @Mock - Principal subject; - @Mock - Reader reader; + @Mock + X509ChainWithIssuer orig; + @Mock + Principal subject; + @Mock + Reader reader; - @Before - public void setUp() throws Exception { - initMocks(this); - // when(subject.get) - when(x509.getSubjectDN()).thenReturn(subject); - when(x509.getEncoded()).thenReturn("x509".getBytes()); - } + @Before + public void setUp() throws Exception { + initMocks(this); + // when(subject.get) + when(x509.getSubjectDN()).thenReturn(subject); + when(x509.getEncoded()).thenReturn("x509".getBytes()); + } - @Test - public void test() throws IOException, CertException { - X509ChainWithIssuer x509Chain = new X509ChainWithIssuer(orig, x509); + @Test + public void test() throws IOException, CertException { + X509ChainWithIssuer x509Chain = new X509ChainWithIssuer(orig, x509); - assertNull(x509Chain.getIssuerDN()); - Certificate[] certs = { x509 }; - // Certificate cert = ; - x509Chain = new X509ChainWithIssuer(certs); - List<Reader> rdrs = new ArrayList<Reader>(); - rdrs.add(null); + assertNull(x509Chain.getIssuerDN()); + Certificate[] certs = { x509 }; + // Certificate cert = ; + x509Chain = new X509ChainWithIssuer(certs); + List<Reader> rdrs = new ArrayList<Reader>(); + rdrs.add(null); - x509Chain = new X509ChainWithIssuer(rdrs); - } + x509Chain = new X509ChainWithIssuer(rdrs); + } } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertReqTest.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertReqTest.java index 1ab26531..8b33036f 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertReqTest.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertReqTest.java @@ -37,26 +37,26 @@ import org.onap.aaf.cadi.configure.CertException; public class JU_CertReqTest { - @Mock - CA ca; - - @Mock - CSRMeta csr; - - @Before - public void setUp() throws Exception { - initMocks(this); - when(ca.newCSRMeta()).thenReturn(csr); - when(csr.cn()).thenReturn("cn123"); - when(csr.mechID()).thenReturn("mechId"); - } - - @Test - public void testCertResp() throws IOException, GeneralSecurityException, CertException { - CertReq req = new CertReq(); - req.certAuthority = ca; - req.fqdns = new ArrayList<String>(); - - assertEquals(csr, req.getCSRMeta()); - } + @Mock + CA ca; + + @Mock + CSRMeta csr; + + @Before + public void setUp() throws Exception { + initMocks(this); + when(ca.newCSRMeta()).thenReturn(csr); + when(csr.cn()).thenReturn("cn123"); + when(csr.mechID()).thenReturn("mechId"); + } + + @Test + public void testCertResp() throws IOException, GeneralSecurityException, CertException { + CertReq req = new CertReq(); + req.certAuthority = ca; + req.fqdns = new ArrayList<String>(); + + assertEquals(csr, req.getCSRMeta()); + } } diff --git a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertRespTest.java b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertRespTest.java index 1366e706..37519a30 100644 --- a/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertRespTest.java +++ b/auth/auth-certman/src/test/java/org/onap/aaf/auth/cm/data/JU_CertRespTest.java @@ -43,98 +43,98 @@ import org.onap.aaf.misc.env.Trans; public class JU_CertRespTest { - @Mock - CSRMeta csrMeta; - - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - Trans trans; - - @Mock - X509Certificate x509; - - @Mock - CA ca; - - @Before - public void setUp() throws Exception { - initMocks(this); - CertDrop drop = new CertDrop(); - CertRenew renew = new CertRenew(); - - PublicKey publicKey = new PublicKey() { - - @Override - public String getFormat() { - // TODO Auto-generated method stub - return null; - } - - @Override - public byte[] getEncoded() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getAlgorithm() { - // TODO Auto-generated method stub - return null; - } - }; - PrivateKey privateKey = new PrivateKey() { - - @Override - public String getFormat() { - // TODO Auto-generated method stub - return null; - } - - @Override - public byte[] getEncoded() { - // TODO Auto-generated method stub - return "privatekey".getBytes(); - } - - @Override - public String getAlgorithm() { - // TODO Auto-generated method stub - return null; - } - }; - KeyPair keypair = new KeyPair(publicKey, privateKey); - - when(csrMeta.keypair(trans)).thenReturn(keypair); - when(csrMeta.challenge()).thenReturn("challenge"); - when(x509.getSubjectDN()).thenReturn(null); - when(x509.getEncoded()).thenReturn("x509Certificate".getBytes()); - - } - - @Test - public void testCertResp() throws IOException, GeneralSecurityException, CertException { - CertResp resp = new CertResp("CERT"); - - assertEquals("CERT", resp.asCertString()); - assertEquals("", resp.challenge()); - - String[] trustChain = { "trustChain" }; - String[] notes = { "notes" }; - - String[] caIssureDNs = { "caIssuer" }; - String[] trustedCAs = { "trustedCAs" }; - - when(ca.getCaIssuerDNs()).thenReturn(caIssureDNs); - when(ca.getEnv()).thenReturn("Env"); - when(ca.getTrustedCAs()).thenReturn(trustedCAs); - - resp = new CertResp(trans, ca, x509, csrMeta, trustChain, notes); - - assertNotNull(resp.privateString()); - assertEquals("challenge", resp.challenge()); - assertEquals("notes", resp.notes()[0]); - assertEquals("trustChain", resp.trustChain()[0]); - assertEquals("caIssuer", resp.caIssuerDNs()[0]); - assertEquals("trustedCAs", resp.trustCAs()[0]); - assertEquals("Env", resp.env()); - } + @Mock + CSRMeta csrMeta; + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + Trans trans; + + @Mock + X509Certificate x509; + + @Mock + CA ca; + + @Before + public void setUp() throws Exception { + initMocks(this); + CertDrop drop = new CertDrop(); + CertRenew renew = new CertRenew(); + + PublicKey publicKey = new PublicKey() { + + @Override + public String getFormat() { + // TODO Auto-generated method stub + return null; + } + + @Override + public byte[] getEncoded() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getAlgorithm() { + // TODO Auto-generated method stub + return null; + } + }; + PrivateKey privateKey = new PrivateKey() { + + @Override + public String getFormat() { + // TODO Auto-generated method stub + return null; + } + + @Override + public byte[] getEncoded() { + // TODO Auto-generated method stub + return "privatekey".getBytes(); + } + + @Override + public String getAlgorithm() { + // TODO Auto-generated method stub + return null; + } + }; + KeyPair keypair = new KeyPair(publicKey, privateKey); + + when(csrMeta.keypair(trans)).thenReturn(keypair); + when(csrMeta.challenge()).thenReturn("challenge"); + when(x509.getSubjectDN()).thenReturn(null); + when(x509.getEncoded()).thenReturn("x509Certificate".getBytes()); + + } + + @Test + public void testCertResp() throws IOException, GeneralSecurityException, CertException { + CertResp resp = new CertResp("CERT"); + + assertEquals("CERT", resp.asCertString()); + assertEquals("", resp.challenge()); + + String[] trustChain = { "trustChain" }; + String[] notes = { "notes" }; + + String[] caIssureDNs = { "caIssuer" }; + String[] trustedCAs = { "trustedCAs" }; + + when(ca.getCaIssuerDNs()).thenReturn(caIssureDNs); + when(ca.getEnv()).thenReturn("Env"); + when(ca.getTrustedCAs()).thenReturn(trustedCAs); + + resp = new CertResp(trans, ca, x509, csrMeta, trustChain, notes); + + assertNotNull(resp.privateString()); + assertEquals("challenge", resp.challenge()); + assertEquals("notes", resp.notes()[0]); + assertEquals("trustChain", resp.trustChain()[0]); + assertEquals("caIssuer", resp.caIssuerDNs()[0]); + assertEquals("trustedCAs", resp.trustCAs()[0]); + assertEquals("Env", resp.env()); + } } 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 9e01d7c7..4cd628e8 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 @@ -124,10 +124,10 @@ public class AAFcli { } public AuthzEnv env() { - return env; - } + return env; + } - public static int timeout() { + public static int timeout() { return TIMEOUT; } @@ -332,7 +332,7 @@ public class AAFcli { Thread.sleep((long)(delay+globalDelay)); } } catch (Exception e) { - if (expect.contains(-1)) { + if (expect.contains(-1)) { pw.println(e.getMessage()); ret = -1; } else { diff --git a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java index d4a82d5d..9bfb77f9 100644 --- a/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java +++ b/auth/auth-cmd/src/main/java/org/onap/aaf/auth/cmd/Version.java @@ -29,7 +29,7 @@ import org.onap.aaf.misc.env.APIException; public class Version extends Cmd { private final String version; - public Version(AAFcli aafcli) { + public Version(AAFcli aafcli) { super(aafcli, "version"); version = aafcli.access.getProperty(Config.AAF_DEPLOYED_VERSION, Config.AAF_DEFAULT_API_VERSION); } 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 3edc0e59..feffbdb0 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 @@ -60,10 +60,10 @@ public class Delete extends Cmd { pk.setAction(args[idx++]); if(pk.getType().contains("@")) { // User Perm deletion... Must remove from hidden role - client.setQueryParams("force"); + client.setQueryParams("force"); } else { - // Set "Force" if set - setQueryParamsOn(client); + // Set "Force" if set + setQueryParamsOn(client); } Future<PermRequest> fp = client.delete( "/authz/perm", 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 2f84f583..d4d6c702 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 @@ -123,12 +123,12 @@ public class List extends BaseCmd<Role> { pw().format(roleFormat, "["+ns+"]"+roleName.substring(ns.length()),XXXX_XX_XX); } } else { - String fullname; - if(ns==null) { - fullname = roleName; - } else { - fullname = ns+'.'+roleName; - } + String fullname; + if(ns==null) { + fullname = roleName; + } else { + fullname = ns+'.'+roleName; + } UserRole ur = get(fullname,urs); if (ur!=null && now.compare(ur.getExpires().normalize())>0) { if (ns==null) { 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 2471c21a..8111fedc 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 @@ -77,8 +77,8 @@ public class ListByUser extends Cmd { urs = fur.value; code = fur.code(); } else { - error(fur); - return fur.code(); + error(fur); + return fur.code(); } if (aafcli.isDetailed()) { @@ -88,37 +88,37 @@ public class ListByUser extends Cmd { getDF(Perms.class) ); if (fp.get(AAFcli.timeout())) { - Map<String, Role> rs = new TreeMap<>(); + Map<String, Role> rs = new TreeMap<>(); perms = fp.value; for( Perm p : perms.getPerm()) { - for(String sr : p.getRoles()) { - Role r = rs.get(sr); - if(r==null) { - r = new Role(); - String[] split = Split.split('|', sr); - if(split.length>1) { - r.setNs(split[0]); - r.setName(split[1]); - } else { - r.setName(sr); - } - rs.put(sr, r); - roles.getRole().add(r); - } - r.getPerms().add(p); - } + for(String sr : p.getRoles()) { + Role r = rs.get(sr); + if(r==null) { + r = new Role(); + String[] split = Split.split('|', sr); + if(split.length>1) { + r.setNs(split[0]); + r.setName(split[1]); + } else { + r.setName(sr); + } + rs.put(sr, r); + roles.getRole().add(r); + } + r.getPerms().add(p); + } } } code = fp.code(); } else { - roles = new Roles(); - java.util.List<Role> lr = roles.getRole(); - Role r; - for(UserRole ur : urs.getUserRole()) { - r = new Role(); - r.setName(ur.getRole()); - lr.add(r); - } + roles = new Roles(); + java.util.List<Role> lr = roles.getRole(); + Role r; + for(UserRole ur : urs.getUserRole()) { + r = new Role(); + r.setName(ur.getRole()); + lr.add(r); + } } 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 d7431be1..1613b2f9 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 @@ -44,7 +44,7 @@ public class Cred extends Cmd { public static final String ATTEMPT_FAILED_SPECIFICS_WITHELD = "Attempt Failed. Specifics witheld."; private static final String CRED_PATH = "/authn/cred"; private static final String[] options = {"add","del","reset","extend"/*,"clean"*/}; - private ErrMessage em; + private ErrMessage em; public Cred(User parent) throws APIException { super(parent,"cred", new Param(optionsToString(options),true), @@ -126,18 +126,18 @@ public class Cred extends Cmd { } else if (fp.code()==202) { pw().println("Credential Action Accepted, but requires Approvals before actualizing"); } else if (fp.code()==300 || fp.code()==406) { - Error err = em.getError(fp); - String text = err.getText(); - List<String> vars = err.getVariables(); - - // IMPORTANT! We do this backward, because it is looking for string - // %1 or %13. If we replace %1 first, that messes up %13 - for(int i=vars.size()-1;i>0;--i) { - text = text.replace("%"+(i+1), (i<10?" ":"") + i+") " + vars.get(i)); - } + Error err = em.getError(fp); + String text = err.getText(); + List<String> vars = err.getVariables(); + + // IMPORTANT! We do this backward, because it is looking for string + // %1 or %13. If we replace %1 first, that messes up %13 + for(int i=vars.size()-1;i>0;--i) { + text = text.replace("%"+(i+1), (i<10?" ":"") + i+") " + vars.get(i)); + } - text = text.replace("%1",vars.get(0)); - pw().println(text); + text = text.replace("%1",vars.get(0)); + pw().println(text); } else if (fp.code()==406 && option==1) { pw().println("You cannot delete this Credential"); } else if (fp.code()==409 && option==0) { 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 444a82ab..212df8ab 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 @@ -64,9 +64,9 @@ public class List extends BaseCmd<User> { String tag=user.getTag(); Integer type = user.getType(); if(tag==null) { - tag=""; + tag=""; } else if(type!=null && type>=200) { - tag = "\n\tfingerprint: " + tag; + tag = "\n\tfingerprint: " + tag; } pw().format(format, user.getId(), 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 5df11617..dff3dc5e 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 @@ -69,7 +69,7 @@ public class ListForPermission extends Cmd { ); if (fp.get(AAFcli.timeout())) { if (aafcli.isTest()) - Collections.sort(fp.value.getUser(), (Comparator<User>) (u1, u2) -> u1.getId().compareTo(u2.getId())); + Collections.sort(fp.value.getUser(), (Comparator<User>) (u1, u2) -> u1.getId().compareTo(u2.getId())); ((org.onap.aaf.auth.cmd.user.List)parent).report(fp.value,false,HEADER,type+"|"+instance+"|"+action); if (fp.code()==404)return 200; } else { 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 4787cabc..b177778e 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 @@ -44,7 +44,7 @@ public class Role extends Cmd { private static final String[] options = {"add", "del", "extend"}; public Role(User parent) { super(parent, "role", new Param(optionsToString(options), true), new Param("user", true), - new Param("role[,role]*", false)); + new Param("role[,role]*", false)); } @Override 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 800a8472..5fb590c1 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 @@ -75,15 +75,15 @@ public class Define { } public static String varReplace(final String potential) { - int idx = potential.indexOf(ROOT_NS_TAG_DOT); - if(idx<0) { - return potential; - } else if(idx==0) { - return ROOT_NS + potential.substring(ROOT_NS_TAG_LEN); + int idx = potential.indexOf(ROOT_NS_TAG_DOT); + if(idx<0) { + return potential; + } else if(idx==0) { + return ROOT_NS + potential.substring(ROOT_NS_TAG_LEN); } else if('.'==potential.charAt(idx)) { return potential.replace(ROOT_NS_TAG, ROOT_NS); } else { - return potential; + return potential; } } @@ -93,7 +93,7 @@ public class Define { public static String getCredType(int type) { switch(type) { - case 0: return "NoCrd"; + case 0: return "NoCrd"; case 1: return "U/P"; case 2: return "U/P2"; case 10: return "FQI"; 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 497c13d6..a46be8ef 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 @@ -102,9 +102,9 @@ public class AuthzEnv extends RosettaEnv implements Access { @Override public void log(Throwable e, Object... msgs) { - Object[] nm = new Object[msgs.length+1]; - System.arraycopy(msgs, 0, nm, 1, msgs.length); - nm[0]=e; + Object[] nm = new Object[msgs.length+1]; + System.arraycopy(msgs, 0, nm, 1, msgs.length); + nm[0]=e; access.log(Level.ERROR, nm); } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java index 1a1e7f24..454d46d2 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/env/AuthzTrans.java @@ -44,8 +44,8 @@ public interface AuthzTrans extends TransStore { public abstract AuthzTrans set(HttpServletRequest req, HttpServletResponse resp); - public abstract HttpServletRequest hreq(); - + public abstract HttpServletRequest hreq(); + public abstract HttpServletResponse hresp(); public abstract String user(); @@ -84,7 +84,7 @@ public interface AuthzTrans extends TransStore { public abstract String getTag(); - public abstract void clearCache(); + public abstract void clearCache(); }
\ No newline at end of file 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 bda23e13..e4420ab1 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 @@ -130,11 +130,11 @@ public class AuthzTransFilter extends TransFilter<AuthzTrans> { sb.append("user="); Principal p = trans.getUserPrincipal(); if (p==null) { - lt=trans.warn(); + lt=trans.warn(); sb.append(target); sb.append("[None]"); } else { - lt=trans.info(); + lt=trans.info(); sb.append(p.getName()); if (p instanceof TrustPrincipal) { sb.append('('); 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 0af760b8..c68f71ab 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 @@ -35,10 +35,10 @@ import org.onap.aaf.misc.env.LogTarget; import org.onap.aaf.misc.env.impl.BasicTrans; public class AuthzTransImpl extends BasicTrans implements AuthzTrans { - private static final String N_A = "n/a"; - private static final String BLANK = ""; - private HttpServletRequest hreq; - private HttpServletResponse hresp; + private static final String N_A = "n/a"; + private static final String BLANK = ""; + private HttpServletRequest hreq; + private HttpServletResponse hresp; private TaggedPrincipal user; private Lur lur; private Organization org; @@ -57,8 +57,8 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public AuthzTrans set(HttpServletRequest req, HttpServletResponse resp) { - hreq = req; - hresp = resp; + hreq = req; + hresp = resp; user = (TaggedPrincipal)req.getUserPrincipal(); for (REQD_TYPE rt : REQD_TYPE.values()) { @@ -76,12 +76,12 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { @Override public HttpServletRequest hreq() { - return hreq; + return hreq; } @Override public HttpServletResponse hresp() { - return hresp; + return hresp; } @Override @@ -135,7 +135,7 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public String path() { - return hreq==null?"":hreq.getPathInfo(); + return hreq==null?"":hreq.getPathInfo(); } /** @@ -231,20 +231,20 @@ public class AuthzTransImpl extends BasicTrans implements AuthzTrans { */ @Override public void setTag(String tag) { - this.tag = tag; + this.tag = tag; } @Override public String getTag() { - return tag; + return tag; } - @Override - public void clearCache() { + @Override + public void clearCache() { if (lur!=null) { - StringBuilder report = new StringBuilder(); + StringBuilder report = new StringBuilder(); lur.clear(user, report); info().log(report); } - } + } } 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 f0052e5a..9189cc30 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 @@ -136,17 +136,17 @@ public class NullTrans implements AuthzTrans { } @Override - public HttpServletRequest hreq() { - return null; - } + public HttpServletRequest hreq() { + return null; + } @Override - public HttpServletResponse hresp() { - return null; - } + public HttpServletResponse hresp() { + return null; + } - @Override + @Override public String user() { return null; } @@ -243,15 +243,15 @@ public class NullTrans implements AuthzTrans { } return now; } - @Override - public void setTag(String tag) { - } - @Override - public String getTag() { - return null; - } - @Override - public void clearCache() { - } + @Override + public void setTag(String tag) { + } + @Override + public String getTag() { + return null; + } + @Override + public void clearCache() { + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/log4j/Log4JAccessAppender.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/log4j/Log4JAccessAppender.java index 7bda155c..165295d9 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/log4j/Log4JAccessAppender.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/log4j/Log4JAccessAppender.java @@ -27,52 +27,52 @@ import org.apache.log4j.spi.LoggingEvent; import org.onap.aaf.cadi.Access; public class Log4JAccessAppender extends AppenderSkeleton{ - private Access access; + private Access access; - public Log4JAccessAppender(Access access) { - this.access = access; - } + public Log4JAccessAppender(Access access) { + this.access = access; + } - @Override - public void close() { - } + @Override + public void close() { + } - @Override - public boolean requiresLayout() { - return false; - } + @Override + public boolean requiresLayout() { + return false; + } - @Override - protected void append(LoggingEvent event) { - Access.Level al = null; - switch(event.getLevel().toInt()) { - case Level.FATAL_INT: - case Level.ERROR_INT: - if(access.willLog(Access.Level.ERROR)) { - al=Access.Level.ERROR; - } - break; - case Level.WARN_INT: - if(!access.willLog(Access.Level.WARN)) { - al=Access.Level.WARN; - } - break; - case Level.ALL_INT: - case Level.INFO_INT: - if(!access.willLog(Access.Level.INFO)) { - al=Access.Level.INFO; - } - break; - case Level.TRACE_INT: - if(!access.willLog(Access.Level.TRACE)) { - al=Access.Level.TRACE; - } - break; - } - if(al!=null) { - access.log(al,"Log4J["+event.getLoggerName()+"]["+event.getLevel()+']',event.getMessage()); - } - } + @Override + protected void append(LoggingEvent event) { + Access.Level al = null; + switch(event.getLevel().toInt()) { + case Level.FATAL_INT: + case Level.ERROR_INT: + if(access.willLog(Access.Level.ERROR)) { + al=Access.Level.ERROR; + } + break; + case Level.WARN_INT: + if(!access.willLog(Access.Level.WARN)) { + al=Access.Level.WARN; + } + break; + case Level.ALL_INT: + case Level.INFO_INT: + if(!access.willLog(Access.Level.INFO)) { + al=Access.Level.INFO; + } + break; + case Level.TRACE_INT: + if(!access.willLog(Access.Level.TRACE)) { + al=Access.Level.TRACE; + } + break; + } + if(al!=null) { + access.log(al,"Log4J["+event.getLoggerName()+"]["+event.getLevel()+']',event.getMessage()); + } + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/FileMailer.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/FileMailer.java index 6a648a8a..9478832b 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/FileMailer.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/FileMailer.java @@ -33,120 +33,120 @@ import org.onap.aaf.misc.env.APIException; import org.onap.aaf.misc.env.util.Chrono; public class FileMailer implements Mailer { - private Path dir; - private String mail_from; - private String testName; - private int count; + private Path dir; + private String mail_from; + private String testName; + private int count; - public FileMailer(Access access) throws APIException { - count = 0; - - mail_from = access.getProperty("MAIL_FROM", null); - if(mail_from==null) { - throw new APIException("MAIL_FROM property is required for Email Notifications"); - } - String env = access.getProperty("CASS_ENV", "UNKNOWN"); - String logdir = access.getProperty("LOG_DIR",null); - if(logdir==null) { - logdir=access.getProperty(env+".LOG_DIR", "logs/"+env); - } - dir = Paths.get(logdir+"/email/"+Chrono.dateOnlyStamp()); - if(!Files.exists(dir)) { - try { - Files.createDirectories(dir); - } catch (IOException e) { - throw new APIException("Cannot create directory: " + dir.toString(),e); - } - } - - boolean dryrun = Boolean.parseBoolean(access.getProperty("DRY_RUN","false")); - String str = access.getProperty("MAX_EMAIL", null); - int maxEmail = str==null || str.isEmpty()?Integer.MAX_VALUE:Integer.parseInt(str); - if(dryrun && maxEmail==1) { - testName = "email_test"; - } else { - testName = null; - } - } + public FileMailer(Access access) throws APIException { + count = 0; + + mail_from = access.getProperty("MAIL_FROM", null); + if(mail_from==null) { + throw new APIException("MAIL_FROM property is required for Email Notifications"); + } + String env = access.getProperty("CASS_ENV", "UNKNOWN"); + String logdir = access.getProperty("LOG_DIR",null); + if(logdir==null) { + logdir=access.getProperty(env+".LOG_DIR", "logs/"+env); + } + dir = Paths.get(logdir+"/email/"+Chrono.dateOnlyStamp()); + if(!Files.exists(dir)) { + try { + Files.createDirectories(dir); + } catch (IOException e) { + throw new APIException("Cannot create directory: " + dir.toString(),e); + } + } + + boolean dryrun = Boolean.parseBoolean(access.getProperty("DRY_RUN","false")); + String str = access.getProperty("MAX_EMAIL", null); + int maxEmail = str==null || str.isEmpty()?Integer.MAX_VALUE:Integer.parseInt(str); + if(dryrun && maxEmail==1) { + testName = "email_test"; + } else { + testName = null; + } + } - @Override - public boolean sendEmail(AuthzTrans trans, String test, List<String> toList, List<String> ccList, - String subject, String body, Boolean urgent) throws OrganizationException { - boolean status = false; - try { - Path path; - if(testName==null) { - path = Files.createTempFile(dir, "email", ".hdr"); - } else { - path = Paths.get(dir.toString(), "emailTEST"+test+".hdr"); - } - BufferedWriter bw = Files.newBufferedWriter(path); - try { - bw.write("TO: "); - boolean first = true; - for(String to : toList) { - if(first) { - first = false; - } else { - bw.write(','); - } - bw.write(to); - } - bw.newLine(); - - bw.write("CC: "); - first = true; - for(String cc : ccList) { - if(first) { - first = false; - } else { - bw.write(','); - } - bw.write(cc); - } - bw.newLine(); - - bw.write("FROM: "); - bw.write(mail_from); - bw.newLine(); - - bw.write("SUBJECT: "); - bw.write(subject); - bw.newLine(); - - if(urgent) { - bw.write("Importance: High"); - bw.newLine(); - } + @Override + public boolean sendEmail(AuthzTrans trans, String test, List<String> toList, List<String> ccList, + String subject, String body, Boolean urgent) throws OrganizationException { + boolean status = false; + try { + Path path; + if(testName==null) { + path = Files.createTempFile(dir, "email", ".hdr"); + } else { + path = Paths.get(dir.toString(), "emailTEST"+test+".hdr"); + } + BufferedWriter bw = Files.newBufferedWriter(path); + try { + bw.write("TO: "); + boolean first = true; + for(String to : toList) { + if(first) { + first = false; + } else { + bw.write(','); + } + bw.write(to); + } + bw.newLine(); + + bw.write("CC: "); + first = true; + for(String cc : ccList) { + if(first) { + first = false; + } else { + bw.write(','); + } + bw.write(cc); + } + bw.newLine(); + + bw.write("FROM: "); + bw.write(mail_from); + bw.newLine(); + + bw.write("SUBJECT: "); + bw.write(subject); + bw.newLine(); + + if(urgent) { + bw.write("Importance: High"); + bw.newLine(); + } - } finally { - bw.close(); - } + } finally { + bw.close(); + } - path = Paths.get(path.toString().replaceAll(".hdr", ".html")); - bw = Files.newBufferedWriter(path); - try { - bw.write(body); - bw.newLine(); - } finally { - bw.close(); - } - status = true; - } catch ( IOException e) { - throw new OrganizationException(e); - } - ++count; - return status; - } + path = Paths.get(path.toString().replaceAll(".hdr", ".html")); + bw = Files.newBufferedWriter(path); + try { + bw.write(body); + bw.newLine(); + } finally { + bw.close(); + } + status = true; + } catch ( IOException e) { + throw new OrganizationException(e); + } + ++count; + return status; + } - @Override - public String mailFrom() { - return mail_from; - } + @Override + public String mailFrom() { + return mail_from; + } - @Override - public int count() { - return count; - } + @Override + public int count() { + return count; + } } diff --git a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java index dd32c651..64a2e8dd 100644 --- a/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java +++ b/auth/auth-core/src/main/java/org/onap/aaf/auth/org/Mailer.java @@ -34,8 +34,8 @@ public interface Mailer { String body, Boolean urgent) throws OrganizationException; - public String mailFrom(); + public String mailFrom(); - public int count(); + public int count(); } 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 539b9369..75669632 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 @@ -65,17 +65,17 @@ public interface Organization { public Organization org(); // Organization of Identity - public static String mixedCase(String in) { - StringBuilder sb = new StringBuilder(); - for(int i=0;i<in.length();++i) { - if(i==0) { - sb.append(Character.toUpperCase(in.charAt(i))); - } else { - sb.append(Character.toLowerCase(in.charAt(i))); - } - } - return sb.toString(); - } + public static String mixedCase(String in) { + StringBuilder sb = new StringBuilder(); + for(int i=0;i<in.length();++i) { + if(i==0) { + sb.append(Character.toUpperCase(in.charAt(i))); + } else { + sb.append(Character.toLowerCase(in.charAt(i))); + } + } + return sb.toString(); + } } @@ -115,7 +115,7 @@ public interface Organization { * feed with a "Deleted ID" feed. * */ - public boolean isRevoked(AuthzTrans trans, String id); + public boolean isRevoked(AuthzTrans trans, String id); /** @@ -559,17 +559,17 @@ public interface Organization { return nullStringArray; } - @Override - public boolean isRevoked(AuthzTrans trans, String id) { - // provide a corresponding feed that indicates that an ID has been intentionally removed from identities.dat table. - return false; - } - - @Override - public List<Identity> getIDs(AuthzTrans trans, String user, int escalate) throws OrganizationException { - // TODO Auto-generated method stub - return null; - } + @Override + public boolean isRevoked(AuthzTrans trans, String id) { + // provide a corresponding feed that indicates that an ID has been intentionally removed from identities.dat table. + return false; + } + + @Override + public List<Identity> getIDs(AuthzTrans trans, String user, int escalate) throws OrganizationException { + // TODO Auto-generated method stub + return null; + } }; } 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 098fb979..4f2ba4f2 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 @@ -64,15 +64,15 @@ public class OrganizationFactory { } } if(firstOrg==null) { // attempt to load DefaultOrg - try { - Class<?> cls = Class.forName("org.onap.aaf.org.DefaultOrg"); - @SuppressWarnings("unchecked") - Constructor<Organization> cnst = (Constructor<Organization>)cls.getConstructor(Env.class,String.class); - String realm = env.getProperty(Config.AAF_DEFAULT_REALM,"people.osaaf.org"); - defaultOrg = cnst.newInstance(env,realm); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) { - env.init().log("Default Organization Module not linked in",e); - } + try { + Class<?> cls = Class.forName("org.onap.aaf.org.DefaultOrg"); + @SuppressWarnings("unchecked") + Constructor<Organization> cnst = (Constructor<Organization>)cls.getConstructor(Env.class,String.class); + String realm = env.getProperty(Config.AAF_DEFAULT_REALM,"people.osaaf.org"); + defaultOrg = cnst.newInstance(env,realm); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException e) { + env.init().log("Default Organization Module not linked in",e); + } } if (defaultOrg == null) { defaultOrg = firstOrg; 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 acca80ba..9dec87db 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 @@ -125,11 +125,11 @@ public abstract class RServlet<TRANS extends Trans> implements Servlet { return "RServlet for Jetty"; } - /** + /** * Allow Service to instantiate certain actions after service starts up - * @throws LocatorException - * @throws CadiException - * @throws APIException + * @throws LocatorException + * @throws CadiException + * @throws APIException */ public void postStartup(String hostname, int port) throws APIException { } 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 81e2e619..2acfbe34 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 @@ -120,7 +120,7 @@ public abstract class TransFilter<TRANS extends TransStore> implements Filter { resp = cadi.validate(req,res,trans); Object tag = req.getAttribute("CRED_TAG"); if(tag!=null) { - ((AuthzTrans)trans).setTag(tag.toString()); + ((AuthzTrans)trans).setTag(tag.toString()); } switch(r=resp.isAuthenticated()) { case IS_AUTHENTICATED: @@ -145,7 +145,7 @@ public abstract class TransFilter<TRANS extends TransStore> implements Filter { // use trans.checkpoint(resp.desc(),Env.ALWAYS); if (resp.isFailedAttempt()) { - target = resp.getTarget(); + target = resp.getTarget(); } } } catch (Exception e) { 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 5fbb951b..4fb81d73 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,16 +65,16 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte String str = access.getProperty(Config.AAF_LOCATOR_ENTRIES, null); String[] scomp = Split.splitTrim(',', str); if(scomp.length==0) { - throw new CadiException(Config.AAF_LOCATOR_ENTRIES + " must be defined."); + throw new CadiException(Config.AAF_LOCATOR_ENTRIES + " must be defined."); } else { - str = ROOT_NS + '.' + scomp[0]; + str = ROOT_NS + '.' + scomp[0]; } app_name = str; str = access.getProperty(Config.AAF_LOCATOR_VERSION, null); if(str==null) { - str = Defaults.AAF_VERSION; - env.setProperty(Config.AAF_LOCATOR_VERSION, str); + str = Defaults.AAF_VERSION; + env.setProperty(Config.AAF_LOCATOR_VERSION, str); } app_version = access.getProperty(Config.AAF_DEPLOYED_VERSION, str); @@ -101,11 +101,11 @@ public abstract class AbsService<ENV extends BasicEnv, TRANS extends Trans> exte } public void setProtocol(String proto) { - env.setProperty(Config.AAF_LOCATOR_PROTOCOL, proto); + env.setProperty(Config.AAF_LOCATOR_PROTOCOL, proto); } public void setSubprotocol(String subproto) { - env.setProperty(Config.AAF_LOCATOR_SUBPROTOCOL, subproto); + env.setProperty(Config.AAF_LOCATOR_SUBPROTOCOL, subproto); } protected abstract Filter[] _filters(Object ... additionalTafLurs) throws CadiException, LocatorException; 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 11ba6562..90f4158f 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 @@ -42,18 +42,18 @@ public abstract class AbsServiceStarter<ENV extends RosettaEnv, TRANS extends Tr private Registrar<ENV> registrar; private boolean do_register; protected AbsService<ENV,TRANS> service; - protected String hostname; - protected final boolean secure; + protected String hostname; + protected final boolean secure; public AbsServiceStarter(final AbsService<ENV,TRANS> service, boolean secure) { - this.secure = secure; + this.secure = secure; this.service = service; try { OrganizationFactory.init(service.env); } catch (OrganizationException e) { service.access.log(e, "Missing defined Organization Plugins"); - System.exit(3); + System.exit(3); } // do_register - this is used for specialty Debug Situations. Developer can create an Instance for a remote system // for Debugging purposes without fear that real clients will start to call your debug instance @@ -61,10 +61,10 @@ public abstract class AbsServiceStarter<ENV extends RosettaEnv, TRANS extends Tr hostname = access().getProperty(Config.HOSTNAME, null); if (hostname==null) { try { - hostname = Inet4Address.getLocalHost().getHostName(); - } catch (UnknownHostException e) { - hostname= "cannotBeDetermined"; - } + hostname = Inet4Address.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + hostname= "cannotBeDetermined"; + } } _propertyAdjustment(); } @@ -83,31 +83,31 @@ public abstract class AbsServiceStarter<ENV extends RosettaEnv, TRANS extends Tr @Override public final void start() throws Exception { - ExecutorService es = Executors.newSingleThreadExecutor(); - Future<?> app = es.submit(this); + ExecutorService es = Executors.newSingleThreadExecutor(); + Future<?> app = es.submit(this); final AbsServiceStarter<?,?> absSS = this; // Docker/K8 may separately create startup Status in this dir for startup // sequencing. If so, delete ON EXIT - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override public void run() { - absSS.access().printf(Level.INIT, "Shutting down %s:%s\n",absSS.service.app_name, absSS.service.app_version); - absSS.shutdown(); - app.cancel(true); - } - }); - if(System.getProperty("ECLIPSE", null)!=null) { - Thread.sleep(2000); - if(!app.isCancelled()) { - System.out.println("Service Started in Eclipse: "); - System.out.print(" Hit <enter> to end:\n"); - try { - System.in.read(); - System.exit(0); - } catch (IOException e) { - } - } - } + absSS.access().printf(Level.INIT, "Shutting down %s:%s\n",absSS.service.app_name, absSS.service.app_version); + absSS.shutdown(); + app.cancel(true); + } + }); + if(System.getProperty("ECLIPSE", null)!=null) { + Thread.sleep(2000); + if(!app.isCancelled()) { + System.out.println("Service Started in Eclipse: "); + System.out.print(" Hit <enter> to end:\n"); + try { + System.in.read(); + System.exit(0); + } catch (IOException e) { + } + } + } } @SafeVarargs @@ -123,16 +123,16 @@ public abstract class AbsServiceStarter<ENV extends RosettaEnv, TRANS extends Tr } @Override - public void run() { + public void run() { try { - _start(service); - } catch (Exception e) { - e.printStackTrace(); - shutdown(); - } - } + _start(service); + } catch (Exception e) { + e.printStackTrace(); + shutdown(); + } + } - @Override + @Override public void shutdown() { if (registrar!=null) { registrar.close(env()); @@ -141,26 +141,26 @@ public abstract class AbsServiceStarter<ENV extends RosettaEnv, TRANS extends Tr if (service!=null) { File status = new File("/opt/app/aaf/status/"); boolean deleted = false; - if(status.exists()) { - int lastdot = service.app_name.lastIndexOf("aaf."); - String fname; - if(lastdot<0) { - fname = service.app_name + '-' + hostname; - } else { - fname = service.app_name.substring(lastdot).replace('.', '-') - + '-' + hostname; - } - status = new File(status, fname); - if(status.exists()) { - deleted=status.delete(); - } - } - if(deleted) { - service.access.log(Level.INIT, "Deleted Status",status.getAbsolutePath()); - } else { - service.access.log(Level.INIT, "Status not deleted: ",status.getAbsolutePath()); - } - service.destroy(); + if(status.exists()) { + int lastdot = service.app_name.lastIndexOf("aaf."); + String fname; + if(lastdot<0) { + fname = service.app_name + '-' + hostname; + } else { + fname = service.app_name.substring(lastdot).replace('.', '-') + + '-' + hostname; + } + status = new File(status, fname); + if(status.exists()) { + deleted=status.delete(); + } + } + if(deleted) { + service.access.log(Level.INIT, "Deleted Status",status.getAbsolutePath()); + } else { + service.access.log(Level.INIT, "Status not deleted: ",status.getAbsolutePath()); + } + 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 8d49720b..78a7702b 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 @@ -197,12 +197,12 @@ public class JettyServiceStarter<ENV extends RosettaEnv, TRANS extends Trans> ex } } try { - String no_register = env().getProperty("aaf_no_register",null); - if(no_register==null) { - register(service.registrants(port)); - } else { - access().printf(Level.INIT,"'aaf_no_register' is set. %s will not be registered with Locator", service.app_name); - } + String no_register = env().getProperty("aaf_no_register",null); + if(no_register==null) { + register(service.registrants(port)); + } else { + access().printf(Level.INIT,"'aaf_no_register' is set. %s will not be registered with Locator", service.app_name); + } access().printf(Level.INIT, "Starting Jetty Service for %s, version %s, on %s://%s:%d", service.app_name,service.app_version,protocol,hostname,port); rserv.postStartup(hostname, port); 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 6d519c64..052f21bf 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 @@ -90,9 +90,9 @@ public class Validator { } protected final void match(String text, String str, Pattern p) { - if(str==null || !p.matcher(str).matches()) { - msg(text); - } + if(str==null || !p.matcher(str).matches()) { + msg(text); + } } protected final boolean nob(String str, Pattern p) { @@ -156,11 +156,11 @@ public class Validator { } else if (user==null) { msg("User is null"); } else { - if(!(type.startsWith(user) && type.endsWith(":id"))) { - if(nob(type,NAME_CHARS)) { - msg("Perm Type [" + type + "] is invalid."); - } - } + if(!(type.startsWith(user) && type.endsWith(":id"))) { + if(nob(type,NAME_CHARS)) { + msg("Perm Type [" + type + "] is invalid."); + } + } } return this; } @@ -177,7 +177,7 @@ public class Validator { } public final Validator permInstance(String instance) { - if(!"/".equals(instance) && nob(instance,instChars)) { + if(!"/".equals(instance) && nob(instance,instChars)) { msg("Perm Instance [" + instance + "] is invalid."); } return this; @@ -192,24 +192,24 @@ public class Validator { } public final Validator role(String user, String role) { - boolean quit = false; - if(role==null) { - msg("Role is null"); - quit = true; - } - if(user==null) { - msg("User is null"); - quit = true; - } - if(!quit) { - if(role.startsWith(user) && role.endsWith(":user")) { - if(!(role.length() == user.length() + 5)) { - msg("Role [" + role + "] is invalid."); - } - } else if (nob(role, NAME_CHARS)) { - msg("Role [" + role + "] is invalid."); - } - } + boolean quit = false; + if(role==null) { + msg("Role is null"); + quit = true; + } + if(user==null) { + msg("User is null"); + quit = true; + } + if(!quit) { + if(role.startsWith(user) && role.endsWith(":user")) { + if(!(role.length() == user.length() + 5)) { + msg("Role [" + role + "] is invalid."); + } + } else if (nob(role, NAME_CHARS)) { + msg("Role [" + role + "] is invalid."); + } + } return this; } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/log4j/test/JU_Log4jAccessAppender.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/log4j/test/JU_Log4jAccessAppender.java index 2c5d86b4..8123a82d 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/log4j/test/JU_Log4jAccessAppender.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/log4j/test/JU_Log4jAccessAppender.java @@ -38,75 +38,75 @@ import org.onap.aaf.cadi.Access; public class JU_Log4jAccessAppender { - @Mock - Access access; - - @Before - public void setUp() { - initMocks(this); - } - - @Test - public void testRequiresLayout() { - Log4JAccessAppender log4jObj = new Log4JAccessAppender(access); - boolean retObj = log4jObj.requiresLayout(); - assertFalse(retObj); - } - - @Test - public void testClose() { - Log4JAccessAppender log4jObj = new Log4JAccessAppender(access); - log4jObj.close(); - - } - - @Test - public void testAppend() { - Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); - LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.FATAL,"test",Thread.currentThread().getName(),null,null,null,null); - log4jObj.append(event); - Mockito.doReturn(true).when(access).willLog(Access.Level.ERROR); - event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.ERROR,"test",Thread.currentThread().getName(),null,null,null,null); - log4jObj.append(event); - event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.ALL,"test",Thread.currentThread().getName(),null,null,null,null); - log4jObj.append(event); - } - - @Test - public void testAppendWARN() { - Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); - Mockito.doReturn(false).when(access).willLog(Access.Level.WARN); - LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.WARN,"test",Thread.currentThread().getName(),null,null,null,null); - log4jObj.append(event); - } - - @Test - public void testAppendINFO() { - Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); - Mockito.doReturn(true).when(access).willLog(Access.Level.INFO); - LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.INFO,"test",Thread.currentThread().getName(),null,null,null,null); - log4jObj.append(event); - } - - @Test - public void testAppendWTrace() { - Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); - Mockito.doReturn(false).when(access).willLog(Access.Level.TRACE); - LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.TRACE,"test",Thread.currentThread().getName(),null,null,null,null); - log4jObj.append(event); - } - - class Log4jAccessAppenderImpl extends Log4JAccessAppender{ + @Mock + Access access; + + @Before + public void setUp() { + initMocks(this); + } + + @Test + public void testRequiresLayout() { + Log4JAccessAppender log4jObj = new Log4JAccessAppender(access); + boolean retObj = log4jObj.requiresLayout(); + assertFalse(retObj); + } + + @Test + public void testClose() { + Log4JAccessAppender log4jObj = new Log4JAccessAppender(access); + log4jObj.close(); + + } + + @Test + public void testAppend() { + Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); + LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.FATAL,"test",Thread.currentThread().getName(),null,null,null,null); + log4jObj.append(event); + Mockito.doReturn(true).when(access).willLog(Access.Level.ERROR); + event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.ERROR,"test",Thread.currentThread().getName(),null,null,null,null); + log4jObj.append(event); + event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.ALL,"test",Thread.currentThread().getName(),null,null,null,null); + log4jObj.append(event); + } + + @Test + public void testAppendWARN() { + Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); + Mockito.doReturn(false).when(access).willLog(Access.Level.WARN); + LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.WARN,"test",Thread.currentThread().getName(),null,null,null,null); + log4jObj.append(event); + } + + @Test + public void testAppendINFO() { + Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); + Mockito.doReturn(true).when(access).willLog(Access.Level.INFO); + LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.INFO,"test",Thread.currentThread().getName(),null,null,null,null); + log4jObj.append(event); + } + + @Test + public void testAppendWTrace() { + Log4jAccessAppenderImpl log4jObj = new Log4jAccessAppenderImpl(access); + Mockito.doReturn(false).when(access).willLog(Access.Level.TRACE); + LoggingEvent event=new LoggingEvent("com.chililog.server.engine",Logger.getLogger(Log4JAccessAppender.class),(new Date()).getTime(),Level.TRACE,"test",Thread.currentThread().getName(),null,null,null,null); + log4jObj.append(event); + } + + class Log4jAccessAppenderImpl extends Log4JAccessAppender{ - public Log4jAccessAppenderImpl(Access access) { - super(access); - // TODO Auto-generated constructor stub - } - - @Override - protected void append(LoggingEvent event) { - super.append(event); - } - - } + public Log4jAccessAppenderImpl(Access access) { + super(access); + // TODO Auto-generated constructor stub + } + + @Override + protected void append(LoggingEvent event) { + super.append(event); + } + + } } diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java index 20b47331..14d702b3 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/org/test/JU_OrganizationFactory.java @@ -56,7 +56,7 @@ public class JU_OrganizationFactory { @SuppressWarnings("static-access") @Test public void testInit() throws OrganizationException { - Assert.assertEquals(null, organizationFactory.init(bEnv)); + Assert.assertEquals(null, organizationFactory.init(bEnv)); } @SuppressWarnings("static-access") //TODO:Fix this once real input is available AAF-111 diff --git a/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/TestKill.java b/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/TestKill.java index c6ddc79f..40e1886e 100644 --- a/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/TestKill.java +++ b/auth/auth-core/src/test/java/org/onap/aaf/auth/util/test/TestKill.java @@ -27,14 +27,14 @@ import java.util.concurrent.Future; public class TestKill implements Runnable { - public static void main(String[] args) { - ExecutorService es = Executors.newSingleThreadExecutor(); - TestKill tk = new TestKill(); - Future<?> app = es.submit(tk); + public static void main(String[] args) { + ExecutorService es = Executors.newSingleThreadExecutor(); + TestKill tk = new TestKill(); + Future<?> app = es.submit(tk); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { - System.out.println("Shutdown Hook, thread: setting interrupt"); + System.out.println("Shutdown Hook, thread: setting interrupt"); app.cancel(true); tk.longProcess(); es.shutdown(); @@ -43,23 +43,23 @@ public class TestKill implements Runnable { System.out.println("Service Start"); System.out.print("Hit <enter> to end:"); try { - System.in.read(); - System.exit(0); - } catch (IOException e) { - } - } + System.in.read(); + System.exit(0); + } catch (IOException e) { + } + } @Override - public void run() { - } + public void run() { + } private void longProcess() { - System.out.println("Starting long cleanup process"); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - System.out.println("Ending long cleanup process"); + System.out.println("Starting long cleanup process"); + try { + Thread.sleep(10000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("Ending long cleanup process"); } } 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 50b65ffe..fa9b5213 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 @@ -48,7 +48,7 @@ public class DefaultOrg implements Organization { final String domain; final String atDomain; final String realm; - + private final String root_ns; private final String NAME; @@ -112,15 +112,15 @@ public class DefaultOrg implements Organization { temp = env.getProperty(AAF_DATA_DIR); if (temp!=null) { File dir = new File(temp); - fRevoked=new File(dir,"revoked.dat"); + fRevoked=new File(dir,"revoked.dat"); } } else { - fRevoked = new File(temp); + fRevoked = new File(temp); } if (fRevoked!=null && fRevoked.exists()) { revoked = new Identities(fRevoked); } else { - revoked = null; + revoked = null; } } catch (IOException e) { @@ -172,54 +172,54 @@ public class DefaultOrg implements Organization { * If the ID isn't in the revoked file, if it exists, it is revoked. */ @Override - public boolean isRevoked(AuthzTrans trans, String key) { - if(revoked!=null) { + public boolean isRevoked(AuthzTrans trans, String key) { + if(revoked!=null) { try { - revoked.open(trans, DefaultOrgIdentity.TIMEOUT); - try { - Reuse r = revoked.reuse(); - int at = key.indexOf(domain); - String search; - if (at>=0) { - search = key.substring(0,at); - } else { - search = key; - } - return revoked.find(search, r)!=null; + revoked.open(trans, DefaultOrgIdentity.TIMEOUT); + try { + Reuse r = revoked.reuse(); + int at = key.indexOf(domain); + String search; + if (at>=0) { + search = key.substring(0,at); + } else { + search = key; + } + return revoked.find(search, r)!=null; } finally { revoked.close(trans); } - } catch (IOException e) { - trans.error().log(e); + } catch (IOException e) { + trans.error().log(e); + } + } + return false; + } + + /* (non-Javadoc) + * @see org.onap.aaf.auth.org.Organization#getEsclaations(org.onap.aaf.auth.env.AuthzTrans, java.lang.String, int) + */ + @Override + public List<Identity> getIDs(AuthzTrans trans, String user, int escalate) throws OrganizationException { + List<Identity> rv = new ArrayList<>(); + int end = Math.min(3,Math.abs(escalate)); + Identity id = null; + for(int i=0;i<end;++i) { + if(id==null) { + id = getIdentity(trans,user); + } else { + id = id.responsibleTo(); + } + if(id==null) { + break; + } else { + rv.add(id); } - } - return false; - } - - /* (non-Javadoc) - * @see org.onap.aaf.auth.org.Organization#getEsclaations(org.onap.aaf.auth.env.AuthzTrans, java.lang.String, int) - */ - @Override - public List<Identity> getIDs(AuthzTrans trans, String user, int escalate) throws OrganizationException { - List<Identity> rv = new ArrayList<>(); - int end = Math.min(3,Math.abs(escalate)); - Identity id = null; - for(int i=0;i<end;++i) { - if(id==null) { - id = getIdentity(trans,user); - } else { - id = id.responsibleTo(); - } - if(id==null) { - break; - } else { - rv.add(id); - } - } - return rv; - } - - // Note: Return a null if found; return a String Message explaining why not found. + } + return rv; + } + + // Note: Return a null if found; return a String Message explaining why not found. @Override public String isValidID(final AuthzTrans trans, final String id) { try { @@ -569,7 +569,7 @@ public class DefaultOrg implements Organization { @Override public String validate(AuthzTrans trans, Policy policy, Executor executor, String... vars) throws OrganizationException { - String user; + String user; switch(policy) { case OWNS_MECHID: case CREATE_MECHID: @@ -595,11 +595,11 @@ public class DefaultOrg implements Organization { case CREATE_MECHID_BY_PERM_ONLY: return getName() + " only allows sponsors to create MechIDs"; - case MAY_EXTEND_CRED_EXPIRES: - // If parm, use it, otherwise, trans - user = vars.length>1?vars[1]:trans.user(); - return executor.hasPermission(user, root_ns,"password", root_ns , "extend") - ?null:user + " does not have permission to extend passwords at " + getName(); + case MAY_EXTEND_CRED_EXPIRES: + // If parm, use it, otherwise, trans + user = vars.length>1?vars[1]:trans.user(); + return executor.hasPermission(user, root_ns,"password", root_ns , "extend") + ?null:user + " does not have permission to extend passwords at " + getName(); default: return policy.name() + " is unsupported at " + getName(); @@ -647,7 +647,7 @@ public class DefaultOrg implements Organization { public int sendEmail(AuthzTrans trans, List<String> toList, List<String> ccList, String subject, String body, Boolean urgent) throws OrganizationException { if (mailer!=null) { - String mailFrom = mailer.mailFrom(); + String mailFrom = mailer.mailFrom(); List<String> to = new ArrayList<>(); for (String em : toList) { if (em.indexOf('@')<0) { 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 67952001..df05da93 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 @@ -108,11 +108,11 @@ public class AAF_FS extends AbsService<AuthzEnv, AuthzTrans> { PropAccess propAccess = new PropAccess(logIt,args); try { new JettyServiceStarter<AuthzEnv,AuthzTrans>( - new AAF_FS(new AuthzEnv(propAccess)),false) - .start(); - } catch (Exception e) { - propAccess.log(e); - } + new AAF_FS(new AuthzEnv(propAccess)),false) + .start(); + } catch (Exception e) { + propAccess.log(e); + } } catch (Exception e) { e.printStackTrace(); } 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 c390afd5..9de694b7 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 @@ -44,83 +44,83 @@ import org.onap.aaf.cadi.register.Registrant; import org.onap.aaf.misc.env.APIException; public class JU_AAF_FS { - AuthzEnv aEnv; - AAF_FS aafFs; - File fService; - File fEtc; - String value; - File d; - private static final String testDir = "src/test/resources/logs"; - private ByteArrayOutputStream outStream; - private ByteArrayOutputStream errStream; + AuthzEnv aEnv; + AAF_FS aafFs; + File fService; + File fEtc; + String value; + File d; + private static final String testDir = "src/test/resources/logs"; + private ByteArrayOutputStream outStream; + private ByteArrayOutputStream errStream; - @Before - public void setUp() throws APIException, IOException, CadiException { - outStream = new ByteArrayOutputStream(); - errStream = new ByteArrayOutputStream(); - System.setOut(new PrintStream(outStream)); - System.setErr(new PrintStream(errStream)); - value = System.setProperty(Config.CADI_LOGDIR, testDir); - System.setProperty(Config.CADI_ETCDIR, testDir); - System.out.println(ClassLoader.getSystemResource("org.osaaf.aaf.log4j.props")); - d = new File(testDir); - d.mkdirs(); - fService = new File(d + "/fs-serviceTEST.log"); - fService.createNewFile(); - fEtc = new File(d + "/org.osaaf.aaf.log4j.props"); - fEtc.createNewFile(); + @Before + public void setUp() throws APIException, IOException, CadiException { + outStream = new ByteArrayOutputStream(); + errStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outStream)); + System.setErr(new PrintStream(errStream)); + value = System.setProperty(Config.CADI_LOGDIR, testDir); + System.setProperty(Config.CADI_ETCDIR, testDir); + System.out.println(ClassLoader.getSystemResource("org.osaaf.aaf.log4j.props")); + d = new File(testDir); + d.mkdirs(); + fService = new File(d + "/fs-serviceTEST.log"); + fService.createNewFile(); + fEtc = new File(d + "/org.osaaf.aaf.log4j.props"); + fEtc.createNewFile(); - aEnv = new AuthzEnv(); - aEnv.staticSlot("test"); - aEnv.access().setProperty("aaf_public_dir", "test"); - aEnv.access().setProperty(Config.AAF_LOCATOR_ENTRIES, "aaf_com"); + aEnv = new AuthzEnv(); + aEnv.staticSlot("test"); + aEnv.access().setProperty("aaf_public_dir", "test"); + aEnv.access().setProperty(Config.AAF_LOCATOR_ENTRIES, "aaf_com"); aEnv.access().setProperty(Config.AAF_LOCATOR_VERSION, "1.1"); - Server serverMock = mock(Server.class); - JettyServiceStarter<AuthzEnv, AuthzTrans> jssMock = mock(JettyServiceStarter.class); - aafFs = new AAF_FS(aEnv); - aEnv.access().setProperty(Config.AAF_LOCATE_URL, "aaf_loc:ate.url"); - aafFs = new AAF_FS(aEnv); - } + Server serverMock = mock(Server.class); + JettyServiceStarter<AuthzEnv, AuthzTrans> jssMock = mock(JettyServiceStarter.class); + aafFs = new AAF_FS(aEnv); + aEnv.access().setProperty(Config.AAF_LOCATE_URL, "aaf_loc:ate.url"); + aafFs = new AAF_FS(aEnv); + } - @Test - public void testRegistrants() throws CadiException, LocatorException { - int port = 8008; - aEnv.access().setProperty(Config.AAF_URL, "www.google.com"); - aEnv.access().setProperty(Config.CADI_LATITUDE, "38.550674"); - aEnv.access().setProperty(Config.CADI_LONGITUDE, "-90.146942"); - aEnv.access().setProperty(Config.AAF_LOCATE_URL, "testLocateUrl"); - aEnv.access().setProperty(Config.HOSTNAME, "testHost"); + @Test + public void testRegistrants() throws CadiException, LocatorException { + int port = 8008; + aEnv.access().setProperty(Config.AAF_URL, "www.google.com"); + aEnv.access().setProperty(Config.CADI_LATITUDE, "38.550674"); + aEnv.access().setProperty(Config.CADI_LONGITUDE, "-90.146942"); + aEnv.access().setProperty(Config.AAF_LOCATE_URL, "testLocateUrl"); + aEnv.access().setProperty(Config.HOSTNAME, "testHost"); - // Doesn't work within Jenkins - Registrant<AuthzEnv>[] registrants = aafFs.registrants(port); - assertNotNull(registrants); - } + // Doesn't work within Jenkins + Registrant<AuthzEnv>[] registrants = aafFs.registrants(port); + assertNotNull(registrants); + } - @Test - public void testFilters() throws CadiException, LocatorException { - aafFs.filters(); - } + @Test + public void testFilters() throws CadiException, LocatorException { + aafFs.filters(); + } - @Test - public void testMain() { - System.setProperty("cadi_exitOnFailure", "false"); + @Test + public void testMain() { + System.setProperty("cadi_exitOnFailure", "false"); - String[] strArr = { "aaf_component=aaf_com:po.nent" }; - try { - AAF_FS.main(strArr); // Timeout caused in Jenkins but not in local - } catch (Exception e) { - // Failure expected until we understand how code is. - } - } + String[] strArr = { "aaf_component=aaf_com:po.nent" }; + try { + AAF_FS.main(strArr); // Timeout caused in Jenkins but not in local + } catch (Exception e) { + // Failure expected until we understand how code is. + } + } - @After - public void cleanUp() { - for (File f : d.listFiles()) { - f.delete(); - } - d.delete(); - System.setErr(System.err); - System.setOut(System.out); - } + @After + public void cleanUp() { + for (File f : d.listFiles()) { + f.delete(); + } + d.delete(); + System.setErr(System.err); + System.setOut(System.out); + } } 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 f2d7522e..cb44ab09 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 @@ -88,11 +88,11 @@ public class CUI extends HttpCode<AuthzTrans, Void> { try { aafcli.eval(cmdStr); if(userPerm.matcher(cmdStr).matches()) { - trans.clearCache(); - Cookie cookie = new Cookie(Page.AAF_THEME,trans.getProperty(Page.AAF_THEME)); - cookie.setMaxAge(-1); - cookie.setComment("Remove AAF GUI Theme"); - trans.hresp().addCookie(cookie); + trans.clearCache(); + Cookie cookie = new Cookie(Page.AAF_THEME,trans.getProperty(Page.AAF_THEME)); + cookie.setMaxAge(-1); + cookie.setComment("Remove AAF GUI Theme"); + trans.hresp().addCookie(cookie); } pw.flush(); } catch (Exception e) { 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 17916c24..e1870e94 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 @@ -129,7 +129,7 @@ public class AAF_GUI extends AbsService<AuthzEnv, AuthzTrans> implements State<E sThemeWebPath = env.staticSlot(CachingFileAccess.CFA_WEB_PATH); if(env.get(sThemeWebPath)==null) { - env.put(sThemeWebPath,"theme"); + env.put(sThemeWebPath,"theme"); } slot_httpServletRequest = env.slot(HTTP_SERVLET_REQUEST); @@ -211,20 +211,20 @@ public class AAF_GUI extends AbsService<AuthzEnv, AuthzTrans> implements State<E route(env, PUT, "/gui/cui", new CUI(this),"text/plain;charset=utf-8","*/*"); route(env, GET, "/gui/clear", new HttpCode<AuthzTrans, Void>(null, "Clear"){ - @Override - public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - trans.clearCache(); - Cookie cookies[] = req.getCookies(); - if(cookies!=null) { - for(Cookie c : cookies) { - if(c.getName().startsWith("aaf.gui.")) { - c.setMaxAge(0); - resp.addCookie(c); - } - } - } - resp.sendRedirect("/gui/home"); - } + @Override + public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { + trans.clearCache(); + Cookie cookies[] = req.getCookies(); + if(cookies!=null) { + for(Cookie c : cookies) { + if(c.getName().startsWith("aaf.gui.")) { + c.setMaxAge(0); + resp.addCookie(c); + } + } + } + resp.sendRedirect("/gui/home"); + } }, "text/plain;charset=utf-8","*/*"); /////////////////////// @@ -287,11 +287,11 @@ public class AAF_GUI extends AbsService<AuthzEnv, AuthzTrans> implements State<E try { new JettyServiceStarter<AuthzEnv,AuthzTrans>( - new AAF_GUI(new AuthzEnv(propAccess)),true) - .start(); - } catch (Exception e) { - propAccess.log(e); - } + new AAF_GUI(new AuthzEnv(propAccess)),true) + .start(); + } catch (Exception e) { + propAccess.log(e); + } } catch (Exception e) { e.printStackTrace(); } 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 877974bd..24262e8f 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 @@ -99,9 +99,9 @@ public class Display { for (int i=0; i<slots.length;++i) { int idx = fields[i].indexOf("[]"); if (idx<0) { // single value - if(asUser(trans, req,fields[i])) { - trans.put(slots[i], req.getParameter(fields[i])); - } + if(asUser(trans, req,fields[i])) { + trans.put(slots[i], req.getParameter(fields[i])); + } } else { // multi value String[] array = new String[30]; String field=fields[i].substring(0, idx); @@ -132,13 +132,13 @@ public class Display { * When the field is "as_user", make sure permission is granted */ private boolean asUser(AuthzTrans trans, HttpServletRequest req, String field) { - if("as_user".equals(field)) { - return req.isUserInRole(Define.ROOT_NS()+"|access|*|*"); - } - return true; - } + if("as_user".equals(field)) { + return req.isUserInRole(Define.ROOT_NS()+"|access|*|*"); + } + return true; + } - @Override + @Override public boolean no_cache() { return no_cache; } 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 9abd5ee0..96c0fc48 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 @@ -97,17 +97,17 @@ public class Page extends HTMLCacheGen { * Relative path, Menu Name, Full Path */ protected static final String[][] MENU_ITEMS = new String[][] { - {"myperms","My Permissions","/gui/myperms"}, - {"myroles","My Roles","/gui/myroles"}, - {"ns","My Namespaces","/gui/ns"}, - {"approve","My Approvals","/gui/approve"}, - {"myrequests","My Pending Requests","/gui/myrequests"}, - // Enable later - // {"onboard","Onboarding"}, - {"passwd","Password Management","/gui/passwd"}, - {"cui","Command Prompt","/gui/cui"}, - {"api","AAF API","/gui/api"}, - {"clear","Clear Preferences","/gui/clear"} + {"myperms","My Permissions","/gui/myperms"}, + {"myroles","My Roles","/gui/myroles"}, + {"ns","My Namespaces","/gui/ns"}, + {"approve","My Approvals","/gui/approve"}, + {"myrequests","My Pending Requests","/gui/myrequests"}, + // Enable later + // {"onboard","Onboarding"}, + {"passwd","Password Management","/gui/passwd"}, + {"cui","Command Prompt","/gui/cui"}, + {"api","AAF API","/gui/api"}, + {"clear","Clear Preferences","/gui/clear"} }; public String name() { @@ -168,16 +168,16 @@ public class Page extends HTMLCacheGen { private static class PageCode implements Code<HTMLGen> { - private static final String AAF_GUI_THEME = "aaf.gui.theme"; - private static final String AAF_GUI_TITLE = "aaf_gui_title"; + private static final String AAF_GUI_THEME = "aaf.gui.theme"; + private static final String AAF_GUI_TITLE = "aaf_gui_title"; private final ContentCode[] content; private final Slot browserSlot; private final int backdots; protected AuthzEnv env; private StaticSlot sTheme; - private static Map<String,List<String>> themes; - private static Map<String,Properties> themeProps; + private static Map<String,List<String>> themes; + private static Map<String,Properties> themeProps; public PageCode(AuthzEnv env, int backdots, final ContentCode[] content) { this.content = content; @@ -185,78 +185,78 @@ public class Page extends HTMLCacheGen { browserSlot = env.slot(BROWSER_TYPE); sTheme = env.staticSlot(AAF_GUI.AAF_GUI_THEME); this.env = env; - getThemeFiles(env,""); // + getThemeFiles(env,""); // } private static synchronized List<String> getThemeFiles(Env env, String theme) { - if(themes==null) { - themes = new TreeMap<>(); + if(themes==null) { + themes = new TreeMap<>(); File themeD = new File("theme"); if(themeD.exists() && themeD.isDirectory()) { - for (File t : themeD.listFiles()) { - if(t.isDirectory()) { - List<String> la = new ArrayList<>(); - for(File f : t.listFiles()) { - if(f.isFile()) { - if(f.getName().endsWith(".props")) { - Properties props; - if(themeProps == null) { - themeProps = new TreeMap<>(); - props = null; - } else { - props = themeProps.get(t.getName()); - } - if(props==null) { - props = new Properties(); - themeProps.put(t.getName(), props); - } - - try { - FileInputStream fis = new FileInputStream(f); - try { - props.load(fis); - } finally { - fis.close(); - } - } catch (IOException e) { - env.error().log(e); - } - } else { - la.add(f.getName()); - } - } - } - themes.put(t.getName(),la); - } - } + for (File t : themeD.listFiles()) { + if(t.isDirectory()) { + List<String> la = new ArrayList<>(); + for(File f : t.listFiles()) { + if(f.isFile()) { + if(f.getName().endsWith(".props")) { + Properties props; + if(themeProps == null) { + themeProps = new TreeMap<>(); + props = null; + } else { + props = themeProps.get(t.getName()); + } + if(props==null) { + props = new Properties(); + themeProps.put(t.getName(), props); + } + + try { + FileInputStream fis = new FileInputStream(f); + try { + props.load(fis); + } finally { + fis.close(); + } + } catch (IOException e) { + env.error().log(e); + } + } else { + la.add(f.getName()); + } + } + } + themes.put(t.getName(),la); + } + } } - } - return themes.get(theme); + } + return themes.get(theme); } protected Imports getImports(Env env, String theme, int backdots, BROWSER browser) { - List<String> ls = getThemeFiles(env,theme); - Imports imp = new Imports(backdots); - String prefix = "theme/" + theme + '/'; - for(String f : ls) { - if(f.endsWith(".js")) { - imp.js(prefix + f); - } else if(f.endsWith(".css")) { - if(f.endsWith("iPhone.css")) { - if(BROWSER.iPhone.equals(browser)) { - imp.css(prefix + f); - } - } else if (f.endsWith("Desktop.css")){ - if(!BROWSER.iPhone.equals(browser)) { - imp.css(prefix + f); - } - // Make Console specific to Console page - } else if (!"console.js".equals(f)) { - imp.css(prefix + f); - } - } - } - return imp; + List<String> ls = getThemeFiles(env,theme); + Imports imp = new Imports(backdots); + String prefix = "theme/" + theme + '/'; + for(String f : ls) { + if(f.endsWith(".js")) { + imp.js(prefix + f); + } else if(f.endsWith(".css")) { + if(f.endsWith("iPhone.css")) { + if(BROWSER.iPhone.equals(browser)) { + imp.css(prefix + f); + } + } else if (f.endsWith("Desktop.css")){ + if(!BROWSER.iPhone.equals(browser)) { + imp.css(prefix + f); + } + // Make Console specific to Console page + } else if (!"console.js".equals(f)) { + imp.css(prefix + f); + } + } + } + return imp; } @Override @@ -284,36 +284,36 @@ public class Page extends HTMLCacheGen { cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() { @Override public void code(AAF_GUI state, AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { - BROWSER browser = browser(trans,browserSlot); - String theme = null; - Cookie[] cookies = trans.hreq().getCookies(); - if(cookies!=null) { - for(Cookie c : cookies) { - if(AAF_GUI_THEME.equals(c.getName())) { - theme=c.getValue(); - if(!(themes.containsKey(theme))) { - theme = defaultTheme; - } - break; - } - } - } - - if(theme==null) { - for(String t : themes.keySet()) { - if(!t.equals(defaultTheme) && trans.fish(new AAFPermission(null,trans.user()+":id", AAF_GUI_THEME, t))) { - theme=t; - break; - } - } - if(theme==null) { - theme = defaultTheme; - } - Cookie cookie = new Cookie(AAF_GUI_THEME,theme); - cookie.setMaxAge(604_800); // one week - trans.hresp().addCookie(cookie); - } - trans.setProperty(Page.AAF_THEME, theme); + BROWSER browser = browser(trans,browserSlot); + String theme = null; + Cookie[] cookies = trans.hreq().getCookies(); + if(cookies!=null) { + for(Cookie c : cookies) { + if(AAF_GUI_THEME.equals(c.getName())) { + theme=c.getValue(); + if(!(themes.containsKey(theme))) { + theme = defaultTheme; + } + break; + } + } + } + + if(theme==null) { + for(String t : themes.keySet()) { + if(!t.equals(defaultTheme) && trans.fish(new AAFPermission(null,trans.user()+":id", AAF_GUI_THEME, t))) { + theme=t; + break; + } + } + if(theme==null) { + theme = defaultTheme; + } + Cookie cookie = new Cookie(AAF_GUI_THEME,theme); + cookie.setMaxAge(604_800); // one week + trans.hresp().addCookie(cookie); + } + trans.setProperty(Page.AAF_THEME, theme); hgen.imports(getImports(env,theme,backdots,browser)); switch(browser) { @@ -404,17 +404,17 @@ public class Page extends HTMLCacheGen { cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() { @Override public void code(AAF_GUI state, AuthzTrans trans,Cache<HTMLGen> cache, HTMLGen xgen) throws APIException, IOException { - String theme = trans.getProperty(Page.AAF_THEME); - Properties props; - if(theme==null) { - props = null; - } else { - props = themeProps==null?null:themeProps.get(theme); - } - - if(props!=null && "TRUE".equalsIgnoreCase(props.getProperty("enable_nav_btn"))) { - xgen.leaf("button", "id=navBtn").end(); - } + String theme = trans.getProperty(Page.AAF_THEME); + Properties props; + if(theme==null) { + props = null; + } else { + props = themeProps==null?null:themeProps.get(theme); + } + + if(props!=null && "TRUE".equalsIgnoreCase(props.getProperty("enable_nav_btn"))) { + xgen.leaf("button", "id=navBtn").end(); + } } }); // Adding "nav Hamburger button" @@ -423,64 +423,64 @@ public class Page extends HTMLCacheGen { cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI,AuthzTrans>() { @Override public void code(AAF_GUI state, AuthzTrans trans,Cache<HTMLGen> cache, HTMLGen xgen) throws APIException, IOException { - String theme = trans.getProperty(Page.AAF_THEME); - Properties props; - if(theme==null) { - props = null; - } else { - props = themeProps==null?null:themeProps.get(theme); - } - - if(props!=null) { - if("TRUE".equalsIgnoreCase(props.getProperty("main_menu_in_nav"))) { - xgen.incr("h2").text("Navigation").end(); - Mark mark = new Mark(); - boolean selected = isSelected(trans.path(),Home.HREF); - //trans.path().endsWith("home"); - xgen.incr(mark,HTMLGen.UL) - .incr(HTMLGen.LI,selected?"class=selected":"") - .incr(HTMLGen.A, "href=home") - .text("Home") - .end(2); - boolean noSelection = !selected; - for(String[] mi : MENU_ITEMS) { - //selected = trans.path().endsWith(mi[0]); - if(noSelection) { - selected = isSelected(trans.path(),mi[2]); - noSelection = !selected; - } else { - selected = false; - } - xgen.incr(HTMLGen.LI,selected?"class=selected":"") - .incr(HTMLGen.A, "href="+mi[2]) - .text(mi[1]) - .end(2); - } - xgen.end(mark); - } - } + String theme = trans.getProperty(Page.AAF_THEME); + Properties props; + if(theme==null) { + props = null; + } else { + props = themeProps==null?null:themeProps.get(theme); + } + + if(props!=null) { + if("TRUE".equalsIgnoreCase(props.getProperty("main_menu_in_nav"))) { + xgen.incr("h2").text("Navigation").end(); + Mark mark = new Mark(); + boolean selected = isSelected(trans.path(),Home.HREF); + //trans.path().endsWith("home"); + xgen.incr(mark,HTMLGen.UL) + .incr(HTMLGen.LI,selected?"class=selected":"") + .incr(HTMLGen.A, "href=home") + .text("Home") + .end(2); + boolean noSelection = !selected; + for(String[] mi : MENU_ITEMS) { + //selected = trans.path().endsWith(mi[0]); + if(noSelection) { + selected = isSelected(trans.path(),mi[2]); + noSelection = !selected; + } else { + selected = false; + } + xgen.incr(HTMLGen.LI,selected?"class=selected":"") + .incr(HTMLGen.A, "href="+mi[2]) + .text(mi[1]) + .end(2); + } + xgen.end(mark); + } + } } - private boolean isSelected(String path, String item) { - if(item.equals(path)) { - return true; - } else { - for(ContentCode c : content) { - if(c instanceof BreadCrumbs) { - Page[] bc = ((BreadCrumbs)c).breadcrumbs; - if(bc!=null) { - for(int i = bc.length-1;i>0;--i) { - if(bc[i].url().equals(item)) { - return true; - } - } - return false; - } - } - } - } - return false; - } + private boolean isSelected(String path, String item) { + if(item.equals(path)) { + return true; + } else { + for(ContentCode c : content) { + if(c instanceof BreadCrumbs) { + Page[] bc = ((BreadCrumbs)c).breadcrumbs; + if(bc!=null) { + for(int i = bc.length-1;i>0;--i) { + if(bc[i].url().equals(item)) { + return true; + } + } + return false; + } + } + } + } + return false; + } }); hgen.incr("h2").text("Related Links").end(); hgen.incr(UL); 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 332ecafe..cb868b16 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 @@ -121,7 +121,7 @@ public class ApprovalForm extends Page { private static final String[] headers = new String[] {"Identity","Request","Approve","Deny"}; private Slot sUser; private Slot sAsDelegate; - private Slot sAsUser; + private Slot sAsUser; public Model(AuthzEnv env) { sUser = env.slot(NAME+".user"); @@ -141,9 +141,9 @@ public class ApprovalForm extends Page { final String asDelegate = trans.get(sAsDelegate, null); final String approver; if(asDelegate==null) { - approver = trans.get(sAsUser,trans.user()); + approver = trans.get(sAsUser,trans.user()); } else { - approver = asDelegate; + approver = asDelegate; } ArrayList<AbsCell[]> rv = new ArrayList<>(); @@ -207,107 +207,107 @@ public class ApprovalForm extends Page { Identity iapprover = trans.org().getIdentity(trans,currApproverList.get(0).getApprover()); if(iapprover==null) { - rv.add(new AbsCell[] { - new TextCell(currApproverList.get(0).getApprover() + " is not part of Organization", + rv.add(new AbsCell[] { + new TextCell(currApproverList.get(0).getApprover() + " is not part of Organization", new String[] {"colspan=4", "class=head"}) - }); + }); } else { - if (!iapprover.fullID().equals(trans.user())) { - - AbsCell[] approverHeader; - // if (domainOfUser.equals(domainOfApprover)) { - // approverHeader = new AbsCell[] { - // new TextAndRefCell("Approvals Delegated to Me by ", currApproverFull, - // TODO_ILM_INFO + currApproverShort, - // true, - // new String[] {"colspan=4", "class=head"}) - // }; - // } else { - approverHeader = new AbsCell[] { - new TextCell("Approvals Delegated to Me by " + iapprover.fullName() - + '(' + iapprover.id() + ')', - new String[] {"colspan=4", "class=head"}) - }; - // } - rv.add(approverHeader); - } - - // Sort by User Requesting - Collections.sort(currApproverList, new Comparator<Approval>() { - @Override - public int compare(Approval a1, Approval a2) { - return a1.getUser().compareTo(a2.getUser()); - } - }); - - String prevUser = null; - boolean userOK=true; - for (Approval appr : currApproverList) { - if (++line<MAX_LINE) { // limit number displayed at one time. - AbsCell userCell; - String user = appr.getUser(); - - if (user.equals(prevUser)) { - userCell = AbsCell.Null; - } else if (user.endsWith(trans.org().getRealm())){ - userOK=true; - String title; - Organization org = OrganizationFactory.obtain(trans.env(), user); - if (org==null) { - title=""; - userCell = new TextCell(user); - } else { - Identity au = org.getIdentity(trans, user); - if (au!=null) { - if(au.isPerson()) { - userCell = new TextToolTipCell(au.fullName(),"Identity: " + au.id()); - } else { - Identity managedBy = au.responsibleTo(); - if (managedBy==null) { - title ="Identity: " + au.type(); - } else { - title="Sponsor: " + managedBy.fullName(); - } - userCell = new TextToolTipCell(au.fullID(),title); - } - } else { - userOK=false; - title="Not a User at " + org.getName(); - userCell = new TextToolTipCell(user,title); - } - } - // userCell = new RefCell(prevUser, - // TODO_ILM_INFO+user.substring(0, user.length()-domainOfApprover.length()), - // true, - // title); - - } else { - userCell = new TextCell(user); - } - AbsCell[] sa = new AbsCell[] { - userCell, - new TextCell(appr.getMemo()), - userOK?new RadioCell("line."+ line,"approve", "approved|"+appr.getTicket()):new TextCell(""), - new RadioCell("line."+ line,"deny", "denied|"+appr.getTicket()) - }; - rv.add(sa); + if (!iapprover.fullID().equals(trans.user())) { + + AbsCell[] approverHeader; + // if (domainOfUser.equals(domainOfApprover)) { + // approverHeader = new AbsCell[] { + // new TextAndRefCell("Approvals Delegated to Me by ", currApproverFull, + // TODO_ILM_INFO + currApproverShort, + // true, + // new String[] {"colspan=4", "class=head"}) + // }; + // } else { + approverHeader = new AbsCell[] { + new TextCell("Approvals Delegated to Me by " + iapprover.fullName() + + '(' + iapprover.id() + ')', + new String[] {"colspan=4", "class=head"}) + }; + // } + rv.add(approverHeader); + } + + // Sort by User Requesting + Collections.sort(currApproverList, new Comparator<Approval>() { + @Override + public int compare(Approval a1, Approval a2) { + return a1.getUser().compareTo(a2.getUser()); + } + }); + + String prevUser = null; + boolean userOK=true; + for (Approval appr : currApproverList) { + if (++line<MAX_LINE) { // limit number displayed at one time. + AbsCell userCell; + String user = appr.getUser(); + + if (user.equals(prevUser)) { + userCell = AbsCell.Null; + } else if (user.endsWith(trans.org().getRealm())){ + userOK=true; + String title; + Organization org = OrganizationFactory.obtain(trans.env(), user); + if (org==null) { + title=""; + userCell = new TextCell(user); + } else { + Identity au = org.getIdentity(trans, user); + if (au!=null) { + if(au.isPerson()) { + userCell = new TextToolTipCell(au.fullName(),"Identity: " + au.id()); + } else { + Identity managedBy = au.responsibleTo(); + if (managedBy==null) { + title ="Identity: " + au.type(); + } else { + title="Sponsor: " + managedBy.fullName(); + } + userCell = new TextToolTipCell(au.fullID(),title); + } + } else { + userOK=false; + title="Not a User at " + org.getName(); + userCell = new TextToolTipCell(user,title); + } + } + // userCell = new RefCell(prevUser, + // TODO_ILM_INFO+user.substring(0, user.length()-domainOfApprover.length()), + // true, + // title); + + } else { + userCell = new TextCell(user); + } + AbsCell[] sa = new AbsCell[] { + userCell, + new TextCell(appr.getMemo()), + userOK?new RadioCell("line."+ line,"approve", "approved|"+appr.getTicket()):new TextCell(""), + new RadioCell("line."+ line,"deny", "denied|"+appr.getTicket()) + }; + rv.add(sa); prevUser=user; - } else { - ++numLeft; - } - } - } - if (numLeft>0) { - msg = "After these, there will be " + numLeft + " approvals left to process"; - } - if (rv.isEmpty()) { - if (numLeft>0) { - msg = "No Approvals to process at this time for user " + userParam +". You have " - + numLeft + " other approvals to process."; - } else { - msg = "No Approvals to process at this time"; - } - } + } else { + ++numLeft; + } + } + } + if (numLeft>0) { + msg = "After these, there will be " + numLeft + " approvals left to process"; + } + if (rv.isEmpty()) { + if (numLeft>0) { + msg = "No Approvals to process at this time for user " + userParam +". You have " + + numLeft + " other approvals to process."; + } else { + msg = "No Approvals to process at this time"; + } + } } } catch (Exception e) { trans.error().log(e); 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 f67f6d5c..c6821199 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 @@ -73,7 +73,7 @@ public class CMArtiChangeAction extends Page { cache.dynamic(hgen, new DynamicCode<HTMLGen,AAF_GUI, AuthzTrans>() { @Override public void code(final AAF_GUI gui, final AuthzTrans trans,final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { - trans.info().log("Step 1"); + trans.info().log("Step 1"); final Artifact arti = new Artifact(); final String machine = trans.get(sMachine,null); final String ca = trans.get(sCA, null); @@ -86,26 +86,26 @@ public class CMArtiChangeAction extends Page { // These checks to not apply to deletions if(!CMArtiChangeForm.DELETE.equals(trans.get(sCmd, ""))) { - // Disallow IP entries, except by special Permission - if (!trans.fish(getPerm(ca,"ip"))) { - boolean ok=true; - if (IPValidator.ip(machine)) { - ok=false; - } - if (ok) { - for (String s: arti.getSans()) { - if (IPValidator.ip(s)) { - ok=false; - break; - } - } - } - if (!ok) { - hgen.p("Policy Failure: IPs in certificates are only allowed by Exception."); - return; - } - } - + // Disallow IP entries, except by special Permission + if (!trans.fish(getPerm(ca,"ip"))) { + boolean ok=true; + if (IPValidator.ip(machine)) { + ok=false; + } + if (ok) { + for (String s: arti.getSans()) { + if (IPValidator.ip(s)) { + ok=false; + break; + } + } + } + if (!ok) { + hgen.p("Policy Failure: IPs in certificates are only allowed by Exception."); + return; + } + } + } arti.setMechid((String)trans.get(sID,null)); @@ -192,18 +192,18 @@ public class CMArtiChangeAction extends Page { if(f.body().contains("%") ) { hgen.p(Vars.convert(err.getText(),err.getVariables())); } else { - int colon = err.getText().indexOf(':'); - if(colon>0) { - hgen.p(err.getMessageId() + ": " + err.getText().substring(0, colon)); - Mark bq = new Mark(); - hgen.incr(bq,"blockquote"); - for(String em : Split.splitTrim('\n', err.getText().substring(colon+1))) { - hgen.p(em); - } - hgen.end(bq); - } else { - hgen.p(err.getMessageId() + ": " + err.getText()); - } + int colon = err.getText().indexOf(':'); + if(colon>0) { + hgen.p(err.getMessageId() + ": " + err.getText().substring(0, colon)); + Mark bq = new Mark(); + hgen.incr(bq,"blockquote"); + for(String em : Split.splitTrim('\n', err.getText().substring(colon+1))) { + hgen.p(em); + } + hgen.end(bq); + } else { + hgen.p(err.getMessageId() + ": " + err.getText()); + } } } else { hgen.p(arti.getMechid() + " on " + arti.getMachine() + ": " + f.body()); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java index 73e118a2..3553da2b 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/Home.java @@ -38,7 +38,7 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; public class Home extends Page { public static final String HREF = "/gui/home"; - public Home(final AAF_GUI gui) throws APIException, IOException { + public Home(final AAF_GUI gui) throws APIException, IOException { super(gui.env,"Home",HREF, NO_FIELDS, new NamedCode(false,"content") { @Override public void code(final Cache<HTMLGen> cache, final HTMLGen htmlGen) throws APIException, IOException { @@ -57,7 +57,7 @@ public class Home extends Page { final Mark pages = htmlGen.divID("Pages"); htmlGen.leaf(H3).text("Choose from the following:").end(); for(String[] mi : MENU_ITEMS) { - htmlGen.leaf(A,"href="+mi[0]).text(mi[1]).end(); + htmlGen.leaf(A,"href="+mi[0]).text(mi[1]).end(); } htmlGen.end(pages); } 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 ae5fe375..585a75ae 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 @@ -72,53 +72,53 @@ public class PendingRequestsShow extends Page { } private static final class TopOfPage extends NamedCode { - private Slot sAsUser; + private Slot sAsUser; - private TopOfPage(AuthzEnv env, boolean no_cache, String name) { - super(no_cache, name); - sAsUser = env.slot(AS_USER); - } + private TopOfPage(AuthzEnv env, boolean no_cache, String name) { + super(no_cache, name); + sAsUser = env.slot(AS_USER); + } - @Override - public void code(final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { - cache.dynamic(hgen, new DynamicCode<HTMLGen, AAF_GUI, AuthzTrans>() { - @Override - public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { - String user = trans.get(sAsUser,null); - if(user==null) { - user=trans.user(); - } else { - hgen.incr(HTMLGen.H3,"class=center").text("Displaying for " + user).end(); - } + @Override + public void code(final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { + cache.dynamic(hgen, new DynamicCode<HTMLGen, AAF_GUI, AuthzTrans>() { + @Override + public void code(final AAF_GUI gui, final AuthzTrans trans, final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { + String user = trans.get(sAsUser,null); + if(user==null) { + user=trans.user(); + } else { + hgen.incr(HTMLGen.H3,"class=center").text("Displaying for " + user).end(); + } - hgen - .leaf(HTMLGen.P, "class=expedite_request").text("These are your submitted Requests that are awaiting Approval. ") - .br() - .text("To Expedite a Request: ") - .leaf("a","href=#expedite_directions","onclick=divVisibility('expedite_directions');") - .text("Click Here").end() - .divID("expedite_directions", "style=display:none"); - - hgen - .incr(HTMLGen.OL) - .incr(HTMLGen.LI) - .leaf("a","href="+ApprovalForm.HREF+"?user="+user, "id=userApprove") - .text("Copy This Link") - .end() - .end() - .incr(HTMLGen.LI) - .text("Send it to the Approver Listed") - .end() - .end() - .text("NOTE: Using this link, the Approver will only see your requests. You only need to send this link once!") - .end() - .end(); - } - }); + hgen + .leaf(HTMLGen.P, "class=expedite_request").text("These are your submitted Requests that are awaiting Approval. ") + .br() + .text("To Expedite a Request: ") + .leaf("a","href=#expedite_directions","onclick=divVisibility('expedite_directions');") + .text("Click Here").end() + .divID("expedite_directions", "style=display:none"); + + hgen + .incr(HTMLGen.OL) + .incr(HTMLGen.LI) + .leaf("a","href="+ApprovalForm.HREF+"?user="+user, "id=userApprove") + .text("Copy This Link") + .end() + .end() + .incr(HTMLGen.LI) + .text("Send it to the Approver Listed") + .end() + .end() + .text("NOTE: Using this link, the Approver will only see your requests. You only need to send this link once!") + .end() + .end(); + } + }); } - } + } - /** + /** * Implement the Table Content for Requests by User * * @author Jeremiah @@ -126,7 +126,7 @@ public class PendingRequestsShow extends Page { */ private static class Model extends TableData<AAF_GUI,AuthzTrans> { final long NUM_100NS_INTERVALS_SINCE_UUID_EPOCH = 0x01b21dd213814000L; - private final Slot sAsUser; + private final Slot sAsUser; private static final String[] headers = new String[] {"Request Date","Status","Memo","Approver"}; public Model(AuthzEnv env) { @@ -145,7 +145,7 @@ public class PendingRequestsShow extends Page { gui.clientAsUser(trans.getUserPrincipal(), new Retryable<Void>() { @Override public Void code(Rcli<?> client)throws CadiException, ConnectException, APIException { - final String user = trans.get(sAsUser,trans.user()); + final String user = trans.get(sAsUser,trans.user()); TimeTaken tt = trans.start("AAF Get Approvals by User",Env.REMOTE); try { 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 8628d4be..8b6c1376 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 @@ -97,18 +97,18 @@ public class RequestDetail extends Page { ); if (fa.get(AAF_GUI.TIMEOUT)) { - Approval app = fa.value.getApprovals().get(0); - if(app==null) { - return Cells.EMPTY; - } else { - if (!(trans.user().equals(app.getUser()) || - trans.user().equals(app.getApprover()))) { - HttpServletRequest req = trans.get(gui.slot_httpServletRequest,null); - if(req==null || !req.isUserInRole(Define.ROOT_NS()+"|access|*|*")) { - return Cells.EMPTY; - } - } - } + Approval app = fa.value.getApprovals().get(0); + if(app==null) { + return Cells.EMPTY; + } else { + if (!(trans.user().equals(app.getUser()) || + trans.user().equals(app.getApprover()))) { + HttpServletRequest req = trans.get(gui.slot_httpServletRequest,null); + if(req==null || !req.isUserInRole(Define.ROOT_NS()+"|access|*|*")) { + return Cells.EMPTY; + } + } + } tt.done(); tt = trans.start("Load Data", Env.SUB); boolean first = true; 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 6588de54..dcf0f928 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,9 +107,9 @@ public class RoleDetail extends Page { final String pRole = trans.get(sRoleName, null); Validator v = new Validator(); if(!v.isNull("Role",pRole).err()) { - if(!pRole.startsWith(trans.user())) { - v.role(pRole); - } + if(!pRole.startsWith(trans.user())) { + v.role(pRole); + } } if (v.err()) { trans.warn().printf("Error in PermDetail Request: %s", v.errs()); diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java index d0e834a5..73f4981c 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/pages/WebCommand.java @@ -43,8 +43,8 @@ public class WebCommand extends Page { super(gui.env, "Web Command Client",HREF, NO_FIELDS, new BreadCrumbs(breadcrumbs), new NamedCode(true, "content") { - StaticSlot sThemeWebPath = gui.env.staticSlot(CachingFileAccess.CFA_WEB_PATH); - StaticSlot sTheme = gui.env.staticSlot(AAF_GUI.AAF_GUI_THEME); + StaticSlot sThemeWebPath = gui.env.staticSlot(CachingFileAccess.CFA_WEB_PATH); + StaticSlot sTheme = gui.env.staticSlot(AAF_GUI.AAF_GUI_THEME); @Override public void code(final Cache<HTMLGen> cache, final HTMLGen hgen) throws APIException, IOException { hgen.leaf("p","id=help_msg") @@ -64,7 +64,7 @@ public class WebCommand extends Page { @Override public void code(AAF_GUI state, AuthzTrans trans, Cache<HTMLGen> cache, HTMLGen xgen) throws APIException, IOException { - String image_root = "src=../../"+state.env.get(sThemeWebPath).toString() + '/' + state.env.get(sTheme) + "/images/icons"; + String image_root = "src=../../"+state.env.get(sThemeWebPath).toString() + '/' + state.env.get(sTheme) + "/images/icons"; hgen.img(image_root + "/options_down.png", "onclick=handleDivHiding('options',this);", "id=options_img", "alt=Options", "title=Options") .end(); //options_link diff --git a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextToolTipCell.java b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextToolTipCell.java index 986b8245..5eaa69d1 100644 --- a/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextToolTipCell.java +++ b/auth/auth-gui/src/main/java/org/onap/aaf/auth/gui/table/TextToolTipCell.java @@ -31,7 +31,7 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; public class TextToolTipCell extends AbsCell { public final String name; private final String[] attrs; - private final String tooltip; + private final String tooltip; public TextToolTipCell(String name, String tooltip, String... attributes) { attrs = attributes; diff --git a/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_FormTest.java b/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_FormTest.java index 0f348f39..fa95bc25 100644 --- a/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_FormTest.java +++ b/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_FormTest.java @@ -33,31 +33,31 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; public class JU_FormTest { - @Mock - private Cache<HTMLGen> cache; + @Mock + private Cache<HTMLGen> cache; - @Mock - private HTMLGen hgen; + @Mock + private HTMLGen hgen; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void test() throws Exception { - when(hgen.incr("p", "class=preamble")).thenReturn(hgen); - when(hgen.text("preamable")).thenReturn(hgen); - when(hgen.tagOnly("input", "type=submit", "value=Submit")).thenReturn(hgen); - when(hgen.tagOnly("input", "type=reset", "value=Reset")).thenReturn(hgen); + @Test + public void test() throws Exception { + when(hgen.incr("p", "class=preamble")).thenReturn(hgen); + when(hgen.text("preamable")).thenReturn(hgen); + when(hgen.tagOnly("input", "type=submit", "value=Submit")).thenReturn(hgen); + when(hgen.tagOnly("input", "type=reset", "value=Reset")).thenReturn(hgen); - Form form = new Form(false, new BreadCrumbs(null)); + Form form = new Form(false, new BreadCrumbs(null)); - assertThat(form.idattrs(), equalTo(new String[] { "breadcrumbs" })); + assertThat(form.idattrs(), equalTo(new String[] { "breadcrumbs" })); - assertThat(form.preamble("preamable"), equalTo(form)); + assertThat(form.preamble("preamable"), equalTo(form)); - form.code(cache, hgen); - } + form.code(cache, hgen); + } } diff --git a/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_TableTest.java b/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_TableTest.java index b13f6d30..ec39916b 100644 --- a/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_TableTest.java +++ b/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/JU_TableTest.java @@ -39,33 +39,33 @@ import org.onap.aaf.misc.xgen.html.HTMLGen; public class JU_TableTest { - @Mock - private TransStore trans; - private Code<HTMLGen> other; - @Mock - private Data data; - @Mock - private Cache cache; - @Mock - private HTMLGen hgen; + @Mock + private TransStore trans; + private Code<HTMLGen> other; + @Mock + private Data data; + @Mock + private Cache cache; + @Mock + private HTMLGen hgen; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void test() throws APIException, IOException { - when(hgen.leaf("caption", "class=title")).thenReturn(hgen); - when(hgen.text("title")).thenReturn(hgen); - when(data.headers()).thenReturn(new String[0]); + @Test + public void test() throws APIException, IOException { + when(hgen.leaf("caption", "class=title")).thenReturn(hgen); + when(hgen.text("title")).thenReturn(hgen); + when(data.headers()).thenReturn(new String[0]); - Table table = new Table("title", trans, data, other, "name", "attr1", "attr1"); - Table.Cells cells = new Table.Cells(new ArrayList(), ""); + Table table = new Table("title", trans, data, other, "name", "attr1", "attr1"); + Table.Cells cells = new Table.Cells(new ArrayList(), ""); - table.code(cache, hgen); + table.code(cache, hgen); - verify(hgen).end(); - } + verify(hgen).end(); + } } diff --git a/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/table/JU_UICellTest.java b/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/table/JU_UICellTest.java index c6b92f7c..3cf6b723 100644 --- a/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/table/JU_UICellTest.java +++ b/auth/auth-gui/src/test/java/org/onap/aaf/auth/gui/table/JU_UICellTest.java @@ -34,137 +34,137 @@ import org.onap.aaf.auth.gui.table.CheckBoxCell.ALIGN; import org.onap.aaf.misc.xgen.html.HTMLGen; public class JU_UICellTest { - @Mock - private HTMLGen hgen; + @Mock + private HTMLGen hgen; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void testButtonCell() { - String[] attrs = { "type=button", "value=null", "attribute1", "attribute2" }; - ButtonCell cell = new ButtonCell(null, "attribute1", "attribute2"); + @Test + public void testButtonCell() { + String[] attrs = { "type=button", "value=null", "attribute1", "attribute2" }; + ButtonCell cell = new ButtonCell(null, "attribute1", "attribute2"); - when(hgen.incr("input", true, attrs)).thenReturn(hgen); + when(hgen.incr("input", true, attrs)).thenReturn(hgen); - cell.write(hgen); + cell.write(hgen); - AbsCell.Null.write(hgen); + AbsCell.Null.write(hgen); - assertThat(AbsCell.Null.attrs(), equalTo(new String[0])); + assertThat(AbsCell.Null.attrs(), equalTo(new String[0])); - assertThat(cell.attrs(), equalTo(AbsCell.CENTER)); + assertThat(cell.attrs(), equalTo(AbsCell.CENTER)); - verify(hgen).end(); - } + verify(hgen).end(); + } - @Test - public void testCheckBoxCellWithoutAlign() { - String[] attrs = { "type=checkbox", "name=name", "value=attribute1", "attribute2" }; - CheckBoxCell cell = new CheckBoxCell("name", "attribute1", "attribute2"); + @Test + public void testCheckBoxCellWithoutAlign() { + String[] attrs = { "type=checkbox", "name=name", "value=attribute1", "attribute2" }; + CheckBoxCell cell = new CheckBoxCell("name", "attribute1", "attribute2"); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(AbsCell.CENTER)); + assertThat(cell.attrs(), equalTo(AbsCell.CENTER)); - verify(hgen).tagOnly("input", attrs); - } + verify(hgen).tagOnly("input", attrs); + } - @Test - public void testCheckBoxCellWithLeftAlign() { - String[] attrs = { "type=checkbox", "name=name", "value=attribute1", "attribute2" }; - CheckBoxCell cell = new CheckBoxCell("name", ALIGN.left, "attribute1", "attribute2"); + @Test + public void testCheckBoxCellWithLeftAlign() { + String[] attrs = { "type=checkbox", "name=name", "value=attribute1", "attribute2" }; + CheckBoxCell cell = new CheckBoxCell("name", ALIGN.left, "attribute1", "attribute2"); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(AbsCell.LEFT)); + assertThat(cell.attrs(), equalTo(AbsCell.LEFT)); - verify(hgen).tagOnly("input", attrs); - } + verify(hgen).tagOnly("input", attrs); + } - @Test - public void testCheckBoxCellWithRightAlign() { - String[] attrs = { "type=checkbox", "name=name", "value=attribute1", "attribute2" }; - CheckBoxCell cell = new CheckBoxCell("name", ALIGN.right, "attribute1", "attribute2"); + @Test + public void testCheckBoxCellWithRightAlign() { + String[] attrs = { "type=checkbox", "name=name", "value=attribute1", "attribute2" }; + CheckBoxCell cell = new CheckBoxCell("name", ALIGN.right, "attribute1", "attribute2"); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(AbsCell.RIGHT)); + assertThat(cell.attrs(), equalTo(AbsCell.RIGHT)); - verify(hgen).tagOnly("input", attrs); - } + verify(hgen).tagOnly("input", attrs); + } - @Test - public void testRadioCell() { - String[] attrs = { "type=radio", "name=name", "class=attribute1", "value=attribute2" }; - RadioCell cell = new RadioCell("name", "attribute1", "attribute2"); + @Test + public void testRadioCell() { + String[] attrs = { "type=radio", "name=name", "class=attribute1", "value=attribute2" }; + RadioCell cell = new RadioCell("name", "attribute1", "attribute2"); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(AbsCell.CENTER)); + assertThat(cell.attrs(), equalTo(AbsCell.CENTER)); - verify(hgen).tagOnly("input", attrs); - } + verify(hgen).tagOnly("input", attrs); + } - @Test - public void testRefCellWithNewWindow() { - String[] attrs = { "href=attribute1", "attribute2", null }; - RefCell cell = new RefCell("name", "attribute1", true, "attribute2"); + @Test + public void testRefCellWithNewWindow() { + String[] attrs = { "href=attribute1", "attribute2", null }; + RefCell cell = new RefCell("name", "attribute1", true, "attribute2"); - when(hgen.leaf(HTMLGen.A, attrs)).thenReturn(hgen); + when(hgen.leaf(HTMLGen.A, attrs)).thenReturn(hgen); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(new String[0])); - } + assertThat(cell.attrs(), equalTo(new String[0])); + } - @Test - public void testRefCellWithoutNewWindow() { - String[] attrs = { "href=attribute1", "attribute2" }; - RefCell cell = new RefCell("name", "attribute1", false, "attribute2"); + @Test + public void testRefCellWithoutNewWindow() { + String[] attrs = { "href=attribute1", "attribute2" }; + RefCell cell = new RefCell("name", "attribute1", false, "attribute2"); - when(hgen.leaf(HTMLGen.A, attrs)).thenReturn(hgen); + when(hgen.leaf(HTMLGen.A, attrs)).thenReturn(hgen); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(new String[0])); + assertThat(cell.attrs(), equalTo(new String[0])); - } + } - @Test - public void testTextAndRefCell() { - String[] attrs = { "href=href", "attribute1", null }; - String[] attributes = { "attribute1" }; - TextAndRefCell cell = new TextAndRefCell("text", "name", "href", true, attributes); + @Test + public void testTextAndRefCell() { + String[] attrs = { "href=href", "attribute1", null }; + String[] attributes = { "attribute1" }; + TextAndRefCell cell = new TextAndRefCell("text", "name", "href", true, attributes); - when(hgen.leaf(HTMLGen.A, attrs)).thenReturn(hgen); + when(hgen.leaf(HTMLGen.A, attrs)).thenReturn(hgen); - cell.write(hgen); + cell.write(hgen); - verify(hgen).text("text"); - } + verify(hgen).text("text"); + } - @Test - public void testTextCell() { - String[] attrs = { "href" }; - TextCell cell = new TextCell("name", "href"); + @Test + public void testTextCell() { + String[] attrs = { "href" }; + TextCell cell = new TextCell("name", "href"); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(attrs)); + assertThat(cell.attrs(), equalTo(attrs)); - verify(hgen).text("name"); - } + verify(hgen).text("name"); + } - @Test - public void testTextInputCell() { - String[] attrs = { "href" }; - TextInputCell cell = new TextInputCell("name", "textClass", "value"); + @Test + public void testTextInputCell() { + String[] attrs = { "href" }; + TextInputCell cell = new TextInputCell("name", "textClass", "value"); - cell.write(hgen); + cell.write(hgen); - assertThat(cell.attrs(), equalTo(new String[0])); - } + assertThat(cell.attrs(), equalTo(new String[0])); + } } 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 d88ed097..ff957093 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 @@ -124,11 +124,11 @@ public class AAF_Hello extends AbsService<AuthzEnv,AuthzTrans> { try { new JettyServiceStarter<AuthzEnv,AuthzTrans>( - new AAF_Hello(new AuthzEnv(propAccess)),true) - .start(); - } catch (Exception e) { - propAccess.log(e); - } + new AAF_Hello(new AuthzEnv(propAccess)),true) + .start(); + } catch (Exception e) { + propAccess.log(e); + } } catch (Exception e) { e.printStackTrace(); } 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 ebbeae6b..b481ff9a 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 @@ -193,13 +193,13 @@ public class AAF_Locate extends AbsService<AuthzEnv, AuthzTrans> { public Locator<URI> getGUILocator() throws LocatorException { if (gui_locator==null) { - RegistrationPropHolder rph; - try { - rph = new RegistrationPropHolder(access, 0); - } catch (UnknownHostException | CadiException e) { - throw new LocatorException(e); - } - String url = rph.getPublicEntryName("gui", rph.default_container); + RegistrationPropHolder rph; + try { + rph = new RegistrationPropHolder(access, 0); + } catch (UnknownHostException | CadiException e) { + throw new LocatorException(e); + } + String url = rph.getPublicEntryName("gui", rph.default_container); gui_locator = AbsAAFLocator.create(url,Config.AAF_DEFAULT_API_VERSION); } return gui_locator; @@ -243,11 +243,11 @@ public class AAF_Locate extends AbsService<AuthzEnv, AuthzTrans> { try { new JettyServiceStarter<AuthzEnv,AuthzTrans>( - new AAF_Locate(new AuthzEnv(propAccess)),true) - .start(); - } catch (Exception e) { - propAccess.log(e); - } + new AAF_Locate(new AuthzEnv(propAccess)),true) + .start(); + } catch (Exception e) { + propAccess.log(e); + } } catch (Exception e) { e.printStackTrace(); } 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 829335c0..e080e7ee 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 @@ -77,10 +77,10 @@ public class LocateServiceImpl<IN,OUT,ERROR> 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(denied==null) { - denied = new StringBuilder("May not register service(s):"); - } - + if(denied==null) { + denied = new StringBuilder("May not register service(s):"); + } + denied.append("\n\t"); denied.append(p.getKey()); denied.append(')'); @@ -95,7 +95,7 @@ public class LocateServiceImpl<IN,OUT,ERROR> return Result.ok(); } else { return denied==null?Result.err(Result.ERR_NotFound, "No endpoints found") - :Result.err(Result.ERR_Security,denied.toString()); + :Result.err(Result.ERR_Security,denied.toString()); } } @@ -111,14 +111,14 @@ public class LocateServiceImpl<IN,OUT,ERROR> int count = 0; StringBuilder denied = null; for (MgmtEndpoint me : meps.getMgmtEndpoint()) { - if (permToRegister) { + 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.getHostname(),"write"); if (!trans.fish(p)) { - if(denied==null) { - denied = new StringBuilder("May not deregister service(s):"); - } - + if(denied==null) { + denied = new StringBuilder("May not deregister service(s):"); + } + denied.append("\n\t"); denied.append(p.getKey()); denied.append(')'); @@ -133,7 +133,7 @@ public class LocateServiceImpl<IN,OUT,ERROR> return Result.ok(); } else { return denied==null?Result.err(Result.ERR_NotFound, "No endpoints found") - :Result.err(Result.ERR_Security,denied.toString()); + :Result.err(Result.ERR_Security,denied.toString()); } } diff --git a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java index 31876fef..fa713094 100644 --- a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java +++ b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/JU_BasicAuthCodeTest.java @@ -41,74 +41,74 @@ import org.onap.aaf.cadi.principal.X509Principal; import org.onap.aaf.misc.env.LogTarget;
public class JU_BasicAuthCodeTest {
- @Mock
- AAFAuthn authn;
+ @Mock
+ AAFAuthn authn;
- @Mock(answer = Answers.RETURNS_DEEP_STUBS)
- AuthzTrans trans;
+ @Mock(answer = Answers.RETURNS_DEEP_STUBS)
+ AuthzTrans trans;
- @Mock
- HttpServletRequest req;
+ @Mock
+ HttpServletRequest req;
- @Mock
- HttpServletResponse resp;
+ @Mock
+ HttpServletResponse resp;
- @Mock
- LogTarget error;
+ @Mock
+ LogTarget error;
- @Mock
- LocateFacade facade;
+ @Mock
+ LocateFacade facade;
- @Mock
- BasicPrincipal basicPrincipal;
- @Mock
- X509Principal x509Principal;
+ @Mock
+ BasicPrincipal basicPrincipal;
+ @Mock
+ X509Principal x509Principal;
- @Before
- public void setUp() throws Exception {
- initMocks(this);
- }
+ @Before
+ public void setUp() throws Exception {
+ initMocks(this);
+ }
- @Test
- public void testWithNullUserPrincipal() throws Exception {
- BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);
- LocateCode locateCode = basicAuthCode.clone(facade, false);
+ @Test
+ public void testWithNullUserPrincipal() throws Exception {
+ BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);
+ LocateCode locateCode = basicAuthCode.clone(facade, false);
- assertEquals(locateCode.desc(), basicAuthCode.desc());
+ assertEquals(locateCode.desc(), basicAuthCode.desc());
- when(trans.getUserPrincipal()).thenReturn(null);
- when(trans.error()).thenReturn(error);
+ when(trans.getUserPrincipal()).thenReturn(null);
+ when(trans.error()).thenReturn(error);
- basicAuthCode.handle(trans, req, resp);
- }
+ basicAuthCode.handle(trans, req, resp);
+ }
- @Test
- public void testWithBasicUserPrincipal() throws Exception {
- BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);
- LocateCode locateCode = basicAuthCode.clone(facade, false);
+ @Test
+ public void testWithBasicUserPrincipal() throws Exception {
+ BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);
+ LocateCode locateCode = basicAuthCode.clone(facade, false);
- assertEquals(locateCode.desc(), basicAuthCode.desc());
+ assertEquals(locateCode.desc(), basicAuthCode.desc());
- when(trans.getUserPrincipal()).thenReturn(basicPrincipal);
+ when(trans.getUserPrincipal()).thenReturn(basicPrincipal);
- basicAuthCode.handle(trans, req, resp);
+ basicAuthCode.handle(trans, req, resp);
- verify(resp).setStatus(HttpStatus.OK_200);
- }
+ verify(resp).setStatus(HttpStatus.OK_200);
+ }
- @Test
- public void testWithX509UserPrincipal() throws Exception {
- BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);
- LocateCode locateCode = basicAuthCode.clone(facade, false);
+ @Test
+ public void testWithX509UserPrincipal() throws Exception {
+ BasicAuthCode basicAuthCode = new BasicAuthCode(authn, facade);
+ LocateCode locateCode = basicAuthCode.clone(facade, false);
- assertEquals(locateCode.desc(), basicAuthCode.desc());
+ assertEquals(locateCode.desc(), basicAuthCode.desc());
- when(trans.getUserPrincipal()).thenReturn(x509Principal);
- when(req.getHeader("Authorization")).thenReturn("Basic 76//76");
+ when(trans.getUserPrincipal()).thenReturn(x509Principal);
+ when(req.getHeader("Authorization")).thenReturn("Basic 76//76");
- basicAuthCode.handle(trans, req, resp);
+ basicAuthCode.handle(trans, req, resp);
- verify(resp).setStatus(HttpStatus.FORBIDDEN_403);
- }
+ verify(resp).setStatus(HttpStatus.FORBIDDEN_403);
+ }
}
diff --git a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/api/JU_API_AAFTest.java b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/api/JU_API_AAFTest.java index ef8a1dc4..dd9ac7fc 100644 --- a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/api/JU_API_AAFTest.java +++ b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/api/JU_API_AAFTest.java @@ -32,40 +32,40 @@ import org.onap.aaf.auth.locate.facade.LocateFacade; public class JU_API_AAFTest { - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - private AAF_Locate gwAPI; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - private LocateFacade facade; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private AAF_Locate gwAPI; + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + private LocateFacade facade; - @Before - public void setUp() throws Exception { - initMocks(this); - } + @Before + public void setUp() throws Exception { + initMocks(this); + } - @Test - public void testAPI_AAFAccess() throws Exception { - try { - API_AAFAccess.init(gwAPI, facade); - } catch (Exception e) { - fail("There should be no exception as Mocks are used"); - } - } + @Test + public void testAPI_AAFAccess() throws Exception { + try { + API_AAFAccess.init(gwAPI, facade); + } catch (Exception e) { + fail("There should be no exception as Mocks are used"); + } + } - @Test - public void testAPI_Find() throws Exception { - try { - API_Find.init(gwAPI, facade); - } catch (Exception e) { - fail("There should be no exception as Mocks are used"); - } - } + @Test + public void testAPI_Find() throws Exception { + try { + API_Find.init(gwAPI, facade); + } catch (Exception e) { + fail("There should be no exception as Mocks are used"); + } + } - @Test - public void testAPI_API() throws Exception { - try { - API_Api.init(gwAPI, facade); - } catch (Exception e) { - fail("There should be no exception as Mocks are used"); - } - } + @Test + public void testAPI_API() throws Exception { + try { + API_Api.init(gwAPI, facade); + } catch (Exception e) { + fail("There should be no exception as Mocks are used"); + } + } } diff --git a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java index 26bea940..5422117c 100644 --- a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java +++ b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/mapper/JU_Mapper_1_0Test.java @@ -35,31 +35,31 @@ import locate_local.v1_0.Out; public class JU_Mapper_1_0Test {
- @Before
- public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
- }
+ }
- @Test
- public void testGetClasses() {
- Mapper_1_1 mapper = new Mapper_1_1();
- assertEquals(InRequest.class, mapper.getClass(API.IN_REQ));
- assertEquals(Out.class, mapper.getClass(API.OUT));
- assertEquals(Error.class, mapper.getClass(API.ERROR));
- assertEquals(Void.class, mapper.getClass(API.VOID));
- assertEquals(Endpoints.class, mapper.getClass(API.ENDPOINTS));
- assertEquals(MgmtEndpoints.class, mapper.getClass(API.MGMT_ENDPOINTS));
- }
+ @Test
+ public void testGetClasses() {
+ Mapper_1_1 mapper = new Mapper_1_1();
+ assertEquals(InRequest.class, mapper.getClass(API.IN_REQ));
+ assertEquals(Out.class, mapper.getClass(API.OUT));
+ assertEquals(Error.class, mapper.getClass(API.ERROR));
+ assertEquals(Void.class, mapper.getClass(API.VOID));
+ assertEquals(Endpoints.class, mapper.getClass(API.ENDPOINTS));
+ assertEquals(MgmtEndpoints.class, mapper.getClass(API.MGMT_ENDPOINTS));
+ }
- @Test
- public void testNewInstance() {
- Mapper_1_1 mapper = new Mapper_1_1();
- assertTrue(mapper.newInstance(API.IN_REQ) instanceof InRequest);
- assertTrue(mapper.newInstance(API.OUT) instanceof Out);
- assertTrue(mapper.newInstance(API.ERROR) instanceof Error);
- assertTrue(mapper.newInstance(API.ENDPOINTS) instanceof Endpoints);
- assertTrue(mapper.newInstance(API.MGMT_ENDPOINTS) instanceof MgmtEndpoints);
- assertEquals(null, mapper.newInstance(API.VOID));
- }
+ @Test
+ public void testNewInstance() {
+ Mapper_1_1 mapper = new Mapper_1_1();
+ assertTrue(mapper.newInstance(API.IN_REQ) instanceof InRequest);
+ assertTrue(mapper.newInstance(API.OUT) instanceof Out);
+ assertTrue(mapper.newInstance(API.ERROR) instanceof Error);
+ assertTrue(mapper.newInstance(API.ENDPOINTS) instanceof Endpoints);
+ assertTrue(mapper.newInstance(API.MGMT_ENDPOINTS) instanceof MgmtEndpoints);
+ assertEquals(null, mapper.newInstance(API.VOID));
+ }
}
diff --git a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java index c66de60b..e3a74720 100644 --- a/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java +++ b/auth/auth-locate/src/test/java/org/onap/aaf/auth/locate/service/JU_LocateServiceImplTest.java @@ -44,71 +44,71 @@ import locate.v1_0.MgmtEndpoints; public class JU_LocateServiceImplTest {
- // Extend, because I don't want a "setter" in the original. Compromised with a protected...
- private final class LocateServiceImplExtension extends LocateServiceImpl {
- private LocateServiceImplExtension(AuthzTrans trans, AAF_Locate locate, Mapper mapper) throws APIException {
- super(trans, locate, mapper);
- }
- public void set(LocateDAO ld) {
- locateDAO=ld;
- }
- }
-
- @Mock
- private AuthzTrans trans;
- @Mock
- private AAF_Locate aaf_locate;
- @Mock
- private LocateDAO locateDAO;
- @Mock
- private Mapper mapper;
- @Mock
- private Result<List<Data>> result;
- @Mock
- private Result endPointResult;
- @Mock
- private MgmtEndpoints meps;
- @Mock
- private MgmtEndpoint mgmtEndPoint;
-
- @Before
- public void setup() {
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void test() throws APIException {
- LocateServiceImplExtension locateServiceImpl = new LocateServiceImplExtension(trans, aaf_locate, mapper);
- locateServiceImpl.set(locateDAO);
-
- assertEquals(mapper, locateServiceImpl.mapper());
-
- when(locateDAO.readByName(trans, "http")).thenReturn(result);
- when(mapper.endpoints(result, "1.0", "other")).thenReturn(endPointResult);
-
- Result output = locateServiceImpl.getEndPoints(trans, "http", "1.0", "other");
-
- assertEquals(endPointResult, output);
-
- List<MgmtEndpoint> mgmtEndPoints = new ArrayList<>();
- mgmtEndPoints.add(mgmtEndPoint);
-
- when(mgmtEndPoint.getName()).thenReturn("http.Endpoint1");
- when(mgmtEndPoint.getHostname()).thenReturn("HOST1");
- when(mgmtEndPoint.getPort()).thenReturn(9090);
- when(mgmtEndPoint.getProtocol()).thenReturn("HTTP");
-
- when(meps.getMgmtEndpoint()).thenReturn(mgmtEndPoints);
- output = locateServiceImpl.putMgmtEndPoints(trans, meps);
-
- assertEquals(output.toString(), Result.ok().toString());
-
- when(trans.fish(any())).thenReturn(true);
- Data data = new LocateDAO.Data();
- when(mapper.locateData(mgmtEndPoint)).thenReturn(data);
- output = locateServiceImpl.removeMgmtEndPoints(trans, meps);
-
- assertEquals(output.toString(), Result.ok().toString());
- }
+ // Extend, because I don't want a "setter" in the original. Compromised with a protected...
+ private final class LocateServiceImplExtension extends LocateServiceImpl {
+ private LocateServiceImplExtension(AuthzTrans trans, AAF_Locate locate, Mapper mapper) throws APIException {
+ super(trans, locate, mapper);
+ }
+ public void set(LocateDAO ld) {
+ locateDAO=ld;
+ }
+ }
+
+ @Mock
+ private AuthzTrans trans;
+ @Mock
+ private AAF_Locate aaf_locate;
+ @Mock
+ private LocateDAO locateDAO;
+ @Mock
+ private Mapper mapper;
+ @Mock
+ private Result<List<Data>> result;
+ @Mock
+ private Result endPointResult;
+ @Mock
+ private MgmtEndpoints meps;
+ @Mock
+ private MgmtEndpoint mgmtEndPoint;
+
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ }
+
+ @Test
+ public void test() throws APIException {
+ LocateServiceImplExtension locateServiceImpl = new LocateServiceImplExtension(trans, aaf_locate, mapper);
+ locateServiceImpl.set(locateDAO);
+
+ assertEquals(mapper, locateServiceImpl.mapper());
+
+ when(locateDAO.readByName(trans, "http")).thenReturn(result);
+ when(mapper.endpoints(result, "1.0", "other")).thenReturn(endPointResult);
+
+ Result output = locateServiceImpl.getEndPoints(trans, "http", "1.0", "other");
+
+ assertEquals(endPointResult, output);
+
+ List<MgmtEndpoint> mgmtEndPoints = new ArrayList<>();
+ mgmtEndPoints.add(mgmtEndPoint);
+
+ when(mgmtEndPoint.getName()).thenReturn("http.Endpoint1");
+ when(mgmtEndPoint.getHostname()).thenReturn("HOST1");
+ when(mgmtEndPoint.getPort()).thenReturn(9090);
+ when(mgmtEndPoint.getProtocol()).thenReturn("HTTP");
+
+ when(meps.getMgmtEndpoint()).thenReturn(mgmtEndPoints);
+ output = locateServiceImpl.putMgmtEndPoints(trans, meps);
+
+ assertEquals(output.toString(), Result.ok().toString());
+
+ when(trans.fish(any())).thenReturn(true);
+ Data data = new LocateDAO.Data();
+ when(mapper.locateData(mgmtEndPoint)).thenReturn(data);
+ output = locateServiceImpl.removeMgmtEndPoints(trans, meps);
+
+ assertEquals(output.toString(), Result.ok().toString());
+ }
}
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 7f38b65a..b4c9f97b 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 @@ -194,11 +194,11 @@ public class AAF_OAuth extends AbsService<AuthzEnv,AuthzTrans> { try { new JettyServiceStarter<AuthzEnv,AuthzTrans>( - new AAF_OAuth(new AuthzEnv(propAccess)),true) - .start(); - } catch (Exception e) { - propAccess.log(e); - } + new AAF_OAuth(new AuthzEnv(propAccess)),true) + .start(); + } catch (Exception e) { + propAccess.log(e); + } } catch (Exception e) { e.printStackTrace(); } 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 333c0fc1..bdba4696 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 @@ -196,11 +196,11 @@ public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { @Override public void postStartup(final String hostname, final int port) throws APIException { - try { - CacheInfoDAO.startUpdate(env, aafCon().hman(), aafCon().securityInfo().defSS,hostname,port); - } catch (CadiException | LocatorException e) { - throw new APIException(e); - } + try { + CacheInfoDAO.startUpdate(env, aafCon().hman(), aafCon().securityInfo().defSS,hostname,port); + } catch (CadiException | LocatorException e) { + throw new APIException(e); + } } @Override @@ -241,11 +241,11 @@ public class AAF_Service extends AbsService<AuthzEnv,AuthzTrans> { try { new JettyServiceStarter<AuthzEnv,AuthzTrans>( - new AAF_Service(new AuthzEnv(propAccess)),true) - .start(); - } catch (Exception e) { - propAccess.log(e); - } + new AAF_Service(new AuthzEnv(propAccess)),true) + .start(); + } catch (Exception e) { + propAccess.log(e); + } } catch (Exception e) { e.printStackTrace(); } 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 d102b045..3b010821 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 @@ -118,7 +118,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE implements AuthzService <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> { private static final String TWO_SPACE = " "; - private Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper; + private Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper; @Override public Mapper <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERTS,KEYS,REQUEST,HISTORY,ERR,APPROVALS> mapper() {return mapper;} @@ -816,120 +816,120 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // User Permission mechanism if(newPd.value.ns.indexOf('@')>0) { - PermDAO.Data pdd = newPd.value; - if(trans.user().equals(newPd.value.ns)) { - CachedPermDAO permDAO = ques.permDAO(); - Result<List<PermDAO.Data>> rlpdd = permDAO.read(trans, pdd); - if(rlpdd.notOK()) { - return Result.err(rlpdd); - } - if(!rlpdd.isEmpty()) { - return Result.err(Result.ERR_ConflictAlreadyExists,"Permission already exists"); - } - - RoleDAO.Data rdd = new RoleDAO.Data(); - rdd.ns = pdd.ns; - rdd.name = "user"; - - pdd.roles(true).add(rdd.fullName()); - Result<PermDAO.Data> rpdd = permDAO.create(trans, pdd); - if(rpdd.notOK()) { - return Result.err(rpdd); - } - - CachedRoleDAO roleDAO = ques.roleDAO(); - Result<List<RoleDAO.Data>> rlrdd = roleDAO.read(trans, rdd); - if(rlrdd.notOK()) { - return Result.err(rlrdd); - } else { - if(!rlrdd.isEmpty()) { - rdd = rlrdd.value.get(0); - } - } - - String eperm = pdd.encode(); - rdd.perms(true).add(eperm); - Result<Void> rv = roleDAO.update(trans, rdd); - if(rv.notOK()) { - return rv; - } - - CachedUserRoleDAO urDAO = ques.userRoleDAO(); - UserRoleDAO.Data urdd = new UserRoleDAO.Data(); - urdd.user = trans.user(); - urdd.ns = rdd.ns; - urdd.rname = rdd.name; - urdd.role = rdd.fullName(); - Result<List<UserRoleDAO.Data>> rlurdd = urDAO.read(trans, urdd); - if(rlurdd.notOK()) { - return Result.err(rlrdd); - } else if(rlurdd.isEmpty()) { - GregorianCalendar gc = trans.org().expiration(null, Expiration.UserInRole); - if(gc==null) { - return Result.err(Result.ERR_Policy,"Organzation does not grant Expiration for UserRole"); - } else { - urdd.expires = gc.getTime(); - } - Result<UserRoleDAO.Data> rurdd = urDAO.create(trans, urdd); - return Result.err(rurdd); - } - return rv; - } else { - return Result.err(Result.ERR_Security,"Only the User can create User Permissions"); - } + PermDAO.Data pdd = newPd.value; + if(trans.user().equals(newPd.value.ns)) { + CachedPermDAO permDAO = ques.permDAO(); + Result<List<PermDAO.Data>> rlpdd = permDAO.read(trans, pdd); + if(rlpdd.notOK()) { + return Result.err(rlpdd); + } + if(!rlpdd.isEmpty()) { + return Result.err(Result.ERR_ConflictAlreadyExists,"Permission already exists"); + } + + RoleDAO.Data rdd = new RoleDAO.Data(); + rdd.ns = pdd.ns; + rdd.name = "user"; + + pdd.roles(true).add(rdd.fullName()); + Result<PermDAO.Data> rpdd = permDAO.create(trans, pdd); + if(rpdd.notOK()) { + return Result.err(rpdd); + } + + CachedRoleDAO roleDAO = ques.roleDAO(); + Result<List<RoleDAO.Data>> rlrdd = roleDAO.read(trans, rdd); + if(rlrdd.notOK()) { + return Result.err(rlrdd); + } else { + if(!rlrdd.isEmpty()) { + rdd = rlrdd.value.get(0); + } + } + + String eperm = pdd.encode(); + rdd.perms(true).add(eperm); + Result<Void> rv = roleDAO.update(trans, rdd); + if(rv.notOK()) { + return rv; + } + + CachedUserRoleDAO urDAO = ques.userRoleDAO(); + UserRoleDAO.Data urdd = new UserRoleDAO.Data(); + urdd.user = trans.user(); + urdd.ns = rdd.ns; + urdd.rname = rdd.name; + urdd.role = rdd.fullName(); + Result<List<UserRoleDAO.Data>> rlurdd = urDAO.read(trans, urdd); + if(rlurdd.notOK()) { + return Result.err(rlrdd); + } else if(rlurdd.isEmpty()) { + GregorianCalendar gc = trans.org().expiration(null, Expiration.UserInRole); + if(gc==null) { + return Result.err(Result.ERR_Policy,"Organzation does not grant Expiration for UserRole"); + } else { + urdd.expires = gc.getTime(); + } + Result<UserRoleDAO.Data> rurdd = urDAO.create(trans, urdd); + return Result.err(rurdd); + } + return rv; + } else { + return Result.err(Result.ERR_Security,"Only the User can create User Permissions"); + } } else { - // Does Perm Type exist as a Namespace? - if(newPd.value.type.isEmpty() || ques.nsDAO().read(trans, newPd.value.fullType()).isOKhasData()) { - return Result.err(Status.ERR_ConflictAlreadyExists, - "Permission Type exists as a Namespace"); - } - - Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false, - new Mapper.Memo() { - @Override - public String get() { - return "Create Permission [" + - newPd.value.fullType() + '|' + - newPd.value.instance + '|' + - newPd.value.action + ']'; - } - }, - new MayChange() { - private Result<NsDAO.Data> nsd; - @Override - public Result<?> mayChange() { - 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()) { - return Result.err(nsr); - } - switch(fd.status) { - case OK: - Result<String> rfc = func.createFuture(trans,fd.value, - newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action, - trans.user(), - nsr.value.get(0), - FUTURE_OP.C); - 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, - newPd.value.instance, - newPd.value.action); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - return func.createPerm(trans, newPd.value, true); - default: - return Result.err(fd); - } + // Does Perm Type exist as a Namespace? + if(newPd.value.type.isEmpty() || ques.nsDAO().read(trans, newPd.value.fullType()).isOKhasData()) { + return Result.err(Status.ERR_ConflictAlreadyExists, + "Permission Type exists as a Namespace"); + } + + Result<FutureDAO.Data> fd = mapper.future(trans, PermDAO.TABLE, rreq, newPd.value,false, + new Mapper.Memo() { + @Override + public String get() { + return "Create Permission [" + + newPd.value.fullType() + '|' + + newPd.value.instance + '|' + + newPd.value.action + ']'; + } + }, + new MayChange() { + private Result<NsDAO.Data> nsd; + @Override + public Result<?> mayChange() { + 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()) { + return Result.err(nsr); + } + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans,fd.value, + newPd.value.fullType() + '|' + newPd.value.instance + '|' + newPd.value.action, + trans.user(), + nsr.value.get(0), + FUTURE_OP.C); + 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, + newPd.value.instance, + newPd.value.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + return func.createPerm(trans, newPd.value, true); + default: + return Result.err(fd); + } } } @@ -1995,7 +1995,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE if (nsd==null) { nsd = ques.mayUser(trans, trans.user(), rpd.value, Access.write); if(nsd.notOK()) { - trans.requested(REQD_TYPE.future,true); + trans.requested(REQD_TYPE.future,true); } } return nsd; @@ -2006,32 +2006,32 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE return Result.err(nsr); } switch(fd.status) { - case OK: - Result<String> rfc = func.createFuture(trans,fd.value, - rpd.value.fullPerm(), - trans.user(), - nsr.value.get(0), - FUTURE_OP.G); - 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, - rpd.value.instance, - rpd.value.action); - } else { - return Result.err(rfc); - } - case Status.ACC_Now: - Result<Void> rv = null; - if (createPerm!=null) {// has been validated for creating - rv = func.createPerm(trans, createPerm, false); - } - if (rv==null || rv.isOK()) { - rv = func.addPermToRole(trans, rrd.value, rpd.value, false); - } - return rv; - default: - return Result.err(fd); + case OK: + Result<String> rfc = func.createFuture(trans,fd.value, + rpd.value.fullPerm(), + trans.user(), + nsr.value.get(0), + FUTURE_OP.G); + 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, + rpd.value.instance, + rpd.value.action); + } else { + return Result.err(rfc); + } + case Status.ACC_Now: + Result<Void> rv = null; + if (createPerm!=null) {// has been validated for creating + rv = func.createPerm(trans, createPerm, false); + } + if (rv==null || rv.isOK()) { + rv = func.addPermToRole(trans, rrd.value, rpd.value, false); + } + return rv; + default: + return Result.err(fd); } } @@ -2310,12 +2310,12 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private class MayChangeCred implements MayChange { private static final String EXTEND = "extend"; - private static final String RESET = "reset"; - private static final String DELETE = "delete"; - private Result<NsDAO.Data> nsd; + private static final String RESET = "reset"; + private static final String DELETE = "delete"; + private Result<NsDAO.Data> nsd; private AuthzTrans trans; private CredDAO.Data cred; - private String action; + private String action; public MayChangeCred(AuthzTrans trans, CredDAO.Data cred, String action) { this.trans = trans; this.cred = cred; @@ -2330,35 +2330,35 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } // Get the Namespace if (nsd.isOK()) { - String ns = nsd.value.name; - String user = trans.user(); - String company; - String temp[] = Split.split('.',ns); - switch(temp.length) { - case 0: - company = Defaults.AAF_NS; - break; - case 1: - company = temp[0]; - break; - default: - company = temp[0] + '.' + temp[1]; - } - switch(action) { - case DELETE: - if(ques.isOwner(trans, user,ns) || - ques.isAdmin(trans, user,ns) || - ques.isGranted(trans, user, ROOT_NS,"password",company,DELETE)) { - return Result.ok(); - } - break; - case RESET: - case EXTEND: + String ns = nsd.value.name; + String user = trans.user(); + String company; + String temp[] = Split.split('.',ns); + switch(temp.length) { + case 0: + company = Defaults.AAF_NS; + break; + case 1: + company = temp[0]; + break; + default: + company = temp[0] + '.' + temp[1]; + } + switch(action) { + case DELETE: + if(ques.isOwner(trans, user,ns) || + ques.isAdmin(trans, user,ns) || + ques.isGranted(trans, user, ROOT_NS,"password",company,DELETE)) { + return Result.ok(); + } + break; + case RESET: + case EXTEND: if (ques.isGranted(trans, trans.user(), ROOT_NS,"password",company,action)) { return Result.ok(); } break; - } + } } return Result.err(Status.ERR_Denied,"%s is not allowed to %s %s in %s",trans.user(),action,cred.id,cred.ns); } @@ -2432,27 +2432,27 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // password to validate char differences. // byte[] rawCred = rcred.value.type==CredDAO.RAW?null:; return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists"); - if(rcred.value.type==CredDAO.FQI ) { - if(curr.type==CredDAO.FQI) { - return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists"); - } - } else { - - rb = ques.userCredCheck(trans, curr, rcred.value.cred!=null?rcred.value.cred.array():null); - if (rb.notOK()) { - return Result.err(rb); - } 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 - ) { - // Allow if expiring differential is greater than 1 day (for TEMP) - // Unless expiring in 1 day - if(System.currentTimeMillis() - rcred.value.expires.getTime() > TimeUnit.DAYS.toMillis(1)) { - return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists"); - } - } - } + if(rcred.value.type==CredDAO.FQI ) { + if(curr.type==CredDAO.FQI) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists"); + } + } else { + + rb = ques.userCredCheck(trans, curr, rcred.value.cred!=null?rcred.value.cred.array():null); + if (rb.notOK()) { + return Result.err(rb); + } 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 + ) { + // Allow if expiring differential is greater than 1 day (for TEMP) + // Unless expiring in 1 day + if(System.currentTimeMillis() - rcred.value.expires.getTime() > TimeUnit.DAYS.toMillis(1)) { + return Result.err(Status.ERR_ConflictAlreadyExists, "Credential with same Expiration Date exists"); + } + } + } } } else { try { @@ -2510,18 +2510,18 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE if (firstID) { // OK, it's a first ID, and not by NS Owner if(!ques.isOwner(trans,trans.user(),cdd.ns)) { - // Admins are not allowed to set first Cred, but Org has already - // said entity MAY create, typically by Permission - // We can't know which reason they are allowed here, so we - // have to assume that any with Special Permission would not be - // an Admin. - if(ques.isAdmin(trans, trans.user(), cdd.ns)) { - return Result.err(Result.ERR_Denied, - "Only Owners may create first passwords in their Namespace. Admins may modify after one exists" ); - } else { - // Allow IDs that AREN'T part of NS with Org Onboarding Permission (see Org object) to create Temp Passwords. + // Admins are not allowed to set first Cred, but Org has already + // said entity MAY create, typically by Permission + // We can't know which reason they are allowed here, so we + // have to assume that any with Special Permission would not be + // an Admin. + if(ques.isAdmin(trans, trans.user(), cdd.ns)) { + return Result.err(Result.ERR_Denied, + "Only Owners may create first passwords in their Namespace. Admins may modify after one exists" ); + } else { + // Allow IDs that AREN'T part of NS with Org Onboarding Permission (see Org object) to create Temp Passwords. rcred.value.expires = org.expiration(null, Expiration.TempPassword).getTime(); - } + } } } } catch (Exception e) { @@ -2852,7 +2852,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE cd.tag = found.tag; cd.expires = org.expiration(null, Expiration.ExtendPassword,days).getTime(); if(cd.expires.before(found.expires)) { - return Result.err(Result.ERR_BadData,String.format("Credential's expiration date is more than %s days in the future",days)); + return Result.err(Result.ERR_BadData,String.format("Credential's expiration date is more than %s days in the future",days)); } cred = ques.credDAO().create(trans, cd); @@ -2866,249 +2866,249 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } @ApiDoc( - method = DELETE, - path = "/authn/cred", - params = {}, - expectedCode = 200, - errorCodes = {300,403,404,406}, - text = { "Delete a Credential. If multiple credentials exist for this", - "ID, you will need to specify which entry you are deleting in the", - "CredRequest object." - } - ) - @Override - 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()) { - return Result.err(Status.ERR_BadData,v.errs()); - } - - MayChange mc = new MayChangeCred(trans,cred.value,MayChangeCred.DELETE); - Result<?> rmc = mc.mayChange(); - if (rmc.notOK()) { - return Result.err(rmc); - } - - boolean doForce = trans.requested(force); - Result<List<CredDAO.Data>> rlcd = ques.credDAO().readID(trans, cred.value.id); - if (rlcd.notOKorIsEmpty()) { - // Empty Creds should not have user_roles. - Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO().readByUser(trans, cred.value.id); - if (rlurd.isOKhasData()) { - for (UserRoleDAO.Data data : rlurd.value) { - ques.userRoleDAO().delete(trans, data, false); - } - } - return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); - } - boolean isLastCred = rlcd.value.size()==1; - - int entry; - CredRequest cr = (CredRequest)from; - if(isLastCred) { - if(cr.getEntry()==null || "1".equals(cr.getEntry())) { - entry = 0; - } else { - return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); - } - } else { - entry = -1; - int fentry = entry; - if(cred.value.type==CredDAO.FQI) { - entry = -1; - for(CredDAO.Data cdd : rlcd.value) { - ++fentry; - if(cdd.type == CredDAO.FQI) { - entry = fentry; - break; - } - } - } else { - if (!doForce) { - if (rlcd.value.size() > 1) { - String inputOption = cr.getEntry(); - if (inputOption == null) { - List<CredDAO.Data> list = filterList(rlcd.value,CredDAO.BASIC_AUTH,CredDAO.BASIC_AUTH_SHA256,CredDAO.CERT_SHA256_RSA); - String message = selectCredFromList(list, MayChangeCred.DELETE); - Object[] variables = buildVariables(list); - return Result.err(Status.ERR_ChoiceNeeded, message, variables); - } else { - try { - if (inputOption.length()>5) { // should be a date - Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime(); - for (CredDAO.Data cd : rlcd.value) { - ++fentry; - if (cd.type.equals(cr.getType()) && cd.expires.equals(d)) { - entry = fentry; - break; - } - } - } else { - entry = Integer.parseInt(inputOption) - 1; - int count = 0; - for (CredDAO.Data cd : rlcd.value) { - if(cd.type!=CredDAO.BASIC_AUTH && cd.type!=CredDAO.BASIC_AUTH_SHA256 && cd.type!=CredDAO.CERT_SHA256_RSA) { - ++entry; - } - if(++count>entry) { - break; - } - } - } - } catch (NullPointerException e) { - return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry"); - } catch (NumberFormatException e) { - return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); - } - } - isLastCred = (entry==-1); - } else { - isLastCred = true; - } - if (entry < -1 || entry >= rlcd.value.size()) { - return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); - } - } - } - } - - Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false, - () -> "Delete Credential [" + - cred.value.id + - ']', - mc); - - Result<List<NsDAO.Data>> nsr = ques.nsDAO().read(trans, cred.value.ns); - if (nsr.notOKorIsEmpty()) { - return Result.err(nsr); - } - - switch(fd.status) { - case OK: - Result<String> rfc = func.createFuture(trans, fd.value, cred.value.id, - trans.user(), nsr.value.get(0), FUTURE_OP.D); - - 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); - } - case Status.ACC_Now: - Result<?>udr = null; - if (!trans.requested(force)) { - if (entry<0 || entry >= rlcd.value.size()) { - if(cred.value.type==CredDAO.FQI) { - return Result.err(Status.ERR_BadData,"FQI does not exist"); - } else { - 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); - } else { - for (CredDAO.Data curr : rlcd.value) { - udr = ques.credDAO().delete(trans, curr, false); - if (udr.notOK()) { - return Result.err(udr); - } - } - } - if (isLastCred) { - Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO().readByUser(trans, cred.value.id); - if (rlurd.isOK()) { - for (UserRoleDAO.Data data : rlurd.value) { - ques.userRoleDAO().delete(trans, data, false); - } - } - } - if (udr==null) { - return Result.err(Result.ERR_NotFound,"No User Data found"); - } - if (udr.isOK()) { - return Result.ok(); - } - return Result.err(udr); - default: - return Result.err(fd); - } - - } - - /* - * Codify the way to get Either Choice Needed or actual Integer from Credit Request - */ - private Result<Integer> selectEntryIfMultiple(final CredRequest cr, List<CredDAO.Data> lcd, String action) { - int entry = 0; - if (lcd.size() > 1) { - String inputOption = cr.getEntry(); - if (inputOption == null) { - String message = selectCredFromList(lcd, action); - Object[] variables = buildVariables(lcd); - return Result.err(Status.ERR_ChoiceNeeded, message, variables); - } else { - if(MayChangeCred.EXTEND.equals(action)) { - // might be Tag - if(inputOption.length()>4) { //Tag is at least 12 - int e = 0; - CredDAO.Data last = null; - int lastIdx = -1; - for(CredDAO.Data cdd : lcd) { - if(inputOption.equals(cdd.tag)) { - if(last==null) { - last = cdd; - lastIdx = e; - } else { - if(last.expires.before(cdd.expires)) { - last = cdd; - lastIdx = e; - } - } - } - ++e; - } - if(last!=null) { - return Result.ok(lastIdx); - } - return Result.err(Status.ERR_BadData, "User chose unknown Tag"); - } - } - entry = Integer.parseInt(inputOption) - 1; - } - if (entry < 0 || entry >= lcd.size()) { - return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); - } - } - return Result.ok(entry); - } - - private List<CredDAO.Data> filterList(List<CredDAO.Data> orig, Integer ... types) { - List<CredDAO.Data> rv = new ArrayList<>(); + method = DELETE, + path = "/authn/cred", + params = {}, + expectedCode = 200, + errorCodes = {300,403,404,406}, + text = { "Delete a Credential. If multiple credentials exist for this", + "ID, you will need to specify which entry you are deleting in the", + "CredRequest object." + } + ) + @Override + 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()) { + return Result.err(Status.ERR_BadData,v.errs()); + } + + MayChange mc = new MayChangeCred(trans,cred.value,MayChangeCred.DELETE); + Result<?> rmc = mc.mayChange(); + if (rmc.notOK()) { + return Result.err(rmc); + } + + boolean doForce = trans.requested(force); + Result<List<CredDAO.Data>> rlcd = ques.credDAO().readID(trans, cred.value.id); + if (rlcd.notOKorIsEmpty()) { + // Empty Creds should not have user_roles. + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO().readByUser(trans, cred.value.id); + if (rlurd.isOKhasData()) { + for (UserRoleDAO.Data data : rlurd.value) { + ques.userRoleDAO().delete(trans, data, false); + } + } + return Result.err(Status.ERR_UserNotFound, "Credential does not exist"); + } + boolean isLastCred = rlcd.value.size()==1; + + int entry; + CredRequest cr = (CredRequest)from; + if(isLastCred) { + if(cr.getEntry()==null || "1".equals(cr.getEntry())) { + entry = 0; + } else { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } else { + entry = -1; + int fentry = entry; + if(cred.value.type==CredDAO.FQI) { + entry = -1; + for(CredDAO.Data cdd : rlcd.value) { + ++fentry; + if(cdd.type == CredDAO.FQI) { + entry = fentry; + break; + } + } + } else { + if (!doForce) { + if (rlcd.value.size() > 1) { + String inputOption = cr.getEntry(); + if (inputOption == null) { + List<CredDAO.Data> list = filterList(rlcd.value,CredDAO.BASIC_AUTH,CredDAO.BASIC_AUTH_SHA256,CredDAO.CERT_SHA256_RSA); + String message = selectCredFromList(list, MayChangeCred.DELETE); + Object[] variables = buildVariables(list); + return Result.err(Status.ERR_ChoiceNeeded, message, variables); + } else { + try { + if (inputOption.length()>5) { // should be a date + Date d = Chrono.xmlDatatypeFactory.newXMLGregorianCalendar(inputOption).toGregorianCalendar().getTime(); + for (CredDAO.Data cd : rlcd.value) { + ++fentry; + if (cd.type.equals(cr.getType()) && cd.expires.equals(d)) { + entry = fentry; + break; + } + } + } else { + entry = Integer.parseInt(inputOption) - 1; + int count = 0; + for (CredDAO.Data cd : rlcd.value) { + if(cd.type!=CredDAO.BASIC_AUTH && cd.type!=CredDAO.BASIC_AUTH_SHA256 && cd.type!=CredDAO.CERT_SHA256_RSA) { + ++entry; + } + if(++count>entry) { + break; + } + } + } + } catch (NullPointerException e) { + return Result.err(Status.ERR_BadData, "Invalid Date Format for Entry"); + } catch (NumberFormatException e) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + isLastCred = (entry==-1); + } else { + isLastCred = true; + } + if (entry < -1 || entry >= rlcd.value.size()) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + } + } + + Result<FutureDAO.Data> fd = mapper.future(trans,CredDAO.TABLE,from,cred.value,false, + () -> "Delete Credential [" + + cred.value.id + + ']', + mc); + + Result<List<NsDAO.Data>> nsr = ques.nsDAO().read(trans, cred.value.ns); + if (nsr.notOKorIsEmpty()) { + return Result.err(nsr); + } + + switch(fd.status) { + case OK: + Result<String> rfc = func.createFuture(trans, fd.value, cred.value.id, + trans.user(), nsr.value.get(0), FUTURE_OP.D); + + 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); + } + case Status.ACC_Now: + Result<?>udr = null; + if (!trans.requested(force)) { + if (entry<0 || entry >= rlcd.value.size()) { + if(cred.value.type==CredDAO.FQI) { + return Result.err(Status.ERR_BadData,"FQI does not exist"); + } else { + 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); + } else { + for (CredDAO.Data curr : rlcd.value) { + udr = ques.credDAO().delete(trans, curr, false); + if (udr.notOK()) { + return Result.err(udr); + } + } + } + if (isLastCred) { + Result<List<UserRoleDAO.Data>> rlurd = ques.userRoleDAO().readByUser(trans, cred.value.id); + if (rlurd.isOK()) { + for (UserRoleDAO.Data data : rlurd.value) { + ques.userRoleDAO().delete(trans, data, false); + } + } + } + if (udr==null) { + return Result.err(Result.ERR_NotFound,"No User Data found"); + } + if (udr.isOK()) { + return Result.ok(); + } + return Result.err(udr); + default: + return Result.err(fd); + } + + } + + /* + * Codify the way to get Either Choice Needed or actual Integer from Credit Request + */ + private Result<Integer> selectEntryIfMultiple(final CredRequest cr, List<CredDAO.Data> lcd, String action) { + int entry = 0; + if (lcd.size() > 1) { + String inputOption = cr.getEntry(); + if (inputOption == null) { + String message = selectCredFromList(lcd, action); + Object[] variables = buildVariables(lcd); + return Result.err(Status.ERR_ChoiceNeeded, message, variables); + } else { + if(MayChangeCred.EXTEND.equals(action)) { + // might be Tag + if(inputOption.length()>4) { //Tag is at least 12 + int e = 0; + CredDAO.Data last = null; + int lastIdx = -1; + for(CredDAO.Data cdd : lcd) { + if(inputOption.equals(cdd.tag)) { + if(last==null) { + last = cdd; + lastIdx = e; + } else { + if(last.expires.before(cdd.expires)) { + last = cdd; + lastIdx = e; + } + } + } + ++e; + } + if(last!=null) { + return Result.ok(lastIdx); + } + return Result.err(Status.ERR_BadData, "User chose unknown Tag"); + } + } + entry = Integer.parseInt(inputOption) - 1; + } + if (entry < 0 || entry >= lcd.size()) { + return Result.err(Status.ERR_BadData, "User chose invalid credential selection"); + } + } + return Result.ok(entry); + } + + private List<CredDAO.Data> filterList(List<CredDAO.Data> orig, Integer ... types) { + List<CredDAO.Data> rv = new ArrayList<>(); for(CredDAO.Data cdd : orig) { - if(cdd!=null) { - for(int t : types) { - if(t==cdd.type) { - rv.add(cdd); - } - } - } + if(cdd!=null) { + for(int t : types) { + if(t==cdd.type) { + rv.add(cdd); + } + } + } } Collections.sort(rv, (o1,o2) -> { - if(o1.type==o2.type) { - return o1.expires.compareTo(o2.expires); - } else { - return o1.type.compareTo(o2.type); - } + if(o1.type==o2.type) { + return o1.expires.compareTo(o2.expires); + } else { + return o1.type.compareTo(o2.type); + } }); - return rv; - } + return rv; + } - private String[] buildVariables(List<CredDAO.Data> value) { + private String[] buildVariables(List<CredDAO.Data> value) { String [] vars = new String[value.size()]; CredDAO.Data cdd; for (int i = 0; i < value.size(); i++) { - cdd = value.get(i); - vars[i] = cdd.id + TWO_SPACE + Define.getCredType(cdd.type) + TWO_SPACE + Chrono.niceUTCStamp(cdd.expires) + TWO_SPACE + cdd.tag; + cdd = value.get(i); + vars[i] = cdd.id + TWO_SPACE + Define.getCredType(cdd.type) + TWO_SPACE + Chrono.niceUTCStamp(cdd.expires) + TWO_SPACE + cdd.tag; } return vars; } @@ -3116,8 +3116,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private String selectCredFromList(List<CredDAO.Data> value, String action) { StringBuilder errMessage = new StringBuilder(); String userPrompt = MayChangeCred.DELETE.equals(action)? - "Select which cred to delete (set force=true to delete all):": - "Select which cred to " + action + ':'; + "Select which cred to delete (set force=true to delete all):": + "Select which cred to " + action + ':'; int numSpaces = value.get(0).id.length() - "Id".length(); errMessage.append(userPrompt + '\n'); @@ -3132,7 +3132,7 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE if(MayChangeCred.EXTEND.equals(action)) { errMessage.append("Run same command again with chosen entry or Tag as last parameter"); } else { - errMessage.append("Run same command again with chosen entry as last parameter"); + errMessage.append("Run same command again with chosen entry as last parameter"); } return errMessage.toString(); @@ -3193,20 +3193,20 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE } @ApiDoc( - method = GET, - path = "/authn/basicAuth", - params = {}, - expectedCode = 200, - errorCodes = { 403 }, - text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n" - + "Use /authn/validate instead\n" - + "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast" - + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth " - + "security, and 403 if it does not." } - ) - private void basicAuth() { - // This is a place holder for Documentation. The real BasicAuth API does not call Service. - } + method = GET, + path = "/authn/basicAuth", + params = {}, + expectedCode = 200, + errorCodes = { 403 }, + text = { "!!!! DEPRECATED without X509 Authentication STOP USING THIS API BY DECEMBER 2017, or use Certificates !!!!\n" + + "Use /authn/validate instead\n" + + "Note: Validate a Password using BasicAuth Base64 encoded Header. This HTTP/S call is intended as a fast" + + " User/Password lookup for Security Frameworks, and responds 200 if it passes BasicAuth " + + "security, and 403 if it does not." } + ) + private void basicAuth() { + // This is a place holder for Documentation. The real BasicAuth API does not call Service. + } /*********************************** * USER-ROLE @@ -3251,9 +3251,9 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE private Result<NsDAO.Data> nsd; @Override public Result<?> mayChange() { - if(urr.value.role.startsWith(urr.value.user)) { - return Result.ok((NsDAO.Data)null); - } + if(urr.value.role.startsWith(urr.value.user)) { + return Result.ok((NsDAO.Data)null); + } if (nsd==null) { RoleDAO.Data r = RoleDAO.Data.decode(userRole); nsd = ques.mayUser(trans, trans.user(), r, Access.write); @@ -3264,15 +3264,15 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE NsDAO.Data ndd; if(userRole.role.startsWith(userRole.user)) { - userRole.ns=userRole.user; - userRole.rname="user"; - ndd = null; + userRole.ns=userRole.user; + userRole.rname="user"; + ndd = null; } else { - Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role); - if (nsr.notOK()) { - return Result.err(nsr); - } - ndd = nsr.value; + Result<NsDAO.Data> nsr = ques.deriveNs(trans, userRole.role); + if (nsr.notOK()) { + return Result.err(nsr); + } + ndd = nsr.value; } switch(fd.status) { @@ -3820,17 +3820,17 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE // May user see Namespace of Permission (since it's only one piece... we can't check for "is permission part of") Result<List<HistoryDAO.Data>> resp; if(type.startsWith(trans.user())) { - resp = ques.historyDAO().readBySubject(trans, type, "perm", yyyymm); + resp = ques.historyDAO().readBySubject(trans, type, "perm", yyyymm); } else { Result<NsDAO.Data> rnd = ques.deriveNs(trans,type); - if (rnd.notOK()) { - return Result.err(rnd); - } - rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); - if (rnd.notOK()) { - return Result.err(rnd); - } - resp = ques.historyDAO().readBySubject(trans, type, "perm", yyyymm); + if (rnd.notOK()) { + return Result.err(rnd); + } + rnd = ques.mayUser(trans, trans.user(), rnd.value, Access.read); + if (rnd.notOK()) { + return Result.err(rnd); + } + resp = ques.historyDAO().readBySubject(trans, type, "perm", yyyymm); } if (resp.notOK()) { @@ -3864,8 +3864,8 @@ public class AuthzCassServiceImpl <NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE @Override public Result<HISTORY> getHistoryBySubject(AuthzTrans trans, String subject, String target, int[] yyyymm, final int sort) { - NsDAO.Data ndd = new NsDAO.Data(); - ndd.name = FQI.reverseDomain(subject); + NsDAO.Data ndd = new NsDAO.Data(); + ndd.name = FQI.reverseDomain(subject); Result<Data> rnd = ques.mayUser(trans, trans.user(), ndd, Access.read); if (rnd.notOK()) { return Result.err(rnd); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java index 80d317f0..f9f23f46 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/AuthzService.java @@ -644,7 +644,7 @@ public interface AuthzService<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DELGS,CERT * @param sort * @return */ - public Result<HISTORY> getHistoryBySubject(AuthzTrans trans, String subject, String target, int[] yyyymm, int sort); + public Result<HISTORY> getHistoryBySubject(AuthzTrans trans, String subject, String target, int[] yyyymm, int sort); /*********************************** * DELEGATE 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 c8bae9f0..f7c38681 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 @@ -194,7 +194,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); + Result<Void> r = context.createUserCred(trans, req); if (r.isOK()) { resp.setStatus(HttpStatus.CREATED_201); } else { diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java index a56b7c26..15d2302f 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/api/API_UserRole.java @@ -114,7 +114,7 @@ public class API_UserRole { authzAPI.route(PUT,"/authz/userRole/user",API.USER_ROLE_REQ,new Code(facade,"Update Roles for a user", true) { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - context.error(trans,resp,removeAPI); + context.error(trans,resp,removeAPI); } }); @@ -125,7 +125,7 @@ public class API_UserRole { authzAPI.route(PUT,"/authz/userRole/role",API.USER_ROLE_REQ,new Code(facade,"Update Users for a role", true) { @Override public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception { - context.error(trans,resp,removeAPI); + context.error(trans,resp,removeAPI); } }); diff --git a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java index 80e02264..f9ea39d6 100644 --- a/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java +++ b/auth/auth-service/src/main/java/org/onap/aaf/auth/service/facade/AuthzFacade.java @@ -243,7 +243,7 @@ public interface AuthzFacade { public abstract Result<Void> getHistoryBySubject(AuthzTrans trans, HttpServletResponse resp, String type, String subject, int[] yyyymm, int sort); - /* + /* * Cache */ public abstract Result<Void> cacheClear(AuthzTrans trans, String pathParam); 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 323c9fe0..10138d2c 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 @@ -174,16 +174,16 @@ public abstract class AuthzFacadeImpl<NSS,PERMS,PERMKEY,ROLES,USERS,USERROLES,DE if (result.variables==null || result.variables.length<1) { detail = new String[1]; } else { - List<String> dlist = new ArrayList<String>(); - dlist.add(null); - String os; - for(Object s : result.variables) { - if(s!=null && (os=s.toString()).length()>0) { - dlist.add(os); - } - } - detail = new String[dlist.size()]; - dlist.toArray(detail); + List<String> dlist = new ArrayList<String>(); + dlist.add(null); + String os; + for(Object s : result.variables) { + if(s!=null && (os=s.toString()).length()>0) { + dlist.add(os); + } + } + detail = new String[dlist.size()]; + dlist.toArray(detail); } //int httpstatus; 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 56ba5f5f..26216c65 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 @@ -367,30 +367,30 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo PermRequest from = (PermRequest)req; String type = from.getType(); if(type==null) { - return Result.err(Result.ERR_BadData, "Invalid Perm Type"); + return Result.err(Result.ERR_BadData, "Invalid Perm Type"); } PermDAO.Data pd = new PermDAO.Data(); if(type.contains("@")) { - String[] split = Split.splitTrim(':', type); - pd.ns = split[0]; - pd.type=split.length>1?split[1]:""; - pd.instance = from.getInstance(); - pd.action = from.getAction(); - pd.description = from.getDescription(); - return Result.ok(pd); + String[] split = Split.splitTrim(':', type); + pd.ns = split[0]; + pd.type=split.length>1?split[1]:""; + pd.instance = from.getInstance(); + pd.action = from.getAction(); + pd.description = from.getDescription(); + return Result.ok(pd); } else { - Result<NsSplit> nss = q.deriveNsSplit(trans, from.getType()); - if (nss.isOK()) { - pd.ns=nss.value.ns; - pd.type = nss.value.name; - pd.instance = from.getInstance(); - pd.action = from.getAction(); - pd.description = from.getDescription(); - trans.checkpoint(pd.fullPerm(), Env.ALWAYS); - return Result.ok(pd); - } else { - return Result.err(nss); - } + Result<NsSplit> nss = q.deriveNsSplit(trans, from.getType()); + if (nss.isOK()) { + pd.ns=nss.value.ns; + pd.type = nss.value.name; + pd.instance = from.getInstance(); + pd.action = from.getAction(); + pd.description = from.getDescription(); + trans.checkpoint(pd.fullPerm(), Env.ALWAYS); + return Result.ok(pd); + } else { + return Result.err(nss); + } } } @@ -526,23 +526,23 @@ public class Mapper_2_0 implements Mapper<Nss, Perms, Pkey, Roles, Users, UserRo to.ns = Question.domain2ns(to.id); to.type = from.getType(); if(to.type!=null && to.type==CredDAO.FQI) { - to.cred = null; + to.cred = null; } else { - String passwd = from.getPassword(); - if (requiresPass) { - String ok = trans.org().isValidPassword(trans, to.id,passwd); - if (ok.length()>0) { - return Result.err(Status.ERR_BadData,ok); - } - } - if (passwd != null) { - to.cred = ByteBuffer.wrap(passwd.getBytes()); - to.type = CredDAO.RAW; - } else { - to.type = CredDAO.NONE; - } - } - + String passwd = from.getPassword(); + if (requiresPass) { + String ok = trans.org().isValidPassword(trans, to.id,passwd); + if (ok.length()>0) { + return Result.err(Status.ERR_BadData,ok); + } + } + if (passwd != null) { + to.cred = ByteBuffer.wrap(passwd.getBytes()); + to.type = CredDAO.RAW; + } else { + to.type = CredDAO.NONE; + } + } + // Note: Ensure requested EndDate created will match Organization Password Rules // P.S. Do not apply TempPassword rule here. Do that when you know you are doing a Create/Reset (see Service) to.expires = getExpires(trans.org(),Expiration.Password,base,from.getId()); 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 df8bde8b..56785fee 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 @@ -57,9 +57,9 @@ public class ServiceValidator extends Validator { if (pd==null) { msg("Perm Data is null."); } else { - if(!pd.ns.contains("@")) { - ns(pd.ns); - } + if(!pd.ns.contains("@")) { + ns(pd.ns); + } permType(pd.type,pd.ns); permInstance(pd.instance); permAction(pd.action); @@ -222,8 +222,8 @@ public class ServiceValidator extends Validator { public ServiceValidator user_role(String user, UserRoleDAO.Data urdd) { role(user,urdd.role); if(!urdd.role.startsWith(user)) { - nullOrBlank("UserRole.ns",urdd.ns); - nullOrBlank("UserRole.rname",urdd.rname); + nullOrBlank("UserRole.ns",urdd.ns); + nullOrBlank("UserRole.rname",urdd.rname); } return this; } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_BaseServiceImpl.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_BaseServiceImpl.java index 5e6cfb62..9a804c98 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_BaseServiceImpl.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_BaseServiceImpl.java @@ -75,20 +75,20 @@ import aaf.v2_0.Users; @RunWith(MockitoJUnitRunner.class) public abstract class JU_BaseServiceImpl { - protected AuthzCassServiceImpl<Nss, Perms, Pkey, Roles, Users, UserRoles, Delgs, Certs, Keys, Request, History, Error, Approvals> - acsi; - protected Mapper_2_0 mapper; + protected AuthzCassServiceImpl<Nss, Perms, Pkey, Roles, Users, UserRoles, Delgs, Certs, Keys, Request, History, Error, Approvals> + acsi; + protected Mapper_2_0 mapper; - @Mock + @Mock protected DefaultOrg org; - @Mock + @Mock protected DefaultOrgIdentity orgIdentity; // // NOTE: Annotation format (@Mock and @Spy) do NOT seem to always work as a Base Class, // so we construct manually. // -// Mock Objects +// Mock Objects protected HistoryDAO historyDAO = mock(HistoryDAO.class); protected CacheInfoDAO cacheInfoDAO = mock(CacheInfoDAO.class); protected CachedNSDAO nsDAO = mock(CachedNSDAO.class); @@ -102,47 +102,47 @@ public abstract class JU_BaseServiceImpl { protected DelegateDAO delegateDAO = mock(DelegateDAO.class); protected ApprovalDAO approvalDAO = mock(ApprovalDAO.class); - // Spy Objects + // Spy Objects @Spy protected static PropAccess access = new PropAccess(); @Spy - protected static AuthzEnv env = new AuthzEnv(access); + protected static AuthzEnv env = new AuthzEnv(access); @Spy protected static AuthzTrans trans = env.newTransNoAvg(); // @Spy doesn't seem to work on Question. @Spy protected Question question = spy(new Question(trans, - historyDAO,cacheInfoDAO,nsDAO,permDAO, - roleDAO,userRoleDAO,credDAO,certDAO, - locateDAO,futureDAO,delegateDAO,approvalDAO)); + historyDAO,cacheInfoDAO,nsDAO,permDAO, + roleDAO,userRoleDAO,credDAO,certDAO, + locateDAO,futureDAO,delegateDAO,approvalDAO)); - public void setUp() throws Exception { - when(trans.org()).thenReturn(org); - when(org.getDomain()).thenReturn("org.onap"); - Define.set(access); - access.setProperty(Config.CADI_LATITUDE, "38.0"); - access.setProperty(Config.CADI_LONGITUDE, "-72.0"); - - mapper = new Mapper_2_0(question); - acsi = new AuthzCassServiceImpl<>(trans, mapper, question); - } - - ////////// - // Common Data Objects - ///////// + public void setUp() throws Exception { + when(trans.org()).thenReturn(org); + when(org.getDomain()).thenReturn("org.onap"); + Define.set(access); + access.setProperty(Config.CADI_LATITUDE, "38.0"); + access.setProperty(Config.CADI_LONGITUDE, "-72.0"); + + mapper = new Mapper_2_0(question); + acsi = new AuthzCassServiceImpl<>(trans, mapper, question); + } + + ////////// + // Common Data Objects + ///////// protected List<NsDAO.Data> nsData(String name) { - NsDAO.Data ndd = new NsDAO.Data(); - ndd.name=name; - int dot = name.lastIndexOf('.'); - if(dot<0) { - ndd.parent="."; - } else { - ndd.parent=name.substring(0,dot); - } - List<NsDAO.Data> rv = new ArrayList<NsDAO.Data>(); - rv.add(ndd); - return rv; + NsDAO.Data ndd = new NsDAO.Data(); + ndd.name=name; + int dot = name.lastIndexOf('.'); + if(dot<0) { + ndd.parent="."; + } else { + ndd.parent=name.substring(0,dot); + } + List<NsDAO.Data> rv = new ArrayList<NsDAO.Data>(); + rv.add(ndd); + return rv; } /** @@ -155,36 +155,36 @@ public abstract class JU_BaseServiceImpl { * @param days */ protected void whenRole(AuthzTrans trans, String user, String ns, String role, boolean exists, int days) { - Result<List<UserRoleDAO.Data>> result; - if(exists) { - result = Result.ok(listOf(urData(user,ns,role,days))); - } else { - result = Result.ok(emptyList(UserRoleDAO.Data.class)); - } - when(question.userRoleDAO().read(trans, user, ns+'.'+role)).thenReturn(result); + Result<List<UserRoleDAO.Data>> result; + if(exists) { + result = Result.ok(listOf(urData(user,ns,role,days))); + } else { + result = Result.ok(emptyList(UserRoleDAO.Data.class)); + } + when(question.userRoleDAO().read(trans, user, ns+'.'+role)).thenReturn(result); } protected UserRoleDAO.Data urData(String user, String ns, String rname, int days) { - UserRoleDAO.Data urdd = new UserRoleDAO.Data(); - urdd.user = user; - urdd.ns = ns; - urdd.rname = rname; - urdd.role = ns + '.' + rname; - GregorianCalendar gc = new GregorianCalendar(); - gc.add(GregorianCalendar.DAY_OF_YEAR, days); - urdd.expires = gc.getTime(); - return urdd; + UserRoleDAO.Data urdd = new UserRoleDAO.Data(); + urdd.user = user; + urdd.ns = ns; + urdd.rname = rname; + urdd.role = ns + '.' + rname; + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.DAY_OF_YEAR, days); + urdd.expires = gc.getTime(); + return urdd; } protected <T> List<T> listOf(T t) { - List<T> list = new ArrayList<>(); - list.add(t); - return list; + List<T> list = new ArrayList<>(); + list.add(t); + return list; } protected <T> List<T> emptyList(Class<T> cls) { - return new ArrayList<>(); + return new ArrayList<>(); } } diff --git a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_ServiceImpl_createUserCred.java b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_ServiceImpl_createUserCred.java index 00da6b4c..2bb907ac 100644 --- a/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_ServiceImpl_createUserCred.java +++ b/auth/auth-service/src/test/java/org/onap/aaf/auth/service/test/JU_ServiceImpl_createUserCred.java @@ -49,100 +49,100 @@ import junit.framework.Assert; @RunWith(MockitoJUnitRunner.class) public class JU_ServiceImpl_createUserCred extends JU_BaseServiceImpl { - @Mock - private Result<CredDAO.Data> rcdd; - - @Before - public void setUp() throws Exception { - super.setUp(); - } + @Mock + private Result<CredDAO.Data> rcdd; + + @Before + public void setUp() throws Exception { + super.setUp(); + } @Test public void validCreateNewIsOwner() throws OrganizationException { - CredRequest cr = credRequest1(); - final String fqi = "bob@people.onap.org"; - when(trans.user()).thenReturn(fqi); - when(org.isValidPassword(trans, cr.getId(),cr.getPassword())).thenReturn(""); - when(org.isValidCred(trans, cr.getId())).thenReturn(true); - when(org.canHaveMultipleCreds(cr.getId())).thenReturn(true); - when(org.getIdentity(trans, cr.getId())).thenReturn(orgIdentity); - when(orgIdentity.isFound()).thenReturn(true); - final String ns = "org.onap.sample"; - whenRole(trans, fqi, ns, "owner", false, 100); - when(question.nsDAO().read(trans, ns)).thenReturn(Result.ok(nsData(ns))); - when(question.credDAO().readID(trans, cr.getId())).thenReturn(Result.ok(emptyList(CredDAO.Data.class))); - when(question.credDAO().create(any(AuthzTrans.class), any(CredDAO.Data.class) )).thenReturn(Result.ok(credDataFound(cr,100))); - when(question.credDAO().readNS(trans, ns)).thenReturn(Result.ok(listOf(credDataFound(cr,100)))); - Result<?> result = acsi.createUserCred(trans,cr); - // Owner may do FIRST Creds - Assert.assertEquals(Result.OK,result.status); + CredRequest cr = credRequest1(); + final String fqi = "bob@people.onap.org"; + when(trans.user()).thenReturn(fqi); + when(org.isValidPassword(trans, cr.getId(),cr.getPassword())).thenReturn(""); + when(org.isValidCred(trans, cr.getId())).thenReturn(true); + when(org.canHaveMultipleCreds(cr.getId())).thenReturn(true); + when(org.getIdentity(trans, cr.getId())).thenReturn(orgIdentity); + when(orgIdentity.isFound()).thenReturn(true); + final String ns = "org.onap.sample"; + whenRole(trans, fqi, ns, "owner", false, 100); + when(question.nsDAO().read(trans, ns)).thenReturn(Result.ok(nsData(ns))); + when(question.credDAO().readID(trans, cr.getId())).thenReturn(Result.ok(emptyList(CredDAO.Data.class))); + when(question.credDAO().create(any(AuthzTrans.class), any(CredDAO.Data.class) )).thenReturn(Result.ok(credDataFound(cr,100))); + when(question.credDAO().readNS(trans, ns)).thenReturn(Result.ok(listOf(credDataFound(cr,100)))); + Result<?> result = acsi.createUserCred(trans,cr); + // Owner may do FIRST Creds + Assert.assertEquals(Result.OK,result.status); } @Test public void validCreateNewOnlyAdmin() throws OrganizationException { - CredRequest cr = credRequest1(); - final String fqi = "bob@people.onap.org"; - when(trans.user()).thenReturn(fqi); - when(org.isValidPassword(trans, cr.getId(),cr.getPassword())).thenReturn(""); - when(org.isValidCred(trans, cr.getId())).thenReturn(true); - when(org.canHaveMultipleCreds(cr.getId())).thenReturn(true); - when(org.getIdentity(trans, cr.getId())).thenReturn(orgIdentity); - when(orgIdentity.isFound()).thenReturn(true); - final String ns = "org.onap.sample"; - whenRole(trans,fqi,ns,"owner",false, 100); - whenRole(trans,fqi,ns,"admin",true, 100); - when(question.nsDAO().read(trans, ns)).thenReturn(Result.ok(nsData(ns))); - when(question.credDAO().readID(trans, cr.getId())).thenReturn(Result.ok(emptyList(CredDAO.Data.class))); - when(question.credDAO().create(any(AuthzTrans.class), any(CredDAO.Data.class) )).thenReturn(Result.ok(credDataFound(cr,100))); - when(question.credDAO().readNS(trans, ns)).thenReturn(Result.ok(listOf(credDataFound(cr,100)))); - Result<?> result = acsi.createUserCred(trans,cr); - // Admins may not do FIRST Creds - Assert.assertEquals(Result.ERR_Denied,result.status); + CredRequest cr = credRequest1(); + final String fqi = "bob@people.onap.org"; + when(trans.user()).thenReturn(fqi); + when(org.isValidPassword(trans, cr.getId(),cr.getPassword())).thenReturn(""); + when(org.isValidCred(trans, cr.getId())).thenReturn(true); + when(org.canHaveMultipleCreds(cr.getId())).thenReturn(true); + when(org.getIdentity(trans, cr.getId())).thenReturn(orgIdentity); + when(orgIdentity.isFound()).thenReturn(true); + final String ns = "org.onap.sample"; + whenRole(trans,fqi,ns,"owner",false, 100); + whenRole(trans,fqi,ns,"admin",true, 100); + when(question.nsDAO().read(trans, ns)).thenReturn(Result.ok(nsData(ns))); + when(question.credDAO().readID(trans, cr.getId())).thenReturn(Result.ok(emptyList(CredDAO.Data.class))); + when(question.credDAO().create(any(AuthzTrans.class), any(CredDAO.Data.class) )).thenReturn(Result.ok(credDataFound(cr,100))); + when(question.credDAO().readNS(trans, ns)).thenReturn(Result.ok(listOf(credDataFound(cr,100)))); + Result<?> result = acsi.createUserCred(trans,cr); + // Admins may not do FIRST Creds + Assert.assertEquals(Result.ERR_Denied,result.status); } @Test public void validCreateExisting() throws OrganizationException { - CredRequest cr = credRequest1(); - when(org.isValidPassword(trans, cr.getId(),cr.getPassword())).thenReturn(""); - when(org.isValidCred(trans, cr.getId())).thenReturn(true); - when(org.canHaveMultipleCreds(cr.getId())).thenReturn(true); - when(org.getIdentity(trans, cr.getId())).thenReturn(orgIdentity); - when(orgIdentity.isFound()).thenReturn(true); - String ns = "org.onap.sample"; - when(question.nsDAO().read(trans, ns)).thenReturn(Result.ok(nsData(ns))); - - CredDAO.Data cdd = credDataFound(cr,100); - when(question.credDAO().create(any(AuthzTrans.class), any(CredDAO.Data.class) )).thenReturn(Result.ok(cdd)); - when(question.credDAO().readID(trans, cr.getId())).thenReturn(Result.ok(listOf(cdd))); + CredRequest cr = credRequest1(); + when(org.isValidPassword(trans, cr.getId(),cr.getPassword())).thenReturn(""); + when(org.isValidCred(trans, cr.getId())).thenReturn(true); + when(org.canHaveMultipleCreds(cr.getId())).thenReturn(true); + when(org.getIdentity(trans, cr.getId())).thenReturn(orgIdentity); + when(orgIdentity.isFound()).thenReturn(true); + String ns = "org.onap.sample"; + when(question.nsDAO().read(trans, ns)).thenReturn(Result.ok(nsData(ns))); + + CredDAO.Data cdd = credDataFound(cr,100); + when(question.credDAO().create(any(AuthzTrans.class), any(CredDAO.Data.class) )).thenReturn(Result.ok(cdd)); + when(question.credDAO().readID(trans, cr.getId())).thenReturn(Result.ok(listOf(cdd))); - Result<?> result = acsi.createUserCred(trans,cr); - Assert.assertEquals(Result.OK,result.status); + Result<?> result = acsi.createUserCred(trans,cr); + Assert.assertEquals(Result.OK,result.status); } private CredRequest credRequest1() { - CredRequest cr = new CredRequest(); - cr.setId("m12345@sample.onap.org"); - cr.setPassword("BobAndWeave"); - cr.setType(CredDAO.RAW); - return cr; + CredRequest cr = new CredRequest(); + cr.setId("m12345@sample.onap.org"); + cr.setPassword("BobAndWeave"); + cr.setType(CredDAO.RAW); + return cr; } private CredDAO.Data credDataFound(CredRequest cr, int days) { - CredDAO.Data cdd = new CredDAO.Data(); - cdd.id = cr.getId(); - cdd.ns = FQI.reverseDomain(cr.getId()); - cdd.other = 12345; - cdd.tag = "1355434"; - cdd.type = CredDAO.BASIC_AUTH_SHA256; - try { - cdd.cred = ByteBuffer.wrap(Hash.hashSHA256(cr.getPassword().getBytes())); - } catch (NoSuchAlgorithmException e) { - Assert.fail(e.getMessage()); - } - GregorianCalendar gc = new GregorianCalendar(); - gc.add(GregorianCalendar.DAY_OF_YEAR, days); - cdd.expires = gc.getTime(); - return cdd; + CredDAO.Data cdd = new CredDAO.Data(); + cdd.id = cr.getId(); + cdd.ns = FQI.reverseDomain(cr.getId()); + cdd.other = 12345; + cdd.tag = "1355434"; + cdd.type = CredDAO.BASIC_AUTH_SHA256; + try { + cdd.cred = ByteBuffer.wrap(Hash.hashSHA256(cr.getPassword().getBytes())); + } catch (NoSuchAlgorithmException e) { + Assert.fail(e.getMessage()); + } + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.DAY_OF_YEAR, days); + cdd.expires = gc.getTime(); + return cdd; } }
\ No newline at end of file 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 037ee8be..8c39e44d 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 @@ -83,9 +83,9 @@ public class AAFPermission implements Permission { * If you want a simple field comparison, it is faster without REGEX */ public boolean match(Permission p) { - if(p==null) { - return false; - } + if(p==null) { + return false; + } String aafNS; String aafType; String aafInstance; 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 7c843dbd..498f1bf9 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 @@ -67,20 +67,20 @@ public class PermEval { String[] skeys=Split.split(startChar,sInst); String[] pkeys=Split.split(startChar,pInst); if (pkeys.length<skeys.length) { - return false; + return false; } else if(pkeys.length > skeys.length && - (skeys.length==0 || !ASTERIX.equals(skeys[skeys.length-1]))) { - return false; + (skeys.length==0 || !ASTERIX.equals(skeys[skeys.length-1]))) { + 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])) { - if(i==skeys.length-1) { - // accept all after - return true; - } - continue; // Server data accepts all for this key spot + if(i==skeys.length-1) { + // accept all after + return true; + } + 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 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 efcaa7ef..2f2d2ac3 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 @@ -57,7 +57,7 @@ public class TestConnectivity { private static Map<String, String> aaf_urls; - public static void main(String[] args) { + public static void main(String[] args) { if (args.length<1) { System.out.println("Usage: ConnectivityTester <cadi_prop_files> [<AAF FQDN (i.e. aaf.dev.att.com)>]"); } else { @@ -84,48 +84,48 @@ public class TestConnectivity { SecuritySetter<HttpURLConnection> ss = si.defSS; permTest(locator,ss); } else { - ///////// - print(true,"Test Connections driven by AAFLocator"); - String serviceURI = aaf_urls.get(Config.AAF_URL); - - for (String url : new String[] { - serviceURI, - aaf_urls.get(Config.AAF_OAUTH2_TOKEN_URL), - aaf_urls.get(Config.AAF_OAUTH2_INTROSPECT_URL), - aaf_urls.get(Config.AAF_URL_CM), - aaf_urls.get(Config.AAF_URL_GUI), - aaf_urls.get(Config.AAF_URL_FS), - aaf_urls.get(Config.AAF_URL_HELLO) - }) { - URI uri = new URI(url); - Locator<URI> locator = new AAFLocator(si, uri); - try { - connectTest(locator, uri); - } catch (Exception e) { - e.printStackTrace(); - System.err.flush(); - } - } + ///////// + print(true,"Test Connections driven by AAFLocator"); + String serviceURI = aaf_urls.get(Config.AAF_URL); + + for (String url : new String[] { + serviceURI, + aaf_urls.get(Config.AAF_OAUTH2_TOKEN_URL), + aaf_urls.get(Config.AAF_OAUTH2_INTROSPECT_URL), + aaf_urls.get(Config.AAF_URL_CM), + aaf_urls.get(Config.AAF_URL_GUI), + aaf_urls.get(Config.AAF_URL_FS), + aaf_urls.get(Config.AAF_URL_HELLO) + }) { + URI uri = new URI(url); + Locator<URI> locator = new AAFLocator(si, uri); + try { + connectTest(locator, uri); + } catch (Exception e) { + e.printStackTrace(); + System.err.flush(); + } + } - ///////// - print(true,"Test Service for Perms driven by AAFLocator"); - Locator<URI> locator = new AAFLocator(si,new URI(serviceURI)); - for (SecuritySetter<HttpURLConnection> ss : lss) { - permTest(locator,ss); - } + ///////// + print(true,"Test Service for Perms driven by AAFLocator"); + Locator<URI> locator = new AAFLocator(si,new URI(serviceURI)); + for (SecuritySetter<HttpURLConnection> ss : lss) { + permTest(locator,ss); + } - ////////// - print(true,"Test essential BasicAuth Service call, driven by AAFLocator"); - boolean hasBath=false; - for (SecuritySetter<HttpURLConnection> ss : lss) { - if (ss instanceof HBasicAuthSS) { - hasBath=true; - basicAuthTest(new AAFLocator(si, new URI(serviceURI)),ss); - } - } - if(!hasBath) { - System.out.println("No User/Password to test"); - } + ////////// + print(true,"Test essential BasicAuth Service call, driven by AAFLocator"); + boolean hasBath=false; + for (SecuritySetter<HttpURLConnection> ss : lss) { + if (ss instanceof HBasicAuthSS) { + hasBath=true; + basicAuthTest(new AAFLocator(si, new URI(serviceURI)),ss); + } + } + if(!hasBath) { + System.out.println("No User/Password to test"); + } } } catch (Exception e) { @@ -137,7 +137,7 @@ public class TestConnectivity { } - private static List<SecuritySetter<HttpURLConnection>> loadSetters(PropAccess access, SecurityInfoC<HttpURLConnection> si) { + private static List<SecuritySetter<HttpURLConnection>> loadSetters(PropAccess access, SecurityInfoC<HttpURLConnection> si) { print(true,"Load Security Setters from Configuration Information"); String user = access.getProperty(Config.AAF_APPID); @@ -227,10 +227,10 @@ public class TestConnectivity { if ((uri = dl.get(li)) == null) { System.out.println("Locator Item empty"); } else { - System.out.printf("Located %s using %s\n",uri.toString(), locatorURI.toString()); + System.out.printf("Located %s using %s\n",uri.toString(), locatorURI.toString()); socket = new Socket(); try { - FixURIinfo fui = new FixURIinfo(uri); + FixURIinfo fui = new FixURIinfo(uri); try { socket.connect(new InetSocketAddress(fui.getHost(), fui.getPort()),3000); System.out.printf("Can Connect a Socket to %s %d\n",fui.getHost(),fui.getPort()); @@ -261,7 +261,7 @@ public class TestConnectivity { if (ss instanceof HRenewingTokenSS) { System.out.println(" " + ((HRenewingTokenSS)ss).tokenURL()); } else { - System.out.println(); + System.out.println(); } HClient client = new HClient(ss, uri, 3000); client.setMethod("GET"); 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 42efd89b..d5a2e58a 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 @@ -95,6 +95,6 @@ public class ErrMessage { } public Error getError(Future<?> future) throws APIException { - return errDF.newData().in(TYPE.JSON).load(future.body()).asObject(); + return errDF.newData().in(TYPE.JSON).load(future.body()).asObject(); } } 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 b43c418b..921b5096 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 @@ -100,25 +100,25 @@ public class Examples { } Class<?> cls=null; - int minorIdx = version.indexOf('_'); - if(minorIdx<0) { - throw new APIException("Invalid Interface Version " + version); - } - int minor = Integer.parseInt(version.substring(minorIdx+1)); - String vprefix=version.substring(0, minorIdx+1); - while(cls==null && minor>=0) { - try { - cls = Examples.class.getClassLoader().loadClass("aaf."+vprefix+minor+'.'+className); + int minorIdx = version.indexOf('_'); + if(minorIdx<0) { + throw new APIException("Invalid Interface Version " + version); + } + int minor = Integer.parseInt(version.substring(minorIdx+1)); + String vprefix=version.substring(0, minorIdx+1); + while(cls==null && minor>=0) { + try { + cls = Examples.class.getClassLoader().loadClass("aaf."+vprefix+minor+'.'+className); } catch (ClassNotFoundException e) { - if(--minor<0) { - throw new APIException("No Example for Version " + version + " found."); - } + if(--minor<0) { + throw new APIException("No Example for Version " + version + " found."); + } } - } - - if(cls==null) { - throw new APIException("ERROR: " + "aaf."+vprefix+"X not found."); - } + } + + if(cls==null) { + throw new APIException("ERROR: " + "aaf."+vprefix+"X not found."); + } Method meth; try { 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 e40743da..40684057 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 @@ -79,123 +79,123 @@ public abstract class AAFCon<CLIENT> implements Connector { final public RosettaEnv env; protected AAFCon(AAFCon<CLIENT> copy) { - access = copy.access; - apiVersion = access.getProperty(Config.AAF_API_VERSION, Config.AAF_DEFAULT_API_VERSION); - timeout = copy.timeout; - cleanInterval = copy.cleanInterval; - connTimeout = copy.connTimeout; - highCount = copy.highCount; - userExpires = copy.userExpires; - usageRefreshTriggerCount = copy.usageRefreshTriggerCount; - permsDF = copy.permsDF; - certsDF = copy.certsDF; - usersDF = copy.usersDF; - errDF = copy.errDF; - app = copy.app; - si = copy.si; - env = copy.env; - realm = copy.realm; - } - protected AAFCon(Access access, String tag, SecurityInfoC<CLIENT> si) throws CadiException{ - apiVersion = access.getProperty(Config.AAF_API_VERSION, Config.AAF_DEFAULT_API_VERSION); - 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 - str = tag; - } else { - throw new CadiException("A URL or " + tag + " property is required."); - } - } - try { - RegistrationPropHolder rph = new RegistrationPropHolder(access, 0); - str = rph.replacements("AAFCon",str, null,null); - } catch (UnknownHostException e) { - throw new CadiException(e); - } - access.printf(Level.INFO, "AAFCon has URL of %s",str); - setInitURI(str); - } - 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 - String mechid = access.getProperty(Config.AAF_APPID, null); - if (mechid==null) { - mechid=access.getProperty(Config.OAUTH_CLIENT_ID,null); - } - String alias = access.getProperty(Config.CADI_ALIAS, null); - if(alias != null) { - si.defSS=x509Alias(alias); - set(si.defSS); - } else { - - String encpass = access.getProperty(Config.AAF_APPPASS, null); - if (encpass==null) { - encpass = access.getProperty(Config.OAUTH_CLIENT_SECRET,null); - } - - if (encpass==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 { - if (mechid!=null) { - si.defSS=basicAuth(mechid, encpass); - set(si.defSS); - } else { - si.defSS=new SecuritySetter<CLIENT>() { - - @Override - public String getID() { - return ""; - } - - @Override - public void setSecurity(CLIENT client) throws CadiException { - throw new CadiException("AAFCon has not been initialized with Credentials (SecuritySetter)"); - } - - @Override - public int setLastResponse(int respCode) { - return 0; - } - }; - set(si.defSS); - } - } - } - } - - timeout = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT, Config.AAF_CALL_TIMEOUT_DEF)); - cleanInterval = Integer.parseInt(access.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)); - highCount = Integer.parseInt(access.getProperty(Config.AAF_HIGH_COUNT, Config.AAF_HIGH_COUNT_DEF).trim()); - connTimeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF).trim()); - userExpires = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim()); - usageRefreshTriggerCount = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim())-1; // zero based - - app=FQI.reverseDomain(si.defSS.getID()); - //TODO Get Realm from AAF - realm="people.osaaf.org"; - - env = new RosettaEnv(); - permsDF = env.newDataFactory(Perms.class); - usersDF = env.newDataFactory(Users.class); - certsDF = env.newDataFactory(Certs.class); - certsDF.rootMarshal(new CertsMarshal()); // Speedier Marshaling - errDF = env.newDataFactory(Error.class); - } catch (APIException e) { - throw new CadiException("AAFCon cannot be configured",e); - } - } - protected abstract URI initURI(); + access = copy.access; + apiVersion = access.getProperty(Config.AAF_API_VERSION, Config.AAF_DEFAULT_API_VERSION); + timeout = copy.timeout; + cleanInterval = copy.cleanInterval; + connTimeout = copy.connTimeout; + highCount = copy.highCount; + userExpires = copy.userExpires; + usageRefreshTriggerCount = copy.usageRefreshTriggerCount; + permsDF = copy.permsDF; + certsDF = copy.certsDF; + usersDF = copy.usersDF; + errDF = copy.errDF; + app = copy.app; + si = copy.si; + env = copy.env; + realm = copy.realm; + } + protected AAFCon(Access access, String tag, SecurityInfoC<CLIENT> si) throws CadiException{ + apiVersion = access.getProperty(Config.AAF_API_VERSION, Config.AAF_DEFAULT_API_VERSION); + 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 + str = tag; + } else { + throw new CadiException("A URL or " + tag + " property is required."); + } + } + try { + RegistrationPropHolder rph = new RegistrationPropHolder(access, 0); + str = rph.replacements("AAFCon",str, null,null); + } catch (UnknownHostException e) { + throw new CadiException(e); + } + access.printf(Level.INFO, "AAFCon has URL of %s",str); + setInitURI(str); + } + 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 + String mechid = access.getProperty(Config.AAF_APPID, null); + if (mechid==null) { + mechid=access.getProperty(Config.OAUTH_CLIENT_ID,null); + } + String alias = access.getProperty(Config.CADI_ALIAS, null); + if(alias != null) { + si.defSS=x509Alias(alias); + set(si.defSS); + } else { + + String encpass = access.getProperty(Config.AAF_APPPASS, null); + if (encpass==null) { + encpass = access.getProperty(Config.OAUTH_CLIENT_SECRET,null); + } + + if (encpass==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 { + if (mechid!=null) { + si.defSS=basicAuth(mechid, encpass); + set(si.defSS); + } else { + si.defSS=new SecuritySetter<CLIENT>() { + + @Override + public String getID() { + return ""; + } + + @Override + public void setSecurity(CLIENT client) throws CadiException { + throw new CadiException("AAFCon has not been initialized with Credentials (SecuritySetter)"); + } + + @Override + public int setLastResponse(int respCode) { + return 0; + } + }; + set(si.defSS); + } + } + } + } + + timeout = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT, Config.AAF_CALL_TIMEOUT_DEF)); + cleanInterval = Integer.parseInt(access.getProperty(Config.AAF_CLEAN_INTERVAL, Config.AAF_CLEAN_INTERVAL_DEF)); + highCount = Integer.parseInt(access.getProperty(Config.AAF_HIGH_COUNT, Config.AAF_HIGH_COUNT_DEF).trim()); + connTimeout = Integer.parseInt(access.getProperty(Config.AAF_CONN_TIMEOUT, Config.AAF_CONN_TIMEOUT_DEF).trim()); + userExpires = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim()); + usageRefreshTriggerCount = Integer.parseInt(access.getProperty(Config.AAF_USER_EXPIRES, Config.AAF_USER_EXPIRES_DEF).trim())-1; // zero based + + app=FQI.reverseDomain(si.defSS.getID()); + //TODO Get Realm from AAF + realm="people.osaaf.org"; + + env = new RosettaEnv(); + permsDF = env.newDataFactory(Perms.class); + usersDF = env.newDataFactory(Users.class); + certsDF = env.newDataFactory(Certs.class); + certsDF.rootMarshal(new CertsMarshal()); // Speedier Marshaling + errDF = env.newDataFactory(Error.class); + } catch (APIException e) { + throw new CadiException("AAFCon cannot be configured",e); + } + } + protected abstract URI initURI(); protected abstract void setInitURI(String uriString) throws CadiException; public final String aafVersion() { - return apiVersion; + return apiVersion; } /** @@ -207,8 +207,8 @@ public abstract class AAFCon<CLIENT> implements Connector { * @throws CadiException */ public Rcli<CLIENT> client() throws CadiException { - return client(apiVersion); - } + return client(apiVersion); + } /** * Use this call to get the appropriate client based on configuration (HTTP, future) @@ -218,7 +218,7 @@ public abstract class AAFCon<CLIENT> implements Connector { * @throws CadiException */ public Rcli<CLIENT> client(final String apiVersion) throws CadiException { - Rcli<CLIENT> client = clients.get(apiVersion); + Rcli<CLIENT> client = clients.get(apiVersion); if (client==null) { client = rclient(initURI(),si.defSS); client.apiVersion(apiVersion) 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 eda4a5aa..ed24b1ee 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 @@ -91,7 +91,7 @@ public class AAFLocator extends AbsAAFLocator<BasicTrans> { } if(si.access.willLog(Access.Level.DEBUG)) { - si.access.log(Access.Level.DEBUG, "Root URI:",client.getURI()); + si.access.log(Access.Level.DEBUG, "Root URI:",client.getURI()); } } 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 ace2c73f..9f537bd9 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 @@ -122,7 +122,7 @@ public class AAFLurPerm extends AbsAAFLur<AAFPermission> { StringBuilder sb = new StringBuilder("/authz/perms/user/"); sb.append(name); if(details) { - sb.append("?force"); + sb.append("?force"); } Future<Perms> fp = client.read(sb.toString(),aaf.permsDF); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFSingleLocator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFSingleLocator.java index 80e9f190..8f4fff67 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFSingleLocator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/aaf/v2_0/AAFSingleLocator.java @@ -36,62 +36,62 @@ import org.onap.aaf.cadi.LocatorException; * */ public class AAFSingleLocator implements Locator<URI> { - - private final URI uri; + + private final URI uri; - /** - * NS here is "container" ns. AAF NS is assumed to be AAF_NS at this level of client code. - * @param cont_ns - * @param prefix - * @param version - * @throws URISyntaxException - */ - public AAFSingleLocator(final String uri) throws URISyntaxException { - this.uri = new URI(uri); - } - - @Override - public URI get(Item item) throws LocatorException { - return uri; - } + /** + * NS here is "container" ns. AAF NS is assumed to be AAF_NS at this level of client code. + * @param cont_ns + * @param prefix + * @param version + * @throws URISyntaxException + */ + public AAFSingleLocator(final String uri) throws URISyntaxException { + this.uri = new URI(uri); + } + + @Override + public URI get(Item item) throws LocatorException { + return uri; + } - @Override - public boolean hasItems() { - return true; - } + @Override + public boolean hasItems() { + return true; + } - @Override - public void invalidate(Item item) throws LocatorException { - } + @Override + public void invalidate(Item item) throws LocatorException { + } - @Override - public Item best() throws LocatorException { - return new SingleItem(); - } + @Override + public Item best() throws LocatorException { + return new SingleItem(); + } - @Override - public Item first() throws LocatorException { - return new SingleItem(); - } + @Override + public Item first() throws LocatorException { + return new SingleItem(); + } - @Override - public Item next(Item item) throws LocatorException { - return null; // only one item - } + @Override + public Item next(Item item) throws LocatorException { + return null; // only one item + } - @Override - public boolean refresh() { - return false; - } + @Override + public boolean refresh() { + return false; + } - @Override - public void destroy() { - } - - private class SingleItem implements Item { - } - - public static AAFSingleLocator create(Access access, String url) throws URISyntaxException { - return new AAFSingleLocator(url); - } + @Override + public void destroy() { + } + + private class SingleItem implements Item { + } + + public static AAFSingleLocator create(Access access, String url) throws URISyntaxException { + return new AAFSingleLocator(url); + } } 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 a25d2502..81b55507 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 @@ -89,14 +89,14 @@ public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpT private void initMapBathConverter() { String csvFile = access.getProperty(Config.CADI_BATH_CONVERT, null); if(csvFile==null) { - mapIds=null; + mapIds=null; } else { - try { - mapIds = new MapBathConverter(access, new CSV(access,csvFile)); - access.log(Level.INIT,"Basic Auth Conversion using",csvFile,"enabled" ); - } catch (IOException | CadiException e) { - access.log(e,"Bath Map Conversion is not initialized (non fatal)"); - } + try { + mapIds = new MapBathConverter(access, new CSV(access,csvFile)); + access.log(Level.INIT,"Basic Auth Conversion using",csvFile,"enabled" ); + } catch (IOException | CadiException e) { + access.log(e,"Bath Map Conversion is not initialized (non fatal)"); + } } } @@ -112,7 +112,7 @@ public class AAFTaf<CLIENT> extends AbsUserCache<AAFPermission> implements HttpT aaf.access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); } if(mapIds != null) { - authz = mapIds.convert(access, authz); + authz = mapIds.convert(access, authz); } try { 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 e43250a0..2fe3ffdb 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,20 +66,20 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> public AbsAAFLocator(Access access, String name, final long refreshMin) throws LocatorException { - RegistrationPropHolder rph; - try { - rph = new RegistrationPropHolder(access, 0); - } catch (UnknownHostException | CadiException e1) { - throw new LocatorException(e1); - } + RegistrationPropHolder rph; try { - aaf_locator_host = rph.replacements(getClass().getSimpleName(),"https://"+Config.AAF_LOCATE_URL_TAG,null,null); - if(aaf_locator_host.endsWith("/locate")) { + rph = new RegistrationPropHolder(access, 0); + } catch (UnknownHostException | CadiException e1) { + throw new LocatorException(e1); + } + try { + aaf_locator_host = rph.replacements(getClass().getSimpleName(),"https://"+Config.AAF_LOCATE_URL_TAG,null,null); + if(aaf_locator_host.endsWith("/locate")) { aaf_locator_uri = new URI(aaf_locator_host); - } else { - aaf_locator_uri = new URI(aaf_locator_host+"/locate"); - } - + } else { + aaf_locator_uri = new URI(aaf_locator_host+"/locate"); + } + access.printf(Level.INFO, "AbsAAFLocator AAF URI is %s",aaf_locator_uri); } catch (URISyntaxException e) { throw new LocatorException(e); @@ -122,9 +122,9 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> } public static Locator<URI> create(final String name, final String version) throws LocatorException { - if(locatorCreator==null) { - throw new LocatorException("LocatorCreator is not set"); - } + if(locatorCreator==null) { + throw new LocatorException("LocatorCreator is not set"); + } return locatorCreator.create(name, version); } @@ -138,7 +138,7 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> if (path.length>1 && "locate".equals(path[1])) { return path[2]; } else if(path.length>1) { - return path[1]; + return path[1]; } else { return locatorURI.toString(); } @@ -471,8 +471,8 @@ public abstract class AbsAAFLocator<TRANS extends Trans> implements Locator<URI> } protected void clear() { - epList.clear(); - earliest=0L; + epList.clear(); + earliest=0L; } 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 34c55cee..ac6fc063 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 @@ -65,7 +65,7 @@ public abstract class AbsAAFLur<PERM extends Permission> extends AbsUserCache<PE } public void details(boolean on) { - details = on; + details = on; } 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 1a1d68da..1f6937bb 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 @@ -88,7 +88,7 @@ import locate.v1_1.Configuration.Props; public class Agent { private static final String AGENT_LOAD_URLS = "Agent:loadURLs"; - private static final String HASHES = "################################################################"; + private static final String HASHES = "################################################################"; private static final String PRINT = "print"; private static final String FILE = "file"; public static final String PKCS12 = "pkcs12"; @@ -119,11 +119,11 @@ public class Agent { Config.CADI_ALIAS, Config.CADI_X509_ISSUERS }); private static List<String> LOC_TAGS = Arrays.asList(new String[] { - Config.CADI_LATITUDE, Config.CADI_LONGITUDE - }); + Config.CADI_LATITUDE, Config.CADI_LONGITUDE + }); // Note: This is set by loadURLs. Use that function as singleton, not directly. - private static Map<String,String> aaf_urls = null; - private static boolean configNoPasswd = false; + private static Map<String,String> aaf_urls = null; + private static boolean configNoPasswd = false; public static void main(String[] args) { @@ -143,83 +143,83 @@ public class Agent { String[] newArgs = new String[args.length-1]; System.arraycopy(args, 1, newArgs, 0, newArgs.length); if(newArgs.length>0 && newArgs[0].indexOf('@')>=0) { - newArgs[0]=FQI.reverseDomain(newArgs[0])+".props"; + newArgs[0]=FQI.reverseDomain(newArgs[0])+".props"; } - TestConnectivity.main(newArgs); + TestConnectivity.main(newArgs); } else { try { AAFSSO aafsso=null; PropAccess access=null; - String hasEtc = null; + String hasEtc = null; for(String a : args) { - if(a.startsWith(Config.CADI_PROP_FILES)) { - access = new PropAccess(args); - break; - } else if(a.startsWith(Config.CADI_ETCDIR)) { - int idx = a.indexOf('='); - if(idx>=0 && idx<a.length()) { - hasEtc = a.substring(idx+1); - } - } else if(a.equals("--nopasswd")) { - configNoPasswd=true; - } + if(a.startsWith(Config.CADI_PROP_FILES)) { + access = new PropAccess(args); + break; + } else if(a.startsWith(Config.CADI_ETCDIR)) { + int idx = a.indexOf('='); + if(idx>=0 && idx<a.length()) { + hasEtc = a.substring(idx+1); + } + } else if(a.equals("--nopasswd")) { + configNoPasswd=true; + } } if(access==null) { - if(args.length>1 && args[1].contains("@")) { - String domain = FQI.reverseDomain(args[1]); - if(domain!=null) { - if(hasEtc==null) { - hasEtc = "."; - } - File etc = new File(hasEtc); - if(etc.exists()) { - File nsprops = new File(etc,domain+".props"); - if(nsprops.exists()) { - access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()}); - } - } - } - } + if(args.length>1 && args[1].contains("@")) { + String domain = FQI.reverseDomain(args[1]); + if(domain!=null) { + if(hasEtc==null) { + hasEtc = "."; + } + File etc = new File(hasEtc); + if(etc.exists()) { + File nsprops = new File(etc,domain+".props"); + if(nsprops.exists()) { + access = new PropAccess(new String[] {Config.CADI_PROP_FILES+'='+nsprops.getAbsolutePath()}); + } + } + } + } } if(access==null) { - for(Entry<Object, Object> es : System.getProperties().entrySet()) { - if(Config.CADI_PROP_FILES.equals(es.getKey())) { - access = new PropAccess(); - } - } + for(Entry<Object, Object> es : System.getProperties().entrySet()) { + if(Config.CADI_PROP_FILES.equals(es.getKey())) { + access = new PropAccess(); + } + } } - // When using Config file, check if Cred Exists, and if not, work with Deployer. - if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) { - // not enough credentials to use Props. Use AAFSSO - access = null; - } + // When using Config file, check if Cred Exists, and if not, work with Deployer. + if(access!=null && !"config".equals(args[0]) && access.getProperty(Config.AAF_APPPASS)==null && access.getProperty(Config.CADI_ALIAS)==null) { + // not enough credentials to use Props. Use AAFSSO + access = null; + } if(access==null) { - if (args.length>1 && args[0].equals("validate") ) { - int idx = args[1].indexOf('='); - aafsso = null; - access = new PropAccess( - (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+ - '='+ - (idx<0?args[1]:args[1].substring(idx+1))); - } else { - aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() { - @Override - public Properties process(String[] args, Properties props) { - if (args.length>1) { - if (!args[0].equals("keypairgen")) { - props.put(Config.AAF_APPID, args[1]); - } - } - return props; - } - }); - access = aafsso.access(); - } + if (args.length>1 && args[0].equals("validate") ) { + int idx = args[1].indexOf('='); + aafsso = null; + access = new PropAccess( + (idx<0?Config.CADI_PROP_FILES:args[1].substring(0, idx))+ + '='+ + (idx<0?args[1]:args[1].substring(idx+1))); + } else { + aafsso= new AAFSSO(args, new AAFSSO.ProcessArgs() { + @Override + public Properties process(String[] args, Properties props) { + if (args.length>1) { + if (!args[0].equals("keypairgen")) { + props.put(Config.AAF_APPID, args[1]); + } + } + return props; + } + }); + access = aafsso.access(); + } } if (aafsso!=null && aafsso.loginOnly()) { @@ -230,13 +230,13 @@ public class Agent { env = new RosettaEnv(access.getProperties()); Deque<String> cmds = new ArrayDeque<String>(); for (String p : args) { - int eq; + int eq; if ("-noexit".equalsIgnoreCase(p)) { doExit = false; } else if ((eq=p.indexOf('=')) < 0) { cmds.add(p); } else { - access.setProperty(p.substring(0,eq), p.substring(eq+1)); + access.setProperty(p.substring(0,eq), p.substring(eq+1)); } } @@ -328,7 +328,7 @@ public class Agent { keypairGen(trans, access, cmds); break; case "config": - config(trans,access,args,cmds); + config(trans,access,args,cmds); break; case "validate": validate(access); @@ -365,62 +365,62 @@ public class Agent { } public synchronized static Map<String,String> loadURLs(Access access) throws UnknownHostException, CadiException { - if(aaf_urls==null) { - Map<String,String> rv = new HashMap<>(); - RegistrationPropHolder rph = new RegistrationPropHolder(access, 0); - String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null); - dot_le=dot_le==null?"":'.'+dot_le; - String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION); - for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) { - String tag; - String append=null; - switch(u) { - case "aaf": tag = Config.AAF_URL; break; - case "locate":tag = Config.AAF_LOCATE_URL; break; - case "oauth": tag = Config.AAF_URL_OAUTH; break; - case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break; - case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break; - case "cm": tag = Config.AAF_URL_CM; break; - case "gui": tag = Config.AAF_URL_GUI; break; - case "fs": tag = Config.AAF_URL_FS; break; - case "hello": tag = Config.AAF_URL_HELLO; break; - default: - tag = "aaf_url_" + u; - } - String value; - if((value=access.getProperty(tag,null))==null) { - String proto = "fs".equals(u)?"http://":"https://"; - String lhost; - if("locate".equals(u)) { - lhost=rph.default_fqdn; - } else { - lhost=Config.AAF_LOCATE_URL_TAG; - } - value = rph.replacements(AGENT_LOAD_URLS, - proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version, - null,dot_le); - if(append!=null) { - value+=append; - } - } else { - value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le); - } - rv.put(tag, value); - }; - aaf_urls = rv; - } - return aaf_urls; - } + if(aaf_urls==null) { + Map<String,String> rv = new HashMap<>(); + RegistrationPropHolder rph = new RegistrationPropHolder(access, 0); + String dot_le = access.getProperty(Config.AAF_LOCATOR_CONTAINER,null); + dot_le=dot_le==null?"":'.'+dot_le; + String version = access.getProperty(Config.AAF_API_VERSION,Config.AAF_DEFAULT_API_VERSION); + for(String u : new String[] {"locate","aaf","oauth","cm","gui","fs","hello","token","introspect"}) { + String tag; + String append=null; + switch(u) { + case "aaf": tag = Config.AAF_URL; break; + case "locate":tag = Config.AAF_LOCATE_URL; break; + case "oauth": tag = Config.AAF_URL_OAUTH; break; + case "token": tag = Config.AAF_OAUTH2_TOKEN_URL; append="/token"; break; + case "introspect": tag = Config.AAF_OAUTH2_INTROSPECT_URL; append="/introspect"; break; + case "cm": tag = Config.AAF_URL_CM; break; + case "gui": tag = Config.AAF_URL_GUI; break; + case "fs": tag = Config.AAF_URL_FS; break; + case "hello": tag = Config.AAF_URL_HELLO; break; + default: + tag = "aaf_url_" + u; + } + String value; + if((value=access.getProperty(tag,null))==null) { + String proto = "fs".equals(u)?"http://":"https://"; + String lhost; + if("locate".equals(u)) { + lhost=rph.default_fqdn; + } else { + lhost=Config.AAF_LOCATE_URL_TAG; + } + value = rph.replacements(AGENT_LOAD_URLS, + proto + lhost + "/%CNS.%AAF_NS." + ("aaf".equals(u)?"service":u) + ':' + version, + null,dot_le); + if(append!=null) { + value+=append; + } + } else { + value = rph.replacements(AGENT_LOAD_URLS, value,null,dot_le); + } + rv.put(tag, value); + }; + aaf_urls = rv; + } + return aaf_urls; + } - public static void fillMissing(PropAccess access, Map<String, String> map) { - for(Entry<String, String> es : map.entrySet()) { - if(access.getProperty(es.getKey())==null) { - access.setProperty(es.getKey(),es.getValue()); - } - } - } + public static void fillMissing(PropAccess access, Map<String, String> map) { + for(Entry<String, String> es : map.entrySet()) { + if(access.getProperty(es.getKey())==null) { + access.setProperty(es.getKey(),es.getValue()); + } + } + } - private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException { + private static synchronized AAFCon<?> aafcon(Access access) throws APIException, CadiException, LocatorException { if (aafcon==null) { aafcon = new AAFConHttp(access,Config.AAF_URL_CM); } @@ -453,7 +453,7 @@ public class Agent { if (cmds.size()<1) { String alias = env.getProperty(Config.CADI_ALIAS); if(alias==null) { - alias = env.getProperty(Config.AAF_APPID); + alias = env.getProperty(Config.AAF_APPID); } return alias!=null?alias:AAFSSO.cons.readLine("AppID: "); } @@ -803,8 +803,8 @@ public class Agent { File chalFile = new File(dir,a.getNs()+".chal"); if(chalFile.exists()) { fis.close(); - fis = new FileInputStream(chalFile); - props.load(fis); + fis = new FileInputStream(chalFile); + props.load(fis); } } finally { fis.close(); @@ -862,66 +862,66 @@ public class Agent { private static void config(Trans trans, PropAccess propAccess, String[] args, Deque<String> cmds) throws Exception { TimeTaken tt = trans.start("Get Configuration", Env.REMOTE); try { - final String fqi = fqi(cmds); - Artifact arti = new Artifact(); - arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir"))); - arti.setNs(FQI.reverseDomain(fqi)); + final String fqi = fqi(cmds); + Artifact arti = new Artifact(); + arti.setDir(propAccess.getProperty(Config.CADI_ETCDIR, System.getProperty("user.dir"))); + arti.setNs(FQI.reverseDomain(fqi)); PropHolder loc = PropHolder.get(arti, "location.props"); PropHolder cred = PropHolder.get(arti,"cred.props"); PropHolder app= PropHolder.get(arti,"props"); for(String c : args) { - int idx = c.indexOf('='); - if(idx>0) { - app.add(c.substring(0,idx), c.substring(idx+1)); - } + int idx = c.indexOf('='); + if(idx>0) { + app.add(c.substring(0,idx), c.substring(idx+1)); + } } app.add(Config.CADI_PROP_FILES, loc.getPath()+':'+cred.getPath()); for (String tag : LOC_TAGS) { - loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag)); + loc.add(tag, getProperty(propAccess, trans, false, tag, "%s: ",tag)); } String keyfile = cred.getKeyPath(); if(keyfile!=null) { - File fkeyfile = new File(keyfile); - if(!fkeyfile.exists()) { - ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen()); - } + File fkeyfile = new File(keyfile); + if(!fkeyfile.exists()) { + ArtifactDir.write(fkeyfile,Chmod.to400,Symm.keygen()); + } } cred.add(Config.CADI_KEYFILE, cred.getKeyPath()); final String ssoAppID = propAccess.getProperty(Config.AAF_APPID); if(fqi!=null && fqi.equals(ssoAppID)) { - cred.addEnc(Config.AAF_APPPASS, propAccess, null); + cred.addEnc(Config.AAF_APPPASS, propAccess, null); // only Ask for Password when starting scratch } else if(propAccess.getProperty(Config.CADI_PROP_FILES)==null) { - if(!configNoPasswd) { - char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi); - if(pwd.length>0) { - cred.addEnc(Config.AAF_APPPASS, new String(pwd)); - } - } + if(!configNoPasswd) { + char[] pwd = AAFSSO.cons.readPassword("Password for %s (leave blank for NO password): ", fqi); + if(pwd.length>0) { + cred.addEnc(Config.AAF_APPPASS, new String(pwd)); + } + } } // load all properties that are already setup. Map<String, String> aaf_urls = loadURLs(propAccess); for(Entry<String, String> es : aaf_urls.entrySet()) { - app.add(es.getKey(), es.getValue()); + app.add(es.getKey(), es.getValue()); } app.add(Config.AAF_LOCATE_URL, Config.getAAFLocateUrl(propAccess)); app.add(Config.AAF_ENV,propAccess, "DEV"); String release = propAccess.getProperty(Config.AAF_DEPLOYED_VERSION); if(release==null) { - release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null); + release = System.getProperty(Config.AAF_DEPLOYED_VERSION,null); } if(release!=null) { - app.add(Config.AAF_DEPLOYED_VERSION, release); + app.add(Config.AAF_DEPLOYED_VERSION, release); } for(Entry<Object, Object> aaf_loc_prop : propAccess.getProperties().entrySet()) { - String key = aaf_loc_prop.getKey().toString(); - if(key.startsWith("aaf_locator")) { - app.add(key, aaf_loc_prop.getValue().toString()); - } + String key = aaf_loc_prop.getKey().toString(); + if(key.startsWith("aaf_locator")) { + app.add(key, aaf_loc_prop.getValue().toString()); + } } app.add(Config.AAF_APPID, fqi); @@ -932,64 +932,64 @@ public class Agent { File origTruststore = new File(cts); File newTruststore = new File(app.getDir(),origTruststore.getName()); if(!newTruststore.exists()) { - if (!origTruststore.exists()) { - // Try same directory as cadi_prop_files - String cpf = propAccess.getProperty(Config.CADI_PROP_FILES); - if (cpf!=null) { - for (String f : Split.split(File.pathSeparatorChar, cpf)) { - File fcpf = new File(f); - if (fcpf.exists()) { - int lastSep = cts.lastIndexOf(File.pathSeparator); - origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts); - if (origTruststore.exists()) { - break; - } - } - } - if (!origTruststore.exists()) { - throw new CadiException(cts + " does not exist"); - } - } - - } - if (!newTruststore.exists() && origTruststore.exists()) { - Files.copy(origTruststore.toPath(), newTruststore.toPath()); - } + if (!origTruststore.exists()) { + // Try same directory as cadi_prop_files + String cpf = propAccess.getProperty(Config.CADI_PROP_FILES); + if (cpf!=null) { + for (String f : Split.split(File.pathSeparatorChar, cpf)) { + File fcpf = new File(f); + if (fcpf.exists()) { + int lastSep = cts.lastIndexOf(File.pathSeparator); + origTruststore = new File(fcpf.getParentFile(),lastSep>=0?cts.substring(lastSep):cts); + if (origTruststore.exists()) { + break; + } + } + } + if (!origTruststore.exists()) { + throw new CadiException(cts + " does not exist"); + } + } + + } + if (!newTruststore.exists() && origTruststore.exists()) { + Files.copy(origTruststore.toPath(), newTruststore.toPath()); + } } - System.out.println("New Truststore is " + newTruststore); + System.out.println("New Truststore is " + newTruststore); cred.add(Config.CADI_TRUSTSTORE, newTruststore.getCanonicalPath()); cred.add(Config.CADI_TRUSTSTORE_PASSWORD, "changeit" /* Java default */); String cpf = propAccess.getProperty(Config.CADI_PROP_FILES); if (cpf!=null){ - String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf); + String[] propFiles = Split.splitTrim(File.pathSeparatorChar, cpf); for (int pfi = propFiles.length-1;pfi>=0;--pfi) { - String f = propFiles[pfi]; + String f = propFiles[pfi]; 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()) { - boolean lower = true; - String key = prop.getKey().toString(); - if(LOC_TAGS.contains(key)) { - break; - } - for(int i=0;lower && i<key.length();++i) { - if(Character.isUpperCase(key.charAt(i))) { - lower = false; - } - } - if(lower) { - PropHolder ph = CRED_TAGS.contains(key)?cred:app; - if(key.endsWith("_password")) { - ph.addEnc(key, prop.getValue().toString()); - } else { - ph.add(key, prop.getValue().toString()); - } - } + boolean lower = true; + String key = prop.getKey().toString(); + if(LOC_TAGS.contains(key)) { + break; + } + for(int i=0;lower && i<key.length();++i) { + if(Character.isUpperCase(key.charAt(i))) { + lower = false; + } + } + if(lower) { + PropHolder ph = CRED_TAGS.contains(key)?cred:app; + if(key.endsWith("_password")) { + ph.addEnc(key, prop.getValue().toString()); + } else { + ph.add(key, prop.getValue().toString()); + } + } } } finally { fis.close(); @@ -999,12 +999,12 @@ public class Agent { aafcon = aafcon(propAccess); if (aafcon!=null) { // get Properties from Remote AAF for (Props props : aafProps(trans,aafcon,getProperty(propAccess,aafcon.env,false,Config.AAF_LOCATE_URL,"AAF Locator URL: "),fqi)) { - PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app; - if(props.getTag().endsWith("_password")) { - ph.addEnc(props.getTag(), props.getValue()); - } else { - ph.add(props.getTag(), props.getValue()); - } + PropHolder ph = CRED_TAGS.contains(props.getTag())?cred:app; + if(props.getTag().endsWith("_password")) { + ph.addEnc(props.getTag(), props.getValue()); + } else { + ph.add(props.getTag(), props.getValue()); + } } } @@ -1018,10 +1018,10 @@ public class Agent { } public static List<Props> aafProps(Trans trans, AAFCon<?> aafcon, String locator, String fqi) throws CadiException, APIException, URISyntaxException { - Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator)) + Future<Configuration> acf = aafcon.client(new SingleEndpointLocator(locator)) .read("/configure/"+fqi+"/aaf", configDF); if (acf.get(TIMEOUT)) { - return acf.value.getProps(); + return acf.value.getProps(); } else if (acf.code()==401){ trans.error().log("Bad Password sent to AAF"); } else if (acf.code()==404){ 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 36ee42d8..0971ae0c 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 @@ -45,8 +45,8 @@ public abstract class ArtifactDir implements PlaceArtifact { // This checks for multiple passes of Dir on the same objects. Run clear after done. protected final static Map<String,Object> processed = new HashMap<>(); - private static final Map<String, Symm> symms = new HashMap<>(); - + private static final Map<String, Symm> symms = new HashMap<>(); + /** * Note: Derived Classes should ALWAYS call "super.place(cert,arti)" first, and * then "placeProperties(arti)" just after they implement @@ -94,7 +94,7 @@ public abstract class ArtifactDir implements PlaceArtifact { return true; } - /** + /** * Derived Classes implement this instead, so Dir can process first, and write any Properties last * @param cert * @param arti @@ -104,7 +104,7 @@ public abstract class ArtifactDir implements PlaceArtifact { protected abstract boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException; public static void write(File f, Chmod c, String ... data) throws IOException { - System.out.println("Writing file " + f.getCanonicalPath()); + System.out.println("Writing file " + f.getCanonicalPath()); f.setWritable(true,true); FileOutputStream fos = new FileOutputStream(f); @@ -120,7 +120,7 @@ public abstract class ArtifactDir implements PlaceArtifact { } public static void write(File f, Chmod c, byte[] bytes) throws IOException { - System.out.println("Writing file " + f.getCanonicalPath()); + System.out.println("Writing file " + f.getCanonicalPath()); f.setWritable(true,true); FileOutputStream fos = new FileOutputStream(f); @@ -133,7 +133,7 @@ public abstract class ArtifactDir implements PlaceArtifact { } public static void write(File f, Chmod c, KeyStore ks, char[] pass ) throws IOException, CadiException { - System.out.println("Writing file " + f.getCanonicalPath()); + System.out.println("Writing file " + f.getCanonicalPath()); f.setWritable(true,true); FileOutputStream fos = new FileOutputStream(f); @@ -149,17 +149,17 @@ public abstract class ArtifactDir implements PlaceArtifact { // Get the Symm associated with specific File (there can be several active at once) public synchronized static final Symm getSymm(File f) throws IOException { - Symm symm = symms.get(f.getCanonicalPath()); - if(symm==null) { + Symm symm = symms.get(f.getCanonicalPath()); + if(symm==null) { if (!f.exists()) { write(f,Chmod.to400,Symm.keygen()); // } else { -// System.out.println("Encryptor using " + f.getCanonicalPath()); +// System.out.println("Encryptor using " + f.getCanonicalPath()); } symm = Symm.obtain(f); symms.put(f.getCanonicalPath(),symm); - } - return symm; + } + return symm; } private void validate(Artifact a) throws CadiException { 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 67b3df09..18d74fba 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 @@ -50,7 +50,7 @@ public class PlaceArtifactInKeystore extends ArtifactDir { @Override public boolean _place(Trans trans, CertInfo certInfo, Artifact arti) throws CadiException { - final String ext = (kst==Agent.PKCS12?"p12":kst); + final String ext = (kst==Agent.PKCS12?"p12":kst); File fks = new File(dir,arti.getNs()+'.'+ext); try { KeyStore jks = KeyStore.getInstance(kst); @@ -73,17 +73,17 @@ public class PlaceArtifactInKeystore extends ArtifactDir { if (x509.getSubjectDN().equals(x509.getIssuerDN())) { caSet.add(x509); } else { - // Expect Certs in Trust Chain Order. - if(curr==null) { + // Expect Certs in Trust Chain Order. + if(curr==null) { chainList.add(x509); curr=x509; - } else { - // Only Add Cert next on the list - if(curr.getIssuerDN().equals(x509.getSubjectDN())) { - chainList.add(x509); - curr=x509; - } - } + } else { + // Only Add Cert next on the list + if(curr.getIssuerDN().equals(x509.getSubjectDN())) { + chainList.add(x509); + curr=x509; + } + } } } diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PropHolder.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PropHolder.java index 1b8b76e4..3140df61 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PropHolder.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/configure/PropHolder.java @@ -39,104 +39,104 @@ import certman.v1_0.Artifacts.Artifact; // Doing this because there are lots of lists spread out in this model... // we want these to be unique. public class PropHolder { - private File dir; - private File file; - private File keyfile; - private Symm symm; - private Map<String,String> props; + private File dir; + private File file; + private File keyfile; + private Symm symm; + private Map<String,String> props; - private static boolean dirMessage = true; + private static boolean dirMessage = true; protected final static Map<String,PropHolder> propHolders = new HashMap<>(); public static PropHolder get(Artifact arti, String suffix) throws IOException { - File dir = new File(arti.getDir()); + File dir = new File(arti.getDir()); if (dir.exists()) { - if(dirMessage) { - System.out.println("Writing to " + dir.getCanonicalFile()); - } + if(dirMessage) { + System.out.println("Writing to " + dir.getCanonicalFile()); + } } else if (dir.mkdirs()) { - if(dirMessage) { - System.out.println("Created directory " + dir.getCanonicalFile()); - } + if(dirMessage) { + System.out.println("Created directory " + dir.getCanonicalFile()); + } } else { throw new IOException("Unable to create or write to " + dir.getCanonicalPath()); } dirMessage = false; - File file = new File(dir,arti.getNs()+'.'+suffix); + File file = new File(dir,arti.getNs()+'.'+suffix); - PropHolder ph = propHolders.get(file.getAbsolutePath()); - if(ph == null) { - ph = new PropHolder(dir,file,new File(dir,arti.getNs()+".keyfile")); - propHolders.put(file.getAbsolutePath(), ph); - } - return ph; + PropHolder ph = propHolders.get(file.getAbsolutePath()); + if(ph == null) { + ph = new PropHolder(dir,file,new File(dir,arti.getNs()+".keyfile")); + propHolders.put(file.getAbsolutePath(), ph); + } + return ph; + } + + private PropHolder(File dir, File file, File keyfile) throws IOException { + this.dir = dir; + this.file = file; + this.keyfile = keyfile; + symm = null; + props = new TreeMap<>(); + } + + public String getPath() { + return file.getAbsolutePath(); + } + + public File getDir() { + return dir; } - - private PropHolder(File dir, File file, File keyfile) throws IOException { - this.dir = dir; - this.file = file; - this.keyfile = keyfile; - symm = null; - props = new TreeMap<>(); - } - - public String getPath() { - return file.getAbsolutePath(); - } - - public File getDir() { - return dir; - } - public String getKeyPath() { - return keyfile.getAbsolutePath(); - } + public String getKeyPath() { + return keyfile.getAbsolutePath(); + } - public String add(final String tag, final String value) { - final String rv = value==null?"":value; - props.put(tag, rv); - return rv; - } + public String add(final String tag, final String value) { + final String rv = value==null?"":value; + props.put(tag, rv); + return rv; + } - public String add(final String tag, Access orig, final String def) { - return add(tag, orig.getProperty(tag, def)); - } + public String add(final String tag, Access orig, final String def) { + return add(tag, orig.getProperty(tag, def)); + } - public String addEnc(final String tag, final String value) throws IOException { - String rv; - if(value==null) { - rv = ""; - } else { - if(symm==null) { // Lazy Instantiations... on a few PropFiles have Security - symm = ArtifactDir.getSymm(keyfile); - } - rv = "enc:"+symm.enpass(value); - } - props.put(tag, rv); - return rv; - } + public String addEnc(final String tag, final String value) throws IOException { + String rv; + if(value==null) { + rv = ""; + } else { + if(symm==null) { // Lazy Instantiations... on a few PropFiles have Security + symm = ArtifactDir.getSymm(keyfile); + } + rv = "enc:"+symm.enpass(value); + } + props.put(tag, rv); + return rv; + } - public void addEnc(final String tag, Access orig, final String def) throws IOException { - String pwd = orig.getProperty(tag, def); - if(pwd==null) { - return; - } else if(pwd.startsWith("enc:")) { - pwd = orig.decrypt(pwd, true); - } - addEnc(tag,pwd); - } - - public void write() throws IOException { + public void addEnc(final String tag, Access orig, final String def) throws IOException { + String pwd = orig.getProperty(tag, def); + if(pwd==null) { + return; + } else if(pwd.startsWith("enc:")) { + pwd = orig.decrypt(pwd, true); + } + addEnc(tag,pwd); + } + + public void write() throws IOException { if (props.size()==0) { return; } if (file.exists()) { - System.out.println("Backing up " + file.getCanonicalPath()); + System.out.println("Backing up " + file.getCanonicalPath()); File backup = File.createTempFile(file.getName()+'.', ".backup",dir); file.renameTo(backup); } else { - System.out.println("Creating new " + file.getCanonicalPath()); + System.out.println("Creating new " + file.getCanonicalPath()); } // Append if not first @@ -159,7 +159,7 @@ public class PropHolder { pw.println(); for (Map.Entry<String,String> me : props.entrySet()) { - String key = me.getKey(); + String key = me.getKey(); pw.print(key); pw.print('='); pw.println(me.getValue()); @@ -168,16 +168,16 @@ public class PropHolder { pw.close(); } Chmod.to644.chmod(file); - } - - public static void writeAll() throws IOException { - for(PropHolder ph : propHolders.values()) { - ph.write(); - } - } - - @Override - public String toString() { - return file.getAbsolutePath() + ": " + props; - } + } + + public static void writeAll() throws IOException { + for(PropHolder ph : propHolders.values()) { + ph.write(); + } + } + + @Override + public String toString() { + return file.getAbsolutePath() + ": " + props; + } } 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 14cf0f62..8c47b6cb 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 @@ -78,11 +78,11 @@ public class TokenClientFactory extends Persist<Token,TimedToken> { } for(String tag : new String[] {Config.AAF_ALT_OAUTH2_TOKEN_URL, Config.AAF_ALT_OAUTH2_INTROSPECT_URL}) { - String value = access.getProperty(tag, null); - if(value!=null) { - alts.add(tag); - alts.add(value); - } + String value = access.getProperty(tag, null); + if(value!=null) { + alts.add(tag); + alts.add(value); + } } symm = Symm.encrypt.obtain(); @@ -121,7 +121,7 @@ public class TokenClientFactory extends Persist<Token,TimedToken> { } char okind; if (alts.contains(tagOrURL)) { - okind = Kind.OAUTH; + okind = Kind.OAUTH; } else { okind = Kind.AAF_OAUTH; } 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 c3dc4f6a..18eb7357 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 @@ -71,7 +71,7 @@ public class Registrar<ENV extends BasicEnv> { erroringTimer = null; } } else { - env.error().log(rv.toString()); + env.error().log(rv.toString()); // Account for different Registrations not being to same place if (erroringTimer==null) { erroringTimer = new Timer(REGISTRAR + " error re-check ",true); diff --git a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RegistrationCreator.java b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RegistrationCreator.java index fc3c18b0..80fc1a4f 100644 --- a/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RegistrationCreator.java +++ b/cadi/aaf/src/main/java/org/onap/aaf/cadi/register/RegistrationCreator.java @@ -36,227 +36,227 @@ import locate.v1_0.MgmtEndpoint.SpecialPorts; import locate.v1_0.MgmtEndpoints; public class RegistrationCreator { - private Access access; + private Access access; public RegistrationCreator(Access access) { - this.access = access; + this.access = access; } public MgmtEndpoints create(final int port) throws CadiException { - MgmtEndpoints me = new MgmtEndpoints(); - List<MgmtEndpoint> lme = me.getMgmtEndpoint(); - MgmtEndpoint defData = null; - MgmtEndpoint locate = null; + MgmtEndpoints me = new MgmtEndpoints(); + List<MgmtEndpoint> lme = me.getMgmtEndpoint(); + MgmtEndpoint defData = null; + MgmtEndpoint locate = null; - try { - String dot_le; - String version=null; - String defProtocol="https"; - - RegistrationPropHolder ph = new RegistrationPropHolder(access, port); - - String firstPrivateHostname = null; - // Now, loop through by Container - for(String le : Split.splitTrim(',', ph.lcontainer)) { - if(le.isEmpty()) { - dot_le = le; - } else { - dot_le = "."+le; - } + try { + String dot_le; + String version=null; + String defProtocol="https"; + + RegistrationPropHolder ph = new RegistrationPropHolder(access, port); + + String firstPrivateHostname = null; + // Now, loop through by Container + for(String le : Split.splitTrim(',', ph.lcontainer)) { + if(le.isEmpty()) { + dot_le = le; + } else { + dot_le = "."+le; + } - for(String entry : Split.splitTrim(',', ph.lentries)) { - if(defData==null) { - defData = locate = new MgmtEndpoint(); + for(String entry : Split.splitTrim(',', ph.lentries)) { + if(defData==null) { + defData = locate = new MgmtEndpoint(); - version = access.getProperty(Config.AAF_LOCATOR_VERSION, Defaults.AAF_VERSION); - locate.setProtocol(defProtocol = access.getProperty(Config.AAF_LOCATOR_PROTOCOL,defProtocol)); - List<String> ls = locate.getSubprotocol(); - for(String sp : Split.splitTrim(',', access.getProperty(Config.AAF_LOCATOR_SUBPROTOCOL,""))) { - ls.add(sp); - } - locate.setLatitude(ph.latitude); - locate.setLongitude(ph.longitude); + version = access.getProperty(Config.AAF_LOCATOR_VERSION, Defaults.AAF_VERSION); + locate.setProtocol(defProtocol = access.getProperty(Config.AAF_LOCATOR_PROTOCOL,defProtocol)); + List<String> ls = locate.getSubprotocol(); + for(String sp : Split.splitTrim(',', access.getProperty(Config.AAF_LOCATOR_SUBPROTOCOL,""))) { + ls.add(sp); + } + locate.setLatitude(ph.latitude); + locate.setLongitude(ph.longitude); - } else { - locate = copy(defData); - } - - locate.setName(ph.getEntryName(entry,dot_le)); - /* Cover the situation where there is a Container, and multiple locator Entries, - * the first of which is the only real private FQDN - * example: oauth - * aaf_locator_entries=oauth,token,introspect - * - * Entries for token and introspect, but they point to oauth service. - */ - String locateHostname; - if(le.isEmpty()) { - locateHostname=ph.getEntryFQDN(entry, dot_le); - } else if(firstPrivateHostname==null) { - firstPrivateHostname=locateHostname=ph.getEntryFQDN(entry, dot_le); - } else { - locateHostname=firstPrivateHostname; - } - - locate.setHostname(locateHostname); - locate.setPort(ph.getEntryPort(dot_le)); - - String specificVersion = access.getProperty(Config.AAF_LOCATOR_VERSION + dot_le,null); - if(specificVersion == null && locate == defData) { - specificVersion = version; - } - if(specificVersion!=null) { - String split[] = Split.splitTrim('.', specificVersion); - String deply[]= Split.splitTrim('.', access.getProperty(Config.AAF_DEPLOYED_VERSION, "")); - locate.setMajor(best(split,deply,0)); - locate.setMinor(best(split,deply,1)); - locate.setPatch(best(split,deply,2)); - locate.setPkg(best(split,deply,3)); - } + } else { + locate = copy(defData); + } + + locate.setName(ph.getEntryName(entry,dot_le)); + /* Cover the situation where there is a Container, and multiple locator Entries, + * the first of which is the only real private FQDN + * example: oauth + * aaf_locator_entries=oauth,token,introspect + * + * Entries for token and introspect, but they point to oauth service. + */ + String locateHostname; + if(le.isEmpty()) { + locateHostname=ph.getEntryFQDN(entry, dot_le); + } else if(firstPrivateHostname==null) { + firstPrivateHostname=locateHostname=ph.getEntryFQDN(entry, dot_le); + } else { + locateHostname=firstPrivateHostname; + } + + locate.setHostname(locateHostname); + locate.setPort(ph.getEntryPort(dot_le)); + + String specificVersion = access.getProperty(Config.AAF_LOCATOR_VERSION + dot_le,null); + if(specificVersion == null && locate == defData) { + specificVersion = version; + } + if(specificVersion!=null) { + String split[] = Split.splitTrim('.', specificVersion); + String deply[]= Split.splitTrim('.', access.getProperty(Config.AAF_DEPLOYED_VERSION, "")); + locate.setMajor(best(split,deply,0)); + locate.setMinor(best(split,deply,1)); + locate.setPatch(best(split,deply,2)); + locate.setPkg(best(split,deply,3)); + } - String protocol = access.getProperty(Config.AAF_LOCATOR_PROTOCOL + dot_le, defProtocol); - if (protocol!=null) { - locate.setProtocol(protocol); - List<String> ls = locate.getSubprotocol(); - // ls cannot be null, per generated getSubprotocol code - if(ls.isEmpty()) { - String subprotocols = access.getProperty(Config.AAF_LOCATOR_SUBPROTOCOL + dot_le, null); - if(subprotocols==null) { - subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); - } - if(subprotocols!=null) { - for (String s : Split.split(',', subprotocols)) { - ls.add(s); - } - } else { - access.printf(Level.ERROR, "%s is required for Locator Registration of %s", - Config.AAF_LOCATOR_SUBPROTOCOL,Config.AAF_LOCATOR_PROTOCOL); - } - } - lme.add(locate); - } else { - access.printf(Level.ERROR, "%s is required for Locator Registration",Config.AAF_LOCATOR_PROTOCOL); - } - } - } - } catch (NumberFormatException | UnknownHostException e) { - throw new CadiException("Error extracting Data from Properties for Registrar",e); - } - - if(access.willLog(Level.INFO)) { - access.log(Level.INFO, print(new StringBuilder(),me.getMgmtEndpoint())); - } - return me; + String protocol = access.getProperty(Config.AAF_LOCATOR_PROTOCOL + dot_le, defProtocol); + if (protocol!=null) { + locate.setProtocol(protocol); + List<String> ls = locate.getSubprotocol(); + // ls cannot be null, per generated getSubprotocol code + if(ls.isEmpty()) { + String subprotocols = access.getProperty(Config.AAF_LOCATOR_SUBPROTOCOL + dot_le, null); + if(subprotocols==null) { + subprotocols = access.getProperty(Config.CADI_PROTOCOLS, null); + } + if(subprotocols!=null) { + for (String s : Split.split(',', subprotocols)) { + ls.add(s); + } + } else { + access.printf(Level.ERROR, "%s is required for Locator Registration of %s", + Config.AAF_LOCATOR_SUBPROTOCOL,Config.AAF_LOCATOR_PROTOCOL); + } + } + lme.add(locate); + } else { + access.printf(Level.ERROR, "%s is required for Locator Registration",Config.AAF_LOCATOR_PROTOCOL); + } + } + } + } catch (NumberFormatException | UnknownHostException e) { + throw new CadiException("Error extracting Data from Properties for Registrar",e); + } + + if(access.willLog(Level.INFO)) { + access.log(Level.INFO, print(new StringBuilder(),me.getMgmtEndpoint())); + } + return me; } - + /* * Find the best version between Actual Interface and Deployed version */ private int best(String[] split, String[] deploy, int i) { - StringBuilder sb = new StringBuilder(); - char c; - String s; - if(split.length>i) { - s=split[i]; - for(int j=0;j<s.length();++j) { - if(Character.isDigit(c=s.charAt(j))) { - sb.append(c); - } else { - break; - } - } - } - - if(sb.length()==0 && deploy.length>i) { - s=deploy[i]; - for(int j=0;j<s.length();++j) { - if(Character.isDigit(c=s.charAt(j))) { - sb.append(c); - } else { - break; - } - } - } - - return sb.length()==0?0:Integer.parseInt(sb.toString()); + StringBuilder sb = new StringBuilder(); + char c; + String s; + if(split.length>i) { + s=split[i]; + for(int j=0;j<s.length();++j) { + if(Character.isDigit(c=s.charAt(j))) { + sb.append(c); + } else { + break; + } + } + } + + if(sb.length()==0 && deploy.length>i) { + s=deploy[i]; + for(int j=0;j<s.length();++j) { + if(Character.isDigit(c=s.charAt(j))) { + sb.append(c); + } else { + break; + } + } + } + + return sb.length()==0?0:Integer.parseInt(sb.toString()); } - private StringBuilder print(StringBuilder sb, List<MgmtEndpoint> lme) { - int cnt = 0; - for(MgmtEndpoint m : lme) { - print(sb,cnt++,m); - } - return sb; - } + private StringBuilder print(StringBuilder sb, List<MgmtEndpoint> lme) { + int cnt = 0; + for(MgmtEndpoint m : lme) { + print(sb,cnt++,m); + } + return sb; + } - private void print(StringBuilder out, int cnt, MgmtEndpoint mep) { - out.append("\nManagement Endpoint - "); - out.append(cnt); - out.append("\n\tName: "); - out.append(mep.getName()); - out.append("\n\tHostname: "); - out.append(mep.getHostname()); - out.append("\n\tLatitude: "); - out.append(mep.getLatitude()); - out.append("\n\tLongitude: "); - out.append(mep.getLongitude()); - out.append("\n\tVersion: "); - out.append(mep.getMajor()); - out.append('.'); - out.append(mep.getMinor()); - out.append('.'); - out.append(mep.getPatch()); - out.append('.'); - out.append(mep.getPkg()); - out.append("\n\tPort: "); - out.append(mep.getPort()); - out.append("\n\tProtocol: "); - out.append(mep.getProtocol()); - out.append("\n\tSpecial Ports:"); - for( SpecialPorts sp : mep.getSpecialPorts()) { - out.append("\n\t\tName: "); - out.append(sp.getName()); - out.append("\n\t\tPort: "); - out.append(sp.getPort()); - out.append("\n\t\tProtocol: "); - out.append(sp.getProtocol()); - out.append("\n\t\t Versions: "); - boolean first = true; - for(String s : sp.getProtocolVersions()) { - if(first) { - first = false; - } else { - out.append(','); - } - out.append(s); - } - } - boolean first = true; - out.append("\n\tSubProtocol: "); - for(String s : mep.getSubprotocol()) { - if(first) { - first = false; - } else { - out.append(','); - } - out.append(s); - } - } + private void print(StringBuilder out, int cnt, MgmtEndpoint mep) { + out.append("\nManagement Endpoint - "); + out.append(cnt); + out.append("\n\tName: "); + out.append(mep.getName()); + out.append("\n\tHostname: "); + out.append(mep.getHostname()); + out.append("\n\tLatitude: "); + out.append(mep.getLatitude()); + out.append("\n\tLongitude: "); + out.append(mep.getLongitude()); + out.append("\n\tVersion: "); + out.append(mep.getMajor()); + out.append('.'); + out.append(mep.getMinor()); + out.append('.'); + out.append(mep.getPatch()); + out.append('.'); + out.append(mep.getPkg()); + out.append("\n\tPort: "); + out.append(mep.getPort()); + out.append("\n\tProtocol: "); + out.append(mep.getProtocol()); + out.append("\n\tSpecial Ports:"); + for( SpecialPorts sp : mep.getSpecialPorts()) { + out.append("\n\t\tName: "); + out.append(sp.getName()); + out.append("\n\t\tPort: "); + out.append(sp.getPort()); + out.append("\n\t\tProtocol: "); + out.append(sp.getProtocol()); + out.append("\n\t\t Versions: "); + boolean first = true; + for(String s : sp.getProtocolVersions()) { + if(first) { + first = false; + } else { + out.append(','); + } + out.append(s); + } + } + boolean first = true; + out.append("\n\tSubProtocol: "); + for(String s : mep.getSubprotocol()) { + if(first) { + first = false; + } else { + out.append(','); + } + out.append(s); + } + } private MgmtEndpoint copy(MgmtEndpoint mep) { - MgmtEndpoint out = new MgmtEndpoint(); - out.setName(mep.getName()); - out.setHostname(mep.getHostname()); - out.setLatitude(mep.getLatitude()); - out.setLongitude(mep.getLongitude()); - out.setMajor(mep.getMajor()); - out.setMinor(mep.getMinor()); - out.setPatch(mep.getPatch()); - out.setPkg(mep.getPkg()); - out.setPort(mep.getPort()); - out.setProtocol(mep.getProtocol()); - out.getSpecialPorts().addAll(mep.getSpecialPorts()); - out.getSubprotocol().addAll(mep.getSubprotocol()); - return out; - } + MgmtEndpoint out = new MgmtEndpoint(); + out.setName(mep.getName()); + out.setHostname(mep.getHostname()); + out.setLatitude(mep.getLatitude()); + out.setLongitude(mep.getLongitude()); + out.setMajor(mep.getMajor()); + out.setMinor(mep.getMinor()); + out.setPatch(mep.getPatch()); + out.setPkg(mep.getPkg()); + out.setPort(mep.getPort()); + out.setProtocol(mep.getProtocol()); + out.getSpecialPorts().addAll(mep.getSpecialPorts()); + out.getSubprotocol().addAll(mep.getSubprotocol()); + return out; + } } 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 3672c624..0e4945d0 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 @@ -68,8 +68,8 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { } else { // Note: want Property Locator or Single, not AAFLocator, because we want the core service, not what it can find try { - RegistrationPropHolder rph = new RegistrationPropHolder(access, 0); - aaf_locate = rph.replacements(getClass().getSimpleName(),aaf_locate, null,null); + RegistrationPropHolder rph = new RegistrationPropHolder(access, 0); + aaf_locate = rph.replacements(getClass().getSimpleName(),aaf_locate, null,null); if (aaf_locate.indexOf(',')>=0) { locator = new PropertyLocator(aaf_locate); } else { @@ -86,7 +86,7 @@ public class RemoteRegistrant<ENV extends BasicEnv> implements Registrant<ENV> { - @Override + @Override public Result<Void> update(ENV env) { try { Rcli<?> client = aafcon.client(locator); 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 c0ac43e9..a472ed5b 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 @@ -146,7 +146,7 @@ public class AAFSSO { // Config.setDefaultRealm(access); if (!dot_aaf_kf.exists()) { - // This will create, as required, or reuse + // This will create, as required, or reuse ArtifactDir.getSymm(dot_aaf_kf); } @@ -192,18 +192,18 @@ public class AAFSSO { String aaf_container_ns = ""; if (appID!=null) { - if( access.getProperty(Config.AAF_APPPASS)==null) { - appID = user = cons.readLine("Deployer ID [%s]: ", user); - access.setProperty(Config.AAF_APPID,appID); - char[] password = cons.readPassword("Password for %s: ", user); - if(password.length>0) { - String app_pass = access.encrypt(new String(password)); - access.setProperty(Config.AAF_APPPASS,app_pass); - diskprops.setProperty(Config.AAF_APPPASS,app_pass); - } - aaf_container_ns = cons.readLine("Container Namespace (blank if none)? [\"\"]: ", aaf_container_ns); - } - diskprops.setProperty(Config.AAF_APPID,appID); + if( access.getProperty(Config.AAF_APPPASS)==null) { + appID = user = cons.readLine("Deployer ID [%s]: ", user); + access.setProperty(Config.AAF_APPID,appID); + char[] password = cons.readPassword("Password for %s: ", user); + if(password.length>0) { + String app_pass = access.encrypt(new String(password)); + access.setProperty(Config.AAF_APPPASS,app_pass); + diskprops.setProperty(Config.AAF_APPPASS,app_pass); + } + aaf_container_ns = cons.readLine("Container Namespace (blank if none)? [\"\"]: ", aaf_container_ns); + } + diskprops.setProperty(Config.AAF_APPID,appID); } String keystore=access.getProperty(Config.CADI_KEYSTORE); @@ -380,39 +380,39 @@ public class AAFSSO { access.setProperty(Config.AAF_LOCATE_URL, locateUrl); addProp(Config.AAF_LOCATE_URL, locateUrl); try { - if(access.getProperty(Config.AAF_URL)==null) { - access.setProperty(Config.AAF_URL, Defaults.AAF_ROOT+".service:"+Defaults.AAF_VERSION); - } - AAFCon<?> aafCon = AAFCon.newInstance(access); - Future<Configuration> acf; - RosettaDF<Configuration> configDF = new RosettaEnv().newDataFactory(Configuration.class); - acf = aafCon.client(new SingleEndpointLocator(locateUrl)) - .read("/configure/"+user+"/aaf", configDF); - if (acf.get(aafCon.connTimeout)) { - for(Props p : acf.value.getProps()) { - addProp(p.getTag(),p.getValue()); - if(access.getProperty(p.getTag())==null) { - access.setProperty(p.getTag(), p.getValue()); - } - } - } else { - access.log(Level.INFO,acf.body()); - } - } catch (LocatorException | APIException | URISyntaxException e) { - access.log(e); - } + if(access.getProperty(Config.AAF_URL)==null) { + access.setProperty(Config.AAF_URL, Defaults.AAF_ROOT+".service:"+Defaults.AAF_VERSION); + } + AAFCon<?> aafCon = AAFCon.newInstance(access); + Future<Configuration> acf; + RosettaDF<Configuration> configDF = new RosettaEnv().newDataFactory(Configuration.class); + acf = aafCon.client(new SingleEndpointLocator(locateUrl)) + .read("/configure/"+user+"/aaf", configDF); + if (acf.get(aafCon.connTimeout)) { + for(Props p : acf.value.getProps()) { + addProp(p.getTag(),p.getValue()); + if(access.getProperty(p.getTag())==null) { + access.setProperty(p.getTag(), p.getValue()); + } + } + } else { + access.log(Level.INFO,acf.body()); + } + } catch (LocatorException | APIException | URISyntaxException e) { + access.log(e); + } } final String apiVersion = access.getProperty(Config.AAF_API_VERSION, Config.AAF_DEFAULT_API_VERSION); final String aaf_root_ns = access.getProperty(Config.AAF_ROOT_NS); String locateRoot; if(aaf_root_ns==null) { - locateRoot=Defaults.AAF_ROOT; + locateRoot=Defaults.AAF_ROOT; } else { - locateRoot = Defaults.AAF_LOCATE_CONST + "/%CNS." + aaf_root_ns; + locateRoot = Defaults.AAF_LOCATE_CONST + "/%CNS." + aaf_root_ns; } if(access.getProperty(Config.AAF_URL)==null) { - access.setProperty(Config.AAF_URL, locateRoot+".service:"+apiVersion); + access.setProperty(Config.AAF_URL, locateRoot+".service:"+apiVersion); } writeFiles(); diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFAuthn.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFAuthn.java index 962397cc..7dccc8c1 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFAuthn.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFAuthn.java @@ -40,165 +40,165 @@ import org.onap.aaf.cadi.principal.BasicPrincipal; public class JU_AAFAuthn { - @Mock - AAFCon con; - - @Mock - AbsUserCache<AAFPermission> cache; - - @Mock - PropAccess propaccess; - - @Before - public void setUp() { - initMocks(this); - } + @Mock + AAFCon con; + + @Mock + AbsUserCache<AAFPermission> cache; + + @Mock + PropAccess propaccess; + + @Before + public void setUp() { + initMocks(this); + } - @Test - public void testGetRealm() { - AAFAuthn authnObj = new AAFAuthn(con); - String realm = authnObj.getRealm(); - assertNull(realm); - } - - @Test - public void testValidateFailure() { - AAFAuthnImplWithGetUserNull authnObj = new AAFAuthnImplWithGetUserNull(con, cache); - String realm=""; - try { - Mockito.doReturn("test").when(propaccess).decrypt("test", false); - realm = authnObj.validate("test", "test"); - assertNull(realm); - } catch (Exception e) { - // TODO Auto-generated catch block - assertNull( e.getLocalizedMessage()); - } - } - - @Test - public void testValidate() { - AAFAuthnImpl authnObj = new AAFAuthnImpl(con); - String realm=""; - try { - Mockito.doReturn("test").when(propaccess).decrypt("test", false); - Rcli rcliObj = Mockito.mock(Rcli.class); - Mockito.doReturn(rcliObj).when(con).client(); - Mockito.doReturn(rcliObj).when(rcliObj).forUser(null); - Future<String> futureObj = Mockito.mock(Future.class); - Mockito.doReturn(futureObj).when(rcliObj).read( "/authn/basicAuth","text/plain"); - realm = authnObj.validate("test", "test","test"); - assertTrue(realm.contains("user/pass combo invalid")); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testValidateRevalidate() { - AAFAuthnImpl authnObj = new AAFAuthnImpl(con); - String realm=""; - try { - Mockito.doReturn("test").when(propaccess).decrypt("test", false); - Rcli rcliObj = Mockito.mock(Rcli.class); - Mockito.doReturn(rcliObj).when(con).client(); - Mockito.doReturn(rcliObj).when(rcliObj).forUser(null); - Future<String> futureObj = Mockito.mock(Future.class); - Mockito.doReturn(futureObj).when(rcliObj).read( "/authn/basicAuth","text/plain"); - Mockito.doReturn(true).when(futureObj).get( 0); - realm = authnObj.validate("test", "test","test"); - assertNull(realm); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testValidateValidUser() { - AAFAuthnImplWithGetUser authnObj = new AAFAuthnImplWithGetUser(con); - String realm=""; - try { - Mockito.doReturn("test").when(propaccess).decrypt("test", false); - realm = authnObj.validate("test", "test","test"); - assertTrue(realm.contains("User already denied")); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testValidateValidUserNull() { - AAFAuthnImplWithGetUserNull authnObj = new AAFAuthnImplWithGetUserNull(con); - String realm=""; - try { - Mockito.doReturn("test").when(propaccess).decrypt("test", false); - realm = authnObj.validate("test", "test","test"); - assertNull(realm); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - class AAFAuthnImpl extends AAFAuthn{ - AAFAuthnImpl(AAFCon con) { - super(con); - this.access = propaccess; - // TODO Auto-generated constructor stub - } - - AAFAuthnImpl(AAFCon con, AbsUserCache cache) { - super(con, cache); - this.access = propaccess; - // TODO Auto-generated constructor stub - } - - - } - - class AAFAuthnImplWithGetUser extends AAFAuthn{ - AAFAuthnImplWithGetUser(AAFCon con) { - super(con); - this.access = propaccess; - // TODO Auto-generated constructor stub - } - - AAFAuthnImplWithGetUser(AAFCon con, AbsUserCache cache) { - super(con, cache); - this.access = propaccess; - // TODO Auto-generated constructor stub - } - - @Override - protected User getUser(String user, byte[] cred) { - return new User<>("test",new byte[] {}); - } - } - - class AAFAuthnImplWithGetUserNull extends AAFAuthn{ - AAFAuthnImplWithGetUserNull(AAFCon con) { - super(con); - this.access = propaccess; - // TODO Auto-generated constructor stub - } - - AAFAuthnImplWithGetUserNull(AAFCon con, AbsUserCache cache) { - super(con, cache); - this.access = propaccess; - // TODO Auto-generated constructor stub - } - - @Override - protected User getUser(String user, byte[] cred) { - User user1 = null; - try { - user1 = new User(new BasicPrincipal("test","test")); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - return user1; - } - } + @Test + public void testGetRealm() { + AAFAuthn authnObj = new AAFAuthn(con); + String realm = authnObj.getRealm(); + assertNull(realm); + } + + @Test + public void testValidateFailure() { + AAFAuthnImplWithGetUserNull authnObj = new AAFAuthnImplWithGetUserNull(con, cache); + String realm=""; + try { + Mockito.doReturn("test").when(propaccess).decrypt("test", false); + realm = authnObj.validate("test", "test"); + assertNull(realm); + } catch (Exception e) { + // TODO Auto-generated catch block + assertNull( e.getLocalizedMessage()); + } + } + + @Test + public void testValidate() { + AAFAuthnImpl authnObj = new AAFAuthnImpl(con); + String realm=""; + try { + Mockito.doReturn("test").when(propaccess).decrypt("test", false); + Rcli rcliObj = Mockito.mock(Rcli.class); + Mockito.doReturn(rcliObj).when(con).client(); + Mockito.doReturn(rcliObj).when(rcliObj).forUser(null); + Future<String> futureObj = Mockito.mock(Future.class); + Mockito.doReturn(futureObj).when(rcliObj).read( "/authn/basicAuth","text/plain"); + realm = authnObj.validate("test", "test","test"); + assertTrue(realm.contains("user/pass combo invalid")); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testValidateRevalidate() { + AAFAuthnImpl authnObj = new AAFAuthnImpl(con); + String realm=""; + try { + Mockito.doReturn("test").when(propaccess).decrypt("test", false); + Rcli rcliObj = Mockito.mock(Rcli.class); + Mockito.doReturn(rcliObj).when(con).client(); + Mockito.doReturn(rcliObj).when(rcliObj).forUser(null); + Future<String> futureObj = Mockito.mock(Future.class); + Mockito.doReturn(futureObj).when(rcliObj).read( "/authn/basicAuth","text/plain"); + Mockito.doReturn(true).when(futureObj).get( 0); + realm = authnObj.validate("test", "test","test"); + assertNull(realm); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testValidateValidUser() { + AAFAuthnImplWithGetUser authnObj = new AAFAuthnImplWithGetUser(con); + String realm=""; + try { + Mockito.doReturn("test").when(propaccess).decrypt("test", false); + realm = authnObj.validate("test", "test","test"); + assertTrue(realm.contains("User already denied")); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testValidateValidUserNull() { + AAFAuthnImplWithGetUserNull authnObj = new AAFAuthnImplWithGetUserNull(con); + String realm=""; + try { + Mockito.doReturn("test").when(propaccess).decrypt("test", false); + realm = authnObj.validate("test", "test","test"); + assertNull(realm); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + class AAFAuthnImpl extends AAFAuthn{ + AAFAuthnImpl(AAFCon con) { + super(con); + this.access = propaccess; + // TODO Auto-generated constructor stub + } + + AAFAuthnImpl(AAFCon con, AbsUserCache cache) { + super(con, cache); + this.access = propaccess; + // TODO Auto-generated constructor stub + } + + + } + + class AAFAuthnImplWithGetUser extends AAFAuthn{ + AAFAuthnImplWithGetUser(AAFCon con) { + super(con); + this.access = propaccess; + // TODO Auto-generated constructor stub + } + + AAFAuthnImplWithGetUser(AAFCon con, AbsUserCache cache) { + super(con, cache); + this.access = propaccess; + // TODO Auto-generated constructor stub + } + + @Override + protected User getUser(String user, byte[] cred) { + return new User<>("test",new byte[] {}); + } + } + + class AAFAuthnImplWithGetUserNull extends AAFAuthn{ + AAFAuthnImplWithGetUserNull(AAFCon con) { + super(con); + this.access = propaccess; + // TODO Auto-generated constructor stub + } + + AAFAuthnImplWithGetUserNull(AAFCon con, AbsUserCache cache) { + super(con, cache); + this.access = propaccess; + // TODO Auto-generated constructor stub + } + + @Override + protected User getUser(String user, byte[] cred) { + User user1 = null; + try { + user1 = new User(new BasicPrincipal("test","test")); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return user1; + } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFSingleLocator.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFSingleLocator.java index 488c2857..89066c99 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFSingleLocator.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/aaf/v2_0/JU_AAFSingleLocator.java @@ -42,97 +42,97 @@ import org.onap.aaf.cadi.aaf.AAFPermission; public class JU_AAFSingleLocator { - @Mock - AAFCon con; - - @Mock - AbsUserCache<AAFPermission> cache; - - @Mock - PropAccess propaccess; - + @Mock + AAFCon con; + + @Mock + AbsUserCache<AAFPermission> cache; + + @Mock + PropAccess propaccess; + - AAFSingleLocator authnObj; - - @Before - public void setUp() { - initMocks(this); - try { - authnObj = new AAFSingleLocator("http://www.google.com"); - } catch (URISyntaxException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + AAFSingleLocator authnObj; + + @Before + public void setUp() { + initMocks(this); + try { + authnObj = new AAFSingleLocator("http://www.google.com"); + } catch (URISyntaxException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - @Test - public void testGetRealm() { - try { - URI retVal = authnObj.get(Mockito.mock( Locator.Item.class)); - assertEquals("www.google.com",retVal.getHost()); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testHasItem() { - boolean retVal = authnObj.hasItems(); - assertTrue(retVal); - } - - @Test - public void testInvalidate() { - try { - authnObj.invalidate(Mockito.mock( Locator.Item.class)); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testBest() { - try { - Locator.Item retVal = authnObj.best(); - assertTrue(retVal.toString().contains("org.onap.aaf.cadi.aaf.v2_0.AAFSingleLocator$SingleItem")); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testFirst() { - try { - Locator.Item retVal = authnObj.first(); - assertTrue(retVal.toString().contains("org.onap.aaf.cadi.aaf.v2_0.AAFSingleLocator$SingleItem")); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testNext() { - try { - Locator.Item retVal = authnObj.next(Mockito.mock( Locator.Item.class)); - assertNull(retVal); - } catch (LocatorException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testRefres() { - boolean retVal = authnObj.refresh(); - assertFalse(retVal); - } - - @Test - public void testdestroy() { - authnObj.destroy(); - } - - + @Test + public void testGetRealm() { + try { + URI retVal = authnObj.get(Mockito.mock( Locator.Item.class)); + assertEquals("www.google.com",retVal.getHost()); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testHasItem() { + boolean retVal = authnObj.hasItems(); + assertTrue(retVal); + } + + @Test + public void testInvalidate() { + try { + authnObj.invalidate(Mockito.mock( Locator.Item.class)); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testBest() { + try { + Locator.Item retVal = authnObj.best(); + assertTrue(retVal.toString().contains("org.onap.aaf.cadi.aaf.v2_0.AAFSingleLocator$SingleItem")); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testFirst() { + try { + Locator.Item retVal = authnObj.first(); + assertTrue(retVal.toString().contains("org.onap.aaf.cadi.aaf.v2_0.AAFSingleLocator$SingleItem")); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testNext() { + try { + Locator.Item retVal = authnObj.next(Mockito.mock( Locator.Item.class)); + assertNull(retVal); + } catch (LocatorException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testRefres() { + boolean retVal = authnObj.refresh(); + assertFalse(retVal); + } + + @Test + public void testdestroy() { + authnObj.destroy(); + } + + } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/register/test/JU_RegistrationCreator.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/register/test/JU_RegistrationCreator.java index 216b8660..0394be97 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/register/test/JU_RegistrationCreator.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/register/test/JU_RegistrationCreator.java @@ -38,143 +38,143 @@ import locate.v1_0.MgmtEndpoint; public class JU_RegistrationCreator { - private static final String DOT_OOM = ".oom"; + private static final String DOT_OOM = ".oom"; - @Test - public void test() { - PropAccess pa = new PropAccess(); - pa.setProperty(Config.CADI_LATITUDE, "32.7"); - pa.setProperty(Config.CADI_LONGITUDE, "-72.0"); - pa.setProperty(Config.AAF_LOCATOR_NAME, ""); - - try { - String hostname = Inet4Address.getLocalHost().getHostName(); - String entry = ""; - RegistrationCreator rc = new RegistrationCreator(pa); - int port = 999; - for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { - assertEquals(hostname,me.getHostname()); - assertEquals(port,me.getPort()); - assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); - assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); - assertEquals(2,me.getMajor()); - assertEquals(1,me.getMinor()); - assertEquals(0,me.getPatch()); - assertEquals(0,me.getPkg()); - assertEquals(entry,me.getName()); - assertEquals("https",me.getProtocol()); - assertEquals(0,me.getSpecialPorts().size()); - } + @Test + public void test() { + PropAccess pa = new PropAccess(); + pa.setProperty(Config.CADI_LATITUDE, "32.7"); + pa.setProperty(Config.CADI_LONGITUDE, "-72.0"); + pa.setProperty(Config.AAF_LOCATOR_NAME, ""); + + try { + String hostname = Inet4Address.getLocalHost().getHostName(); + String entry = ""; + RegistrationCreator rc = new RegistrationCreator(pa); + int port = 999; + for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { + assertEquals(hostname,me.getHostname()); + assertEquals(port,me.getPort()); + assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); + assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); + assertEquals(2,me.getMajor()); + assertEquals(1,me.getMinor()); + assertEquals(0,me.getPatch()); + assertEquals(0,me.getPkg()); + assertEquals(entry,me.getName()); + assertEquals("https",me.getProtocol()); + assertEquals(0,me.getSpecialPorts().size()); + } - String protocol = "http"; - pa.setProperty(Config.AAF_LOCATOR_PROTOCOL, protocol); - rc = new RegistrationCreator(pa); - for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { - assertEquals(hostname,me.getHostname()); - assertEquals(port,me.getPort()); - assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); - assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); - assertEquals(2,me.getMajor()); - assertEquals(1,me.getMinor()); - assertEquals(0,me.getPatch()); - assertEquals(0,me.getPkg()); - assertEquals("",me.getName()); - assertEquals(protocol,me.getProtocol()); - assertEquals(0,me.getSpecialPorts().size()); - } - - pa.setProperty(Config.AAF_LOCATOR_ENTRIES, "service"); - rc = new RegistrationCreator(pa); - for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { - switch(me.getName()) { - case "": - assertEquals(hostname,me.getHostname()); - assertEquals(port,me.getPort()); - break; - case "service": - assertEquals(hostname,me.getHostname()); - assertEquals(port,me.getPort()); - break; - default: - fail("unknown Locator Entry"); - } - assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); - assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); - assertEquals(2,me.getMajor()); - assertEquals(1,me.getMinor()); - assertEquals(0,me.getPatch()); - assertEquals(0,me.getPkg()); - assertEquals(protocol,me.getProtocol()); - assertEquals(0,me.getSpecialPorts().size()); - } + String protocol = "http"; + pa.setProperty(Config.AAF_LOCATOR_PROTOCOL, protocol); + rc = new RegistrationCreator(pa); + for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { + assertEquals(hostname,me.getHostname()); + assertEquals(port,me.getPort()); + assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); + assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); + assertEquals(2,me.getMajor()); + assertEquals(1,me.getMinor()); + assertEquals(0,me.getPatch()); + assertEquals(0,me.getPkg()); + assertEquals("",me.getName()); + assertEquals(protocol,me.getProtocol()); + assertEquals(0,me.getSpecialPorts().size()); + } + + pa.setProperty(Config.AAF_LOCATOR_ENTRIES, "service"); + rc = new RegistrationCreator(pa); + for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { + switch(me.getName()) { + case "": + assertEquals(hostname,me.getHostname()); + assertEquals(port,me.getPort()); + break; + case "service": + assertEquals(hostname,me.getHostname()); + assertEquals(port,me.getPort()); + break; + default: + fail("unknown Locator Entry"); + } + assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); + assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); + assertEquals(2,me.getMajor()); + assertEquals(1,me.getMinor()); + assertEquals(0,me.getPatch()); + assertEquals(0,me.getPkg()); + assertEquals(protocol,me.getProtocol()); + assertEquals(0,me.getSpecialPorts().size()); + } - entry = "service"; - pa.setProperty(Config.AAF_LOCATOR_ENTRIES, entry); - rc = new RegistrationCreator(pa); - for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { - switch(me.getName()) { - case "": - assertEquals(hostname,me.getHostname()); - assertEquals(port,me.getPort()); - break; - case "service": - assertEquals(hostname,me.getHostname()); - assertEquals(port,me.getPort()); - break; - default: - fail("unknown Locator Entry"); - } - assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); - assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); - assertEquals(2,me.getMajor()); - assertEquals(1,me.getMinor()); - assertEquals(0,me.getPatch()); - assertEquals(0,me.getPkg()); - assertEquals(protocol,me.getProtocol()); - assertEquals(0,me.getSpecialPorts().size()); - } + entry = "service"; + pa.setProperty(Config.AAF_LOCATOR_ENTRIES, entry); + rc = new RegistrationCreator(pa); + for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { + switch(me.getName()) { + case "": + assertEquals(hostname,me.getHostname()); + assertEquals(port,me.getPort()); + break; + case "service": + assertEquals(hostname,me.getHostname()); + assertEquals(port,me.getPort()); + break; + default: + fail("unknown Locator Entry"); + } + assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); + assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); + assertEquals(2,me.getMajor()); + assertEquals(1,me.getMinor()); + assertEquals(0,me.getPatch()); + assertEquals(0,me.getPkg()); + assertEquals(protocol,me.getProtocol()); + assertEquals(0,me.getSpecialPorts().size()); + } - pa.setProperty(Config.AAF_LOCATOR_CONTAINER, "oom"); - pa.setProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF); - pa.setProperty(Config.AAF_LOCATOR_NAME,"%NS.%N"); - pa.setProperty(Config.AAF_LOCATOR_NAME+DOT_OOM,"%CNS.%NS.%N"); - pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS+DOT_OOM, "onap"); - String k8s_public_hostname="k8s.public.com"; - int public_port = 30001; - - pa.setProperty(Config.AAF_LOCATOR_PUBLIC_FQDN,k8s_public_hostname); - pa.setProperty(Config.AAF_LOCATOR_PUBLIC_PORT+DOT_OOM,Integer.toString(public_port)); - pa.setProperty(Config.AAF_LOCATOR_APP_NS, Config.AAF_ROOT_NS_DEF); - rc = new RegistrationCreator(pa); - for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { - switch(me.getName()) { - case "org.osaaf.aaf.service": - assertEquals(k8s_public_hostname,me.getHostname()); - assertEquals(public_port,me.getPort()); - break; - case "onap.org.osaaf.aaf.service": - assertEquals(hostname,me.getHostname()); - assertEquals(port,me.getPort()); - break; - default: - fail("unknown Entry Name, " + me.getName()); - } - assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); - assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); - assertEquals(2,me.getMajor()); - assertEquals(1,me.getMinor()); - assertEquals(0,me.getPatch()); - assertEquals(0,me.getPkg()); - assertEquals(protocol,me.getProtocol()); - assertEquals(0,me.getSpecialPorts().size()); - } + pa.setProperty(Config.AAF_LOCATOR_CONTAINER, "oom"); + pa.setProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF); + pa.setProperty(Config.AAF_LOCATOR_NAME,"%NS.%N"); + pa.setProperty(Config.AAF_LOCATOR_NAME+DOT_OOM,"%CNS.%NS.%N"); + pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS+DOT_OOM, "onap"); + String k8s_public_hostname="k8s.public.com"; + int public_port = 30001; + + pa.setProperty(Config.AAF_LOCATOR_PUBLIC_FQDN,k8s_public_hostname); + pa.setProperty(Config.AAF_LOCATOR_PUBLIC_PORT+DOT_OOM,Integer.toString(public_port)); + pa.setProperty(Config.AAF_LOCATOR_APP_NS, Config.AAF_ROOT_NS_DEF); + rc = new RegistrationCreator(pa); + for(MgmtEndpoint me : rc.create(port).getMgmtEndpoint()) { + switch(me.getName()) { + case "org.osaaf.aaf.service": + assertEquals(k8s_public_hostname,me.getHostname()); + assertEquals(public_port,me.getPort()); + break; + case "onap.org.osaaf.aaf.service": + assertEquals(hostname,me.getHostname()); + assertEquals(port,me.getPort()); + break; + default: + fail("unknown Entry Name, " + me.getName()); + } + assertEquals(pa.getProperty(Config.CADI_LATITUDE),Float.toString(me.getLatitude())); + assertEquals(pa.getProperty(Config.CADI_LONGITUDE),Float.toString(me.getLongitude())); + assertEquals(2,me.getMajor()); + assertEquals(1,me.getMinor()); + assertEquals(0,me.getPatch()); + assertEquals(0,me.getPkg()); + assertEquals(protocol,me.getProtocol()); + assertEquals(0,me.getSpecialPorts().size()); + } - } catch (CadiException | UnknownHostException e) { - Assert.fail(e.getMessage()); - } - + } catch (CadiException | UnknownHostException e) { + Assert.fail(e.getMessage()); + } + - } + } } diff --git a/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java b/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java index f70fc279..9871c471 100644 --- a/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java +++ b/cadi/aaf/src/test/java/org/onap/aaf/cadi/sso/test/JU_AAFSSO.java @@ -60,7 +60,7 @@ public class JU_AAFSSO { @Test public void test() { - + // Note this is desctructive of personal dirs, and doesn't really test anything. Needs redoing. // AAFSSO sso; // String[] args; @@ -70,7 +70,7 @@ public class JU_AAFSSO { // "-noexit", // }; // try { -// sso = new AAFSSO(args); +// sso = new AAFSSO(args); // // assertThat(new File(aafDir).exists(), is(true)); // assertThat(new File(aafDir + "/.aaf").exists(), is(true)); @@ -108,9 +108,9 @@ public class JU_AAFSSO { // assertThat(sso.useX509(), is(false)); //// //// sso.close(); -// } catch (IOException | CadiException e) { -// e.printStackTrace(); -// } +// } catch (IOException | CadiException e) { +// e.printStackTrace(); +// } } 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 30673f75..38465da4 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 @@ -34,7 +34,7 @@ public class HBasicAuthSS extends HAuthorizationHeader implements BasicAuth { public HBasicAuthSS(SecurityInfoC<HttpURLConnection> si, String user, String password) throws IOException { super(si, user, "Basic " + Symm.base64noSplit.encode(user + ':' + password)); if(password==null) { - throw new IOException("No password passed for " + user); + throw new IOException("No password passed for " + user); } } 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 9255128c..61112c47 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 @@ -121,7 +121,7 @@ public class HClient implements EClient<HttpURLConnection> { } pi.append(pathinfo); } - URI sendURI = null; + URI sendURI = null; try { sendURI = new URI( uri.getScheme(), @@ -149,13 +149,13 @@ public class HClient implements EClient<HttpURLConnection> { } // TODO other settings? There's a bunch here. } catch (APIException e) { - throw e; + throw e; } catch (Exception e) { - if(sendURI==null) { - throw new APIException("Cannot connect to Root URI: '" + uri.toString() + '\'',e); - } else { - throw new APIException("Cannot connect to '" + sendURI.toString() + "' (Root URI: '" + uri.toString() + "')",e); - } + if(sendURI==null) { + throw new APIException("Cannot connect to Root URI: '" + uri.toString() + '\'',e); + } else { + throw new APIException("Cannot connect to '" + sendURI.toString() + "' (Root URI: '" + uri.toString() + "')",e); + } } finally { // ensure all these are reset after sends meth=pathinfo=null; if (headers!=null) { @@ -170,7 +170,7 @@ public class HClient implements EClient<HttpURLConnection> { } public void setURI(URI uri) { - this.uri = uri; + this.uri = uri; } public int timeout() { 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 ae562cb2..19e40b3a 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 @@ -170,11 +170,11 @@ public class HMangr { } public <RET> RET allExcept(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable,boolean notify, String selfHost) throws LocatorException, CadiException, APIException { - return call(ss,retryable,notify,selfHost); + return call(ss,retryable,notify,selfHost); } public<RET> RET oneOf(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable,boolean notify,String host) throws LocatorException, CadiException, APIException { - return call(ss,retryable,notify,host); + return call(ss,retryable,notify,host); } private<RET> RET call(SecuritySetter<HttpURLConnection> ss, Retryable<RET> retryable,boolean notify,String host) throws LocatorException, CadiException, APIException { RET ret = null; 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 66ef4b1e..4711aee6 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 @@ -77,10 +77,10 @@ public class DNSLocator implements Locator<URI> { } public static DNSLocator create(Access access, String url) throws LocatorException { - return new DNSLocator(access, url); - } + return new DNSLocator(access, url); + } - @Override + @Override public URI get(Item item) throws LocatorException { return hosts[((DLItem)item).cnt].uri; } @@ -167,7 +167,7 @@ public class DNSLocator implements Locator<URI> { int slash, start; int colon = aaf_locate.indexOf(':',_start); if (colon > 0) { - host = aaf_locate.substring(_start,colon); + host = aaf_locate.substring(_start,colon); start = colon + 1; int left = aaf_locate.indexOf('[', start); if (left > 0) { @@ -189,7 +189,7 @@ public class DNSLocator implements Locator<URI> { } slash = aaf_locate.indexOf('/', start); if(slash>=0) { - suffix = aaf_locate.substring(slash); + suffix = aaf_locate.substring(slash); } } else { @@ -205,8 +205,8 @@ public class DNSLocator implements Locator<URI> { } } } else { - slash = aaf_locate.indexOf('/', _start); - host = slash<_start?aaf_locate.substring(_start):aaf_locate.substring(_start,slash); + slash = aaf_locate.indexOf('/', _start); + host = slash<_start?aaf_locate.substring(_start):aaf_locate.substring(_start,slash); startPort = endPort = defaultPort; } @@ -225,7 +225,7 @@ public class DNSLocator implements Locator<URI> { } public String toString() { - return uri.toString() + " - " + status.name(); + return uri.toString() + " - " + status.name(); } } 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 bccb8116..34889138 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 @@ -182,7 +182,7 @@ public class PropertyLocator implements Locator<URI> { String realname; for (int i = 0; i < orig.length ; ++i) { try { - FixURIinfo fui = new FixURIinfo(orig[i]); + FixURIinfo fui = new FixURIinfo(orig[i]); InetAddress ia[] = InetAddress.getAllByName(fui.getHost()); URI o,n; diff --git a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java index d1744253..10eb8184 100644 --- a/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java +++ b/cadi/client/src/test/java/org/onap/aaf/cadi/http/test/JU_HMangr.java @@ -184,10 +184,10 @@ public class JU_HMangr { assertThat(hman.best(ssMock, retryableMock), is(nullValue())); try { - hman.all(ssMock, retryableMock, true); - Assert.fail("Should have thrown LocatorException"); + hman.all(ssMock, retryableMock, true); + Assert.fail("Should have thrown LocatorException"); } catch (LocatorException e) { - assertEquals(e.getLocalizedMessage(),"No available clients to call"); + assertEquals(e.getLocalizedMessage(),"No available clients to call"); } } 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 0a1f38db..b697f373 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 @@ -114,7 +114,7 @@ public class CmdLine { // 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]) || "undigest".equalsIgnoreCase(args[0])) - && args.length>2) { + && args.length>2) { try { Symm symm; FileInputStream fis = new FileInputStream(args[2]); 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 9f4b4b9f..1bf0230e 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 @@ -48,9 +48,9 @@ public class PropAccess implements Access { // Sonar says cannot be static... it's ok. not too many PropAccesses created. private final SimpleDateFormat iso8601 = newISO8601(); private Symm symm; - + public static SimpleDateFormat newISO8601() { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); } public static final Level DEFAULT = Level.AUDIT; @@ -135,12 +135,12 @@ public class PropAccess implements Access { load(props.getProperty(Config.CADI_PROP_FILES)); if(sLevel==null) { // if LogLev wasn't set before, check again after Chained Load - sLevel = props.getProperty(Config.CADI_LOGLEVEL); - if (sLevel==null) { - level=DEFAULT.maskOf(); - } else { - level=Level.valueOf(sLevel).maskOf(); - } + sLevel = props.getProperty(Config.CADI_LOGLEVEL); + if (sLevel==null) { + level=DEFAULT.maskOf(); + } else { + level=Level.valueOf(sLevel).maskOf(); + } } // Setup local Symmetrical key encryption if (symm==null) { @@ -179,15 +179,15 @@ public class PropAccess implements Access { // Only load props from recursion which are not already in props // meaning top Property file takes precedence for(Entry<Object, Object> es : fileProps.entrySet()) { - if(props.get(es.getKey())==null) { - String key = es.getKey().toString(); - String value = es.getValue().toString(); - props.put(key, value); - if(key.contains("pass")) { - value = "XXXXXXX"; - } - printf(Level.DEBUG," %s=%s",key,value); - } + if(props.get(es.getKey())==null) { + String key = es.getKey().toString(); + String value = es.getValue().toString(); + props.put(key, value); + if(key.contains("pass")) { + value = "XXXXXXX"; + } + printf(Level.DEBUG," %s=%s",key,value); + } } // Recursively Load String chainProp = fileProps.getProperty(Config.CADI_PROP_FILES); @@ -272,64 +272,64 @@ public class PropAccess implements Access { * Need to pass in DateFormat per thread, because not marked as thread safe */ public static StringBuilder buildMsg(final String name, final DateFormat sdf, Level level, Object[] elements) { - final StringBuilder sb; + final StringBuilder sb; int end = elements.length; - if(sdf==null) { - sb = new StringBuilder(); - write(true,sb,elements); - } else { - sb = new StringBuilder( - sdf.format(new Date()) - ); + if(sdf==null) { + sb = new StringBuilder(); + write(true,sb,elements); + } else { + sb = new StringBuilder( + sdf.format(new Date()) + ); sb.append(' '); sb.append(level.name()); sb.append(" ["); sb.append(name); - if (end<=0) { - sb.append("] "); - } else { - int idx = 0; - if(elements[idx]!=null && - elements[idx] instanceof Integer) { - sb.append('-'); - sb.append(elements[idx]); - ++idx; - } - sb.append("] "); - write(true,sb,elements); - } - } + if (end<=0) { + sb.append("] "); + } else { + int idx = 0; + if(elements[idx]!=null && + elements[idx] instanceof Integer) { + sb.append('-'); + sb.append(elements[idx]); + ++idx; + } + sb.append("] "); + write(true,sb,elements); + } + } return sb; } private static boolean write(boolean first, StringBuilder sb, Object[] elements) { - String s; + String s; for (Object o : elements) { if (o!=null) { - if(o.getClass().isArray()) { - first = write(first,sb,(Object[])o); - } else if(o instanceof Throwable) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - PrintStream ps = new PrintStream(baos); - ((Throwable)o).printStackTrace(ps); - sb.append(baos.toString()); - } else { - s=o.toString(); - if (first) { - first = false; - } else { - int l = s.length(); - if (l>0) { - switch(s.charAt(l-1)) { - case ' ': - break; - default: - sb.append(' '); - } - } - } - sb.append(s); - } + if(o.getClass().isArray()) { + first = write(first,sb,(Object[])o); + } else if(o instanceof Throwable) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + ((Throwable)o).printStackTrace(ps); + sb.append(baos.toString()); + } else { + s=o.toString(); + if (first) { + first = false; + } else { + int l = s.length(); + if (l>0) { + switch(s.charAt(l-1)) { + case ' ': + break; + default: + sb.append(' '); + } + } + } + sb.append(s); + } } } return first; @@ -337,10 +337,10 @@ public class PropAccess implements Access { @Override public void log(Exception e, Object... elements) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - pw.println(); - e.printStackTrace(pw); + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + pw.println(); + e.printStackTrace(pw); log(Level.ERROR,elements,sw.toString()); } @@ -436,6 +436,6 @@ public class PropAccess implements Access { } public String toString() { - return props.toString(); + return props.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 9a66d313..e7533610 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 @@ -82,7 +82,7 @@ public class Symm { private byte[] keyBytes = null; //Note: AES Encryption is not Thread Safe. It is Synchronized //private AES aes = null; // only initialized from File, and only if needed for Passwords - private String name; + private String name; /** * This is the standard base64 Key Set. @@ -900,6 +900,6 @@ public class Symm { @Override public String toString() { - return name; + return name; } } 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 30508b7d..7bd578a5 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 @@ -275,10 +275,10 @@ public class Config { Access access = si.access; RegistrationPropHolder rph; try { - rph = new RegistrationPropHolder(access, 0); - } catch (UnknownHostException e2) { - throw new CadiException(e2); - } + rph = new RegistrationPropHolder(access, 0); + } catch (UnknownHostException e2) { + throw new CadiException(e2); + } ///////////////////////////////////////////////////// // Setup AAFCon for any following ///////////////////////////////////////////////////// @@ -504,7 +504,7 @@ public class Config { // Any Additional Tafs passed in Constructor ///////////////////////////////////////////////////// if (additionalTafLurs!=null) { - int i=0; + int i=0; for (Object additional : additionalTafLurs) { if (additional instanceof BasicHttpTaf) { BasicHttpTaf ht = (BasicHttpTaf)additional; @@ -556,17 +556,17 @@ public class Config { // just return the one taf = htlist.get(0).t; } else { - Collections.sort(htlist); + Collections.sort(htlist); HttpTaf[] htarray = new HttpTaf[htlist.size()]; int i=-1; StringBuilder sb = new StringBuilder("Tafs processed in this order:\n"); for(Priori<HttpTaf> pht : htlist) { - htarray[++i] = pht.t; - sb.append(" "); - sb.append(pht.t.getClass().getName()); - sb.append('('); - sb.append(pht.priority); - sb.append(")\n"); + htarray[++i] = pht.t; + sb.append(" "); + sb.append(pht.t.getClass().getName()); + sb.append('('); + sb.append(pht.priority); + sb.append(")\n"); } access.log(Level.INIT, sb); @@ -585,13 +585,13 @@ public class Config { public static String logProp(RegistrationPropHolder rph, String tag, String def) { String rv = rph.access().getProperty(tag, def); if (rv == null) { - rph.access().log(Level.INIT,tag,"is not explicitly set"); + rph.access().log(Level.INIT,tag,"is not explicitly set"); } else { - rv = rph.replacements("Config.logProp",rv, null, null); - rph.access().log(Level.INIT,tag,"is set to",rv); + rv = rph.replacements("Config.logProp",rv, null, null); + rph.access().log(Level.INIT,tag,"is set to",rv); } return rv; - + } public static String logProp(Access access,String tag, String def) { @@ -608,10 +608,10 @@ public class Config { Access access = si.access; RegistrationPropHolder rph; try { - rph = new RegistrationPropHolder(access, 0); - } catch (UnknownHostException e2) { - throw new CadiException(e2); - } + rph = new RegistrationPropHolder(access, 0); + } catch (UnknownHostException e2) { + throw new CadiException(e2); + } List<Priori<Lur>> lurs = new ArrayList<>(); @@ -728,7 +728,7 @@ public class Config { // Any Additional passed in Constructor ///////////////////////////////////////////////////// if (additionalTafLurs!=null) { - int i=0; + int i=0; for (Object additional : additionalTafLurs) { if (additional instanceof Lur) { lurs.add(new Priori<Lur>((Lur)additional,50+i++)); @@ -754,17 +754,17 @@ public class Config { return lurs.get(0).t; // Only one, just return it, save processing default: // Multiple Lurs, use EpiLUR to handle - Collections.sort(lurs); + Collections.sort(lurs); Lur[] la = new Lur[lurs.size()]; int i=-1; StringBuilder sb = new StringBuilder("Lurs processed in this order:\n"); for(Priori<Lur> pht : lurs) { - la[++i] = pht.t; - sb.append(" "); - sb.append(pht.t.getClass().getName()); - sb.append('('); - sb.append(pht.priority); - sb.append(")\n"); + la[++i] = pht.t; + sb.append(" "); + sb.append(pht.t.getClass().getName()); + sb.append('('); + sb.append(pht.priority); + sb.append(")\n"); } access.log(Level.INIT, sb); return new EpiLur(la); @@ -855,53 +855,53 @@ public class Config { if (_url==null) { access.log(Level.INIT,"No URL passed to 'loadLocator'. Disabled"); } else { - try { - Class<?> aalCls = Class.forName("org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator"); - Method aalMth = aalCls.getMethod("create", String.class,String.class); - int colon = _url.lastIndexOf(':'); - if(colon>=0) { - int slash = _url.indexOf('/',colon); - String version; - if(slash<0) { - version = _url.substring(colon+1); - } else { - version = _url.substring(colon+1,slash); - } - slash = _url.lastIndexOf('/',colon); - if(slash>=0) { - Object aal = aalMth.invoke(null/*static*/, _url.substring(slash+1, colon),version); - return (Locator<URI>)aal; - } - } - } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - String msg; - char quote; - if(e.getCause()!=null) { - msg=e.getCause().getMessage(); - quote='"'; - } else { - msg = "-"; - quote=' '; - } - access.printf(Level.DEBUG, "Configured AbsAAFLocator not found%c%s%cContinuing Locator creation ",quote,msg,quote); - } + try { + Class<?> aalCls = Class.forName("org.onap.aaf.cadi.aaf.v2_0.AbsAAFLocator"); + Method aalMth = aalCls.getMethod("create", String.class,String.class); + int colon = _url.lastIndexOf(':'); + if(colon>=0) { + int slash = _url.indexOf('/',colon); + String version; + if(slash<0) { + version = _url.substring(colon+1); + } else { + version = _url.substring(colon+1,slash); + } + slash = _url.lastIndexOf('/',colon); + if(slash>=0) { + Object aal = aalMth.invoke(null/*static*/, _url.substring(slash+1, colon),version); + return (Locator<URI>)aal; + } + } + } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + String msg; + char quote; + if(e.getCause()!=null) { + msg=e.getCause().getMessage(); + quote='"'; + } else { + msg = "-"; + quote=' '; + } + access.printf(Level.DEBUG, "Configured AbsAAFLocator not found%c%s%cContinuing Locator creation ",quote,msg,quote); + } // String url = _url.replace("/AAF_NS.", "/%C%CID%AAF_NS."); // String root_ns = access.getProperty(Config.AAF_ROOT_NS, null); - String url; + String url; RegistrationPropHolder rph; try { - rph = new RegistrationPropHolder(access, 0); - url = rph.replacements("Config.loadLocator",_url, null, null); - access.printf(Level.INFO, "loadLocator URL is %s",url); - } catch (UnknownHostException | CadiException e1) { - throw new LocatorException(e1); - } + rph = new RegistrationPropHolder(access, 0); + url = rph.replacements("Config.loadLocator",_url, null, null); + access.printf(Level.INFO, "loadLocator URL is %s",url); + } catch (UnknownHostException | CadiException e1) { + throw new LocatorException(e1); + } String aaf_locator_class; if(_url.equals(url) && !url.contains("/locate/")) { - aaf_locator_class = "org.onap.aaf.cadi.locator.DNSLocator"; + aaf_locator_class = "org.onap.aaf.cadi.locator.DNSLocator"; } else { - aaf_locator_class = AAF_LOCATOR_CLASS_DEF; + aaf_locator_class = AAF_LOCATOR_CLASS_DEF; } try { Class<?> lcls = loadClass(access,aaf_locator_class); @@ -945,83 +945,83 @@ public class Config { } public static String getAAFLocateUrl(Access access) { - String rv = null; - String cont = access.getProperty(AAF_LOCATOR_CONTAINER,null); - if(cont!=null) { - rv = access.getProperty(AAF_LOCATE_URL + '.' +cont, null); - } - if(rv==null) { - rv = access.getProperty(AAF_LOCATE_URL, null); - } - return rv; + String rv = null; + String cont = access.getProperty(AAF_LOCATOR_CONTAINER,null); + if(cont!=null) { + rv = access.getProperty(AAF_LOCATE_URL + '.' +cont, null); + } + if(rv==null) { + rv = access.getProperty(AAF_LOCATE_URL, null); + } + return rv; } private static class Priori<T> implements Comparable<Priori<T>> { - public final T t; - public final int priority; - - public Priori(final T t, final int priority) { - this.t = t; - this.priority = priority; - } + public final T t; + public final int priority; + + public Priori(final T t, final int priority) { + this.t = t; + this.priority = priority; + } - @Override - public int compareTo(Priori<T> o) { - if(priority==o.priority) { - return 0; - } else if(priority<o.priority) { - return -1; - } else { - return 1; - } - } - public static<T> void add(Access access, final String tag, List<Priori<T>> list) { - String plugins = access.getProperty(tag, null); - if(plugins!=null) { - access.log(Level.INIT, "Adding TAF Plugins: ", plugins); - for(String tafs : Split.splitTrim(';', plugins)) { - String[] pluginArray = Split.splitTrim(',', tafs); - String clssn = null; - int priority = 60; - switch(pluginArray.length) { - case 0: - break; - case 1: - clssn = tafs; - break; - default: - clssn = pluginArray[0]; - try { - priority = Integer.parseInt(pluginArray[1]); - } catch (NumberFormatException nfe) { - access.printf(Level.ERROR, "%s format is <classname>,priority[;...]\n",CADI_ADD_TAFS); - } - } - - if(clssn!=null) { - Class<?> cls = loadClass(access, clssn); - if(cls!=null) { - try { - @SuppressWarnings("unchecked") - Constructor<T> cnst = (Constructor<T>)cls.getConstructor(Access.class); - try { - list.add(new Priori<T>(cnst.newInstance(access),priority)); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - String hostname = access.getProperty(Config.HOSTNAME,null); - if(hostname==null) { - access.printf(Level.ERROR, "%s cannot be constructed on this machine. Set valid 'hostname' in your properties\n",clssn); - } else { - access.printf(Level.ERROR, "%s cannot be constructed on %s with Access.\n",clssn, hostname); - } - } - } catch (NoSuchMethodException | SecurityException e) { - access.printf(Level.ERROR, "%s needs a Constructor taking Access as sole param.\n",clssn); - } - } - } - } - } - } + @Override + public int compareTo(Priori<T> o) { + if(priority==o.priority) { + return 0; + } else if(priority<o.priority) { + return -1; + } else { + return 1; + } + } + public static<T> void add(Access access, final String tag, List<Priori<T>> list) { + String plugins = access.getProperty(tag, null); + if(plugins!=null) { + access.log(Level.INIT, "Adding TAF Plugins: ", plugins); + for(String tafs : Split.splitTrim(';', plugins)) { + String[] pluginArray = Split.splitTrim(',', tafs); + String clssn = null; + int priority = 60; + switch(pluginArray.length) { + case 0: + break; + case 1: + clssn = tafs; + break; + default: + clssn = pluginArray[0]; + try { + priority = Integer.parseInt(pluginArray[1]); + } catch (NumberFormatException nfe) { + access.printf(Level.ERROR, "%s format is <classname>,priority[;...]\n",CADI_ADD_TAFS); + } + } + + if(clssn!=null) { + Class<?> cls = loadClass(access, clssn); + if(cls!=null) { + try { + @SuppressWarnings("unchecked") + Constructor<T> cnst = (Constructor<T>)cls.getConstructor(Access.class); + try { + list.add(new Priori<T>(cnst.newInstance(access),priority)); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + String hostname = access.getProperty(Config.HOSTNAME,null); + if(hostname==null) { + access.printf(Level.ERROR, "%s cannot be constructed on this machine. Set valid 'hostname' in your properties\n",clssn); + } else { + access.printf(Level.ERROR, "%s cannot be constructed on %s with Access.\n",clssn, hostname); + } + } + } catch (NoSuchMethodException | SecurityException e) { + access.printf(Level.ERROR, "%s needs a Constructor taking Access as sole param.\n",clssn); + } + } + } + } + } + } } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/RegistrationPropHolder.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/RegistrationPropHolder.java index 2a8760f4..f73179a9 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/RegistrationPropHolder.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/RegistrationPropHolder.java @@ -29,259 +29,259 @@ import org.onap.aaf.cadi.CadiException; import org.onap.aaf.cadi.util.Split; public class RegistrationPropHolder { - private final String PUBLIC_NAME="%NS.%N"; - private final String REGI="RegistrationProperty: %s='%s'"; - private final Access access; - public String hostname; - private int port; - public String public_fqdn; - private Integer public_port; - public Float latitude; - public Float longitude; - public final String default_fqdn; - public final String default_container_ns; - public final String default_name; - public final String lentries; - public final String lcontainer; - public final String default_container; - private static boolean firstlog = true; + private final String PUBLIC_NAME="%NS.%N"; + private final String REGI="RegistrationProperty: %s='%s'"; + private final Access access; + public String hostname; + private int port; + public String public_fqdn; + private Integer public_port; + public Float latitude; + public Float longitude; + public final String default_fqdn; + public final String default_container_ns; + public final String default_name; + public final String lentries; + public final String lcontainer; + public final String default_container; + private static boolean firstlog = true; - public RegistrationPropHolder(final Access access, final int port) throws UnknownHostException, CadiException { - this.access = access; - StringBuilder errs = new StringBuilder(); - String str; - this.port = port; + public RegistrationPropHolder(final Access access, final int port) throws UnknownHostException, CadiException { + this.access = access; + StringBuilder errs = new StringBuilder(); + String str; + this.port = port; - lentries=access.getProperty(Config.AAF_LOCATOR_ENTRIES,""); - default_container = access.getProperty(Config.AAF_LOCATOR_CONTAINER, ""); - if(firstlog) { - access.printf(Level.INIT, REGI,"default_container",default_container); - } - if(!default_container.isEmpty()) { - lcontainer=',' + default_container; // "" makes a blank default Public Entry - str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_PORT+'.'+default_container, null); - if(str==null) { - str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_PORT, null); - } - } else { - lcontainer=default_container; - str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_PORT, null); - } - if(str!=null) { - public_port=Integer.decode(str); - } - if(firstlog) { - access.printf(Level.INIT, "RegistrationProperty: public_port='%d'",public_port); - } + lentries=access.getProperty(Config.AAF_LOCATOR_ENTRIES,""); + default_container = access.getProperty(Config.AAF_LOCATOR_CONTAINER, ""); + if(firstlog) { + access.printf(Level.INIT, REGI,"default_container",default_container); + } + if(!default_container.isEmpty()) { + lcontainer=',' + default_container; // "" makes a blank default Public Entry + str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_PORT+'.'+default_container, null); + if(str==null) { + str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_PORT, null); + } + } else { + lcontainer=default_container; + str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_PORT, null); + } + if(str!=null) { + public_port=Integer.decode(str); + } + if(firstlog) { + access.printf(Level.INIT, "RegistrationProperty: public_port='%d'",public_port); + } - hostname = access.getProperty(Config.HOSTNAME, null); - if (hostname==null) { - hostname = Inet4Address.getLocalHost().getHostName(); - } - if (hostname==null) { - mustBeDefined(errs,Config.HOSTNAME); - } - if(firstlog) { - access.printf(Level.INIT, REGI,"hostname",hostname); - } + hostname = access.getProperty(Config.HOSTNAME, null); + if (hostname==null) { + hostname = Inet4Address.getLocalHost().getHostName(); + } + if (hostname==null) { + mustBeDefined(errs,Config.HOSTNAME); + } + if(firstlog) { + access.printf(Level.INIT, REGI,"hostname",hostname); + } - public_fqdn = access.getProperty(Config.AAF_LOCATOR_PUBLIC_FQDN, hostname); - if(firstlog) { - access.printf(Level.INIT, REGI,"public_fqdn",public_fqdn); - } + public_fqdn = access.getProperty(Config.AAF_LOCATOR_PUBLIC_FQDN, hostname); + if(firstlog) { + access.printf(Level.INIT, REGI,"public_fqdn",public_fqdn); + } - // Allow Container to reset the standard name for public - String container_public_name = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME+'.'+default_container, null); - if(container_public_name==null) { - container_public_name = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME, null); - if(container_public_name==null) { - container_public_name = access.getProperty(Config.AAF_LOCATOR_NAME, PUBLIC_NAME); - } - } - default_name = container_public_name; - - if(firstlog) { - access.printf(Level.INIT, REGI,"default_name",default_name); - } - - latitude=null; - String slatitude = access.getProperty(Config.CADI_LATITUDE, null); - if(slatitude == null) { - mustBeDefined(errs,Config.CADI_LATITUDE); - } else { - latitude = Float.parseFloat(slatitude); - } - if(firstlog) { - access.printf(Level.INIT, REGI,"latitude",slatitude); - } + // Allow Container to reset the standard name for public + String container_public_name = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME+'.'+default_container, null); + if(container_public_name==null) { + container_public_name = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME, null); + if(container_public_name==null) { + container_public_name = access.getProperty(Config.AAF_LOCATOR_NAME, PUBLIC_NAME); + } + } + default_name = container_public_name; + + if(firstlog) { + access.printf(Level.INIT, REGI,"default_name",default_name); + } + + latitude=null; + String slatitude = access.getProperty(Config.CADI_LATITUDE, null); + if(slatitude == null) { + mustBeDefined(errs,Config.CADI_LATITUDE); + } else { + latitude = Float.parseFloat(slatitude); + } + if(firstlog) { + access.printf(Level.INIT, REGI,"latitude",slatitude); + } - longitude=null; - String slongitude = access.getProperty(Config.CADI_LONGITUDE, null); - if(slongitude == null) { - mustBeDefined(errs,Config.CADI_LONGITUDE); - } else { - longitude = Float.parseFloat(slongitude); - } - if(firstlog) { - access.printf(Level.INIT, REGI,"longitude",slongitude); - } + longitude=null; + String slongitude = access.getProperty(Config.CADI_LONGITUDE, null); + if(slongitude == null) { + mustBeDefined(errs,Config.CADI_LONGITUDE); + } else { + longitude = Float.parseFloat(slongitude); + } + if(firstlog) { + access.printf(Level.INIT, REGI,"longitude",slongitude); + } - String dot_le; - // Note: only one of the ports can be public... Therefore, only the last - for(String le : Split.splitTrim(',', lcontainer)) { - dot_le = le.isEmpty()?le :"."+le; - str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_FQDN+dot_le,null); - if( str != null && !str.isEmpty()) { - public_fqdn=str; - if(firstlog) { - access.printf(Level.INIT, "RegistrationProperty: public_hostname(overloaded by %s)='%s'",dot_le,public_fqdn); - } - } - } - - default_fqdn = access.getProperty(Config.AAF_LOCATOR_FQDN, hostname); - if(firstlog) { - access.printf(Level.INIT, REGI,"default_fqdn",default_fqdn); - } - default_container_ns = access.getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); - if(firstlog) { - access.printf(Level.INIT, REGI,"default_container_ns",default_container_ns); - } - if(errs.length()>0) { - throw new CadiException(errs.toString()); - } - firstlog = false; - } + String dot_le; + // Note: only one of the ports can be public... Therefore, only the last + for(String le : Split.splitTrim(',', lcontainer)) { + dot_le = le.isEmpty()?le :"."+le; + str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_FQDN+dot_le,null); + if( str != null && !str.isEmpty()) { + public_fqdn=str; + if(firstlog) { + access.printf(Level.INIT, "RegistrationProperty: public_hostname(overloaded by %s)='%s'",dot_le,public_fqdn); + } + } + } + + default_fqdn = access.getProperty(Config.AAF_LOCATOR_FQDN, hostname); + if(firstlog) { + access.printf(Level.INIT, REGI,"default_fqdn",default_fqdn); + } + default_container_ns = access.getProperty(Config.AAF_LOCATOR_CONTAINER_NS,""); + if(firstlog) { + access.printf(Level.INIT, REGI,"default_container_ns",default_container_ns); + } + if(errs.length()>0) { + throw new CadiException(errs.toString()); + } + firstlog = false; + } - private void mustBeDefined(StringBuilder errs, String propname) { - errs.append('\n'); - errs.append(propname); - errs.append(" must be defined."); - - } + private void mustBeDefined(StringBuilder errs, String propname) { + errs.append('\n'); + errs.append(propname); + errs.append(" must be defined."); + + } - public String getEntryFQDN(final String entry, final String dot_le) { - String str; - if(public_fqdn!=null && dot_le.isEmpty()) { - str = public_fqdn; - } else { - str = access.getProperty(Config.AAF_LOCATOR_FQDN+dot_le, default_fqdn); - } - return replacements("RegistrationPropHolder.getEntryFQDN",str,entry,dot_le); - } - - public String getEntryName(final String entry, final String dot_le) { - String str; - if(dot_le.isEmpty()) { - str = default_name; - } else { - str = access.getProperty(Config.AAF_LOCATOR_NAME+dot_le, default_name); - } - return replacements("RegistrationPropHolder.getEntryName",str,entry,dot_le); - } - - public String getPublicEntryName(final String entry, final String dot_le) { - String str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME+dot_le, null); - if(str==null) { - str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME,null); - } - if(str==null) { - str = default_name; - } - return replacements("RegistrationPropHolder.getEntryName",str,entry,dot_le); - } - - - private String getNS(String dot_le) { - String ns; - ns = access.getProperty(Config.AAF_LOCATOR_APP_NS+dot_le,null); - if(ns==null) { - ns = access.getProperty(Config.AAF_LOCATOR_APP_NS, "AAF_NS"); - } - return ns; - } + public String getEntryFQDN(final String entry, final String dot_le) { + String str; + if(public_fqdn!=null && dot_le.isEmpty()) { + str = public_fqdn; + } else { + str = access.getProperty(Config.AAF_LOCATOR_FQDN+dot_le, default_fqdn); + } + return replacements("RegistrationPropHolder.getEntryFQDN",str,entry,dot_le); + } + + public String getEntryName(final String entry, final String dot_le) { + String str; + if(dot_le.isEmpty()) { + str = default_name; + } else { + str = access.getProperty(Config.AAF_LOCATOR_NAME+dot_le, default_name); + } + return replacements("RegistrationPropHolder.getEntryName",str,entry,dot_le); + } + + public String getPublicEntryName(final String entry, final String dot_le) { + String str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME+dot_le, null); + if(str==null) { + str = access.getProperty(Config.AAF_LOCATOR_PUBLIC_NAME,null); + } + if(str==null) { + str = default_name; + } + return replacements("RegistrationPropHolder.getEntryName",str,entry,dot_le); + } + + + private String getNS(String dot_le) { + String ns; + ns = access.getProperty(Config.AAF_LOCATOR_APP_NS+dot_le,null); + if(ns==null) { + ns = access.getProperty(Config.AAF_LOCATOR_APP_NS, "AAF_NS"); + } + return ns; + } - - public String replacements(final String fromCode, final String source, final String name, final String _dot_le) { - if(source == null) { - return ""; - } else if(source.isEmpty()) { - return source; - } - String value = source; - String dot_le; - if(_dot_le==null) { - dot_le = default_container.isEmpty()?"":'.'+default_container; - } else { - dot_le = _dot_le; - } + + public String replacements(final String fromCode, final String source, final String name, final String _dot_le) { + if(source == null) { + return ""; + } else if(source.isEmpty()) { + return source; + } + String value = source; + String dot_le; + if(_dot_le==null) { + dot_le = default_container.isEmpty()?"":'.'+default_container; + } else { + dot_le = _dot_le; + } String aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL+dot_le,null); if(aaf_locator_host==null) { - aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL,null); + aaf_locator_host = access.getProperty(Config.AAF_LOCATE_URL,null); } String str; if(aaf_locator_host!=null) { - if("https://AAF_LOCATE_URL".equals(value)) { - value = aaf_locator_host; - } else { - str = aaf_locator_host; - if(value.indexOf(Config.AAF_LOCATE_URL_TAG)>=0) { - if(!str.endsWith("/")) { - str+='/'; - } - if(!str.endsWith("/locate/")) { - str+="locate/"; - } - if(value.startsWith("http:")) { - value = value.replace("http://AAF_LOCATE_URL/", str); - } else { - value = value.replace("https://AAF_LOCATE_URL/", str); - - } - } - } + if("https://AAF_LOCATE_URL".equals(value)) { + value = aaf_locator_host; + } else { + str = aaf_locator_host; + if(value.indexOf(Config.AAF_LOCATE_URL_TAG)>=0) { + if(!str.endsWith("/")) { + str+='/'; + } + if(!str.endsWith("/locate/")) { + str+="locate/"; + } + if(value.startsWith("http:")) { + value = value.replace("http://AAF_LOCATE_URL/", str); + } else { + value = value.replace("https://AAF_LOCATE_URL/", str); + + } + } + } } - int atC = value.indexOf("%C"); - if(atC>=0) { - // aaf_locator_container_ns - str = access.getProperty(Config.AAF_LOCATOR_CONTAINER_NS+dot_le, default_container_ns); - if(str.isEmpty()) { - value = value.replace("%CNS"+'.', str); - } - value = value.replace("%CNS", str); - - str = access.getProperty(Config.AAF_LOCATOR_CONTAINER+dot_le,default_container); - if(str.isEmpty()) { - value = value.replace("%C"+'.', str); - } - value = value.replace("%C", str); - } - - if(value.indexOf("%NS")>=0) { - str = getNS(dot_le); - if(str==null || str.isEmpty()) { - value = value.replace("%NS"+'.', ""); - } else { - value = value.replace("%NS", str); - } - } + int atC = value.indexOf("%C"); + if(atC>=0) { + // aaf_locator_container_ns + str = access.getProperty(Config.AAF_LOCATOR_CONTAINER_NS+dot_le, default_container_ns); + if(str.isEmpty()) { + value = value.replace("%CNS"+'.', str); + } + value = value.replace("%CNS", str); + + str = access.getProperty(Config.AAF_LOCATOR_CONTAINER+dot_le,default_container); + if(str.isEmpty()) { + value = value.replace("%C"+'.', str); + } + value = value.replace("%C", str); + } + + if(value.indexOf("%NS")>=0) { + str = getNS(dot_le); + if(str==null || str.isEmpty()) { + value = value.replace("%NS"+'.', ""); + } else { + value = value.replace("%NS", str); + } + } - // aaf_root_ns - if(value.indexOf("AAF_NS")>=0) { - str = access.getProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF) + '.'; - String temp = value.replace("%AAF_NS.", str); - if(temp.equals(value)) { // intended - value = value.replace("AAF_NS.", str); // Backward Compatibility - } else { - value = temp; - } - } + // aaf_root_ns + if(value.indexOf("AAF_NS")>=0) { + str = access.getProperty(Config.AAF_ROOT_NS, Config.AAF_ROOT_NS_DEF) + '.'; + String temp = value.replace("%AAF_NS.", str); + if(temp.equals(value)) { // intended + value = value.replace("AAF_NS.", str); // Backward Compatibility + } else { + value = temp; + } + } - - if(value.indexOf('%')>=0) { + + if(value.indexOf('%')>=0) { // These shouldn't be expected to have dot elements if(name!=null) { value = value.replace("%N", name); @@ -292,21 +292,21 @@ public class RegistrationPropHolder { if(public_fqdn!=null) { value = value.replace("%PH", public_fqdn); } - } - access.printf(Level.DEBUG, - "RegistrationReplacement from %s, source: %s, dot_le: %s, value: %s", - fromCode,source,dot_le,value); + } + access.printf(Level.DEBUG, + "RegistrationReplacement from %s, source: %s, dot_le: %s, value: %s", + fromCode,source,dot_le,value); - return value; - } - - public int getEntryPort(final String dot_le) { - return public_port!=null && dot_le.isEmpty()? - public_port: - port; - } + return value; + } + + public int getEntryPort(final String dot_le) { + return public_port!=null && dot_le.isEmpty()? + public_port: + port; + } - public Access access() { - return access; - } + public Access access() { + return access; + } }
\ No newline at end of file diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java index 5d1d23fa..8dbc38e1 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/config/SecurityInfo.java @@ -56,12 +56,12 @@ import org.onap.aaf.cadi.util.NetMask; import org.onap.aaf.cadi.util.Split; public class SecurityInfo { - private static final String SECURITY_ALGO = "RSA"; + private static final String SECURITY_ALGO = "RSA"; private static final String HTTPS_PROTOCOLS = "https.protocols"; private static final String JDK_TLS_CLIENT_PROTOCOLS = "jdk.tls.client.protocols"; private static final String INITIALIZING_ERR_FMT = "Error initializing %s: %s"; - private static final String LOADED_FROM_CADI_PROPERTIES = "%s loaded from CADI Properties"; - private static final String LOADED_FROM_SYSTEM_PROPERTIES = "%s loaded from System Properties"; + private static final String LOADED_FROM_CADI_PROPERTIES = "%s loaded from CADI Properties"; + private static final String LOADED_FROM_SYSTEM_PROPERTIES = "%s loaded from System Properties"; public static final String SSL_KEY_MANAGER_FACTORY_ALGORITHM; @@ -86,26 +86,26 @@ public class SecurityInfo { public SecurityInfo(final Access access) throws CadiException { - String msgHelp = ""; + String msgHelp = ""; try { this.access = access; // reuse DME2 Properties for convenience if specific Properties don't exist String str = access.getProperty(Config.CADI_ALIAS, null); if(str==null || str.isEmpty()) { - defaultAlias = null; + defaultAlias = null; } else { - defaultAlias = str; + defaultAlias = str; } str = access.getProperty(Config.CADI_CLIENT_ALIAS, null); if(str==null) { - defaultClientAlias = defaultAlias; + defaultClientAlias = defaultAlias; } else if(str.isEmpty()) { - // intentionally off, i.e. cadi_client_alias= - defaultClientAlias = null; + // intentionally off, i.e. cadi_client_alias= + defaultClientAlias = null; } else { - defaultClientAlias = str; + defaultClientAlias = str; } msgHelp = String.format(INITIALIZING_ERR_FMT,"Keystore", access.getProperty(Config.CADI_KEYSTORE, "")); @@ -134,34 +134,34 @@ public class SecurityInfo { public static void setHTTPProtocols(Access access) { String httpsProtocols = System.getProperty(Config.HTTPS_PROTOCOLS); if(httpsProtocols!=null) { - access.printf(Level.INIT, LOADED_FROM_SYSTEM_PROPERTIES, HTTPS_PROTOCOLS); + access.printf(Level.INIT, LOADED_FROM_SYSTEM_PROPERTIES, HTTPS_PROTOCOLS); } else { - httpsProtocols = access.getProperty(Config.HTTPS_PROTOCOLS,null); - if(httpsProtocols!=null) { - access.printf(Level.INIT, LOADED_FROM_CADI_PROPERTIES, HTTPS_PROTOCOLS); - } else { - httpsProtocols = access.getProperty(HTTPS_PROTOCOLS, Config.HTTPS_PROTOCOLS_DEFAULT); - access.printf(Level.INIT, "%s set by %s in CADI Properties",Config.HTTPS_PROTOCOLS,Config.CADI_PROTOCOLS); - } - // This needs to be set when people do not. + httpsProtocols = access.getProperty(Config.HTTPS_PROTOCOLS,null); + if(httpsProtocols!=null) { + access.printf(Level.INIT, LOADED_FROM_CADI_PROPERTIES, HTTPS_PROTOCOLS); + } else { + httpsProtocols = access.getProperty(HTTPS_PROTOCOLS, Config.HTTPS_PROTOCOLS_DEFAULT); + access.printf(Level.INIT, "%s set by %s in CADI Properties",Config.HTTPS_PROTOCOLS,Config.CADI_PROTOCOLS); + } + // This needs to be set when people do not. System.setProperty(HTTPS_PROTOCOLS, httpsProtocols); } String httpsClientProtocols = System.getProperty(JDK_TLS_CLIENT_PROTOCOLS,null); if(httpsClientProtocols!=null) { - access.printf(Level.INIT, LOADED_FROM_SYSTEM_PROPERTIES, JDK_TLS_CLIENT_PROTOCOLS); + access.printf(Level.INIT, LOADED_FROM_SYSTEM_PROPERTIES, JDK_TLS_CLIENT_PROTOCOLS); } else { - httpsClientProtocols = access.getProperty(Config.HTTPS_CLIENT_PROTOCOLS, null); - if(httpsClientProtocols!=null) { - access.printf(Level.INIT, LOADED_FROM_CADI_PROPERTIES, Config.HTTPS_CLIENT_PROTOCOLS); - } else { - httpsClientProtocols = Config.HTTPS_PROTOCOLS_DEFAULT; - access.printf(Level.INIT, "%s set from %s",Config.HTTPS_CLIENT_PROTOCOLS, "Default Protocols"); - } - System.setProperty(JDK_TLS_CLIENT_PROTOCOLS, httpsClientProtocols); + httpsClientProtocols = access.getProperty(Config.HTTPS_CLIENT_PROTOCOLS, null); + if(httpsClientProtocols!=null) { + access.printf(Level.INIT, LOADED_FROM_CADI_PROPERTIES, Config.HTTPS_CLIENT_PROTOCOLS); + } else { + httpsClientProtocols = Config.HTTPS_PROTOCOLS_DEFAULT; + access.printf(Level.INIT, "%s set from %s",Config.HTTPS_CLIENT_PROTOCOLS, "Default Protocols"); + } + System.setProperty(JDK_TLS_CLIENT_PROTOCOLS, httpsClientProtocols); } - } + } - /** + /** * @return the scf */ public SSLSocketFactory getSSLSocketFactory() { @@ -201,7 +201,7 @@ public class SecurityInfo { protected void initializeKeyManager() throws CadiException, IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, UnrecoverableKeyException { String keyStore = access.getProperty(Config.CADI_KEYSTORE, null); if(keyStore==null) { - return; + return; } else if (!new File(keyStore).exists()) { throw new CadiException(keyStore + " does not exist"); } @@ -244,20 +244,20 @@ public class SecurityInfo { StringBuilder sb = null; for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) { if (keyManager instanceof X509KeyManager) { - X509KeyManager xkm = (X509KeyManager)keyManager; + X509KeyManager xkm = (X509KeyManager)keyManager; keyManagers.add(xkm); if(defaultAlias!=null) { - sb=new StringBuilder("X509 Chain\n"); - x509Info(sb,xkm.getCertificateChain(defaultAlias)); + sb=new StringBuilder("X509 Chain\n"); + x509Info(sb,xkm.getCertificateChain(defaultAlias)); } if(defaultClientAlias!=null && !defaultClientAlias.equals(defaultAlias)) { - if(sb==null) { - sb = new StringBuilder(); - } else { - sb.append('\n'); - } - sb.append("X509 Client Chain\n"); - x509Info(sb,xkm.getCertificateChain(defaultAlias)); + if(sb==null) { + sb = new StringBuilder(); + } else { + sb.append('\n'); + } + sb.append("X509 Client Chain\n"); + x509Info(sb,xkm.getCertificateChain(defaultAlias)); } } } @@ -265,32 +265,32 @@ public class SecurityInfo { keyManagers.toArray(x509KeyManager); if(sb!=null) { - access.log(Level.INIT, sb); + access.log(Level.INIT, sb); } } private void x509Info(StringBuilder sb, X509Certificate[] chain) { - if(chain!=null) { - int i=0; - for(X509Certificate x : chain) { - sb.append(" "); - sb.append(i++); - sb.append(')'); - sb.append("\n Subject: "); - sb.append(x.getSubjectDN()); - sb.append("\n Issuer : "); - sb.append(x.getIssuerDN()); - sb.append("\n Expires: "); - sb.append(x.getNotAfter()); - sb.append('\n'); - } - } + if(chain!=null) { + int i=0; + for(X509Certificate x : chain) { + sb.append(" "); + sb.append(i++); + sb.append(')'); + sb.append("\n Subject: "); + sb.append(x.getSubjectDN()); + sb.append("\n Issuer : "); + sb.append(x.getIssuerDN()); + sb.append("\n Expires: "); + sb.append(x.getNotAfter()); + sb.append('\n'); + } + } } protected void initializeTrustManager() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, CadiException { String trustStore = access.getProperty(Config.CADI_TRUSTSTORE, null); if(trustStore==null) { - return; + return; } else if(!new File(trustStore).exists()) { throw new CadiException(trustStore + " does not exist"); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiApiEnforcementFilter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiApiEnforcementFilter.java index e32b30d0..292f8e1c 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiApiEnforcementFilter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/CadiApiEnforcementFilter.java @@ -45,92 +45,92 @@ import org.onap.aaf.cadi.util.Split; * @author Instrumental(Jonathan) */ public class CadiApiEnforcementFilter implements Filter { - private String type; - private Map<String,List<String>> publicPaths; - private Access access; - - - public CadiApiEnforcementFilter(Access access, String enforce) throws ServletException { - this.access = access; - init(enforce); - } + private String type; + private Map<String,List<String>> publicPaths; + private Access access; + + + public CadiApiEnforcementFilter(Access access, String enforce) throws ServletException { + this.access = access; + init(enforce); + } - @Override - public void init(FilterConfig fc) throws ServletException { - init(fc.getInitParameter(Config.CADI_API_ENFORCEMENT)); + @Override + public void init(FilterConfig fc) throws ServletException { + init(fc.getInitParameter(Config.CADI_API_ENFORCEMENT)); // need the Context for Logging, instantiating ClassLoader, etc ServletContextAccess sca=new ServletContextAccess(fc); if (access==null) { access = sca; } - } - - private void init(final String ptypes) throws ServletException { - if(ptypes==null) { - throw new ServletException("CadiApiEnforcement requires " + Config.CADI_API_ENFORCEMENT + " property"); - } - String[] full = Split.splitTrim(';', ptypes); - if(full.length==0) { - throw new ServletException(Config.CADI_API_ENFORCEMENT + " property is empty"); - } - if(full.length>0) { - type=full[0]; - } - publicPaths = new TreeMap<String,List<String>>(); - if(full.length>1) { - for(int i=1;i<full.length;++i) { - String pubArray[] = Split.split(':', full[i]); - if(pubArray.length==2) { - List<String> ls = publicPaths.get(pubArray[0]); - if(ls==null) { - ls = new ArrayList<String>(); - publicPaths.put(pubArray[0], ls); - } - ls.add(pubArray[1]); - } - } - } - } + } + + private void init(final String ptypes) throws ServletException { + if(ptypes==null) { + throw new ServletException("CadiApiEnforcement requires " + Config.CADI_API_ENFORCEMENT + " property"); + } + String[] full = Split.splitTrim(';', ptypes); + if(full.length==0) { + throw new ServletException(Config.CADI_API_ENFORCEMENT + " property is empty"); + } + if(full.length>0) { + type=full[0]; + } + publicPaths = new TreeMap<String,List<String>>(); + if(full.length>1) { + for(int i=1;i<full.length;++i) { + String pubArray[] = Split.split(':', full[i]); + if(pubArray.length==2) { + List<String> ls = publicPaths.get(pubArray[0]); + if(ls==null) { + ls = new ArrayList<String>(); + publicPaths.put(pubArray[0], ls); + } + ls.add(pubArray[1]); + } + } + } + } - @Override - public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { - HttpServletRequest hreq = (HttpServletRequest)req; - final String meth = hreq.getMethod(); - String path = hreq.getContextPath()+hreq.getPathInfo(); - - if(path == null || path.isEmpty() || "null".equals(path)) - path = hreq.getRequestURI().substring(hreq.getContextPath().length()); - - List<String> list = publicPaths.get(meth); - if(list!=null) { - for( String p : publicPaths.get(meth)) { - if(path.startsWith(p)) { - access.printf(Level.INFO, "%s accessed public API %s %s\n", - hreq.getUserPrincipal().getName(), - meth, - path); - fc.doFilter(req, resp); - return; - } - } - } - if(hreq.isUserInRole(type + '|'+path+'|'+meth)) { - access.printf(Level.INFO, "%s is allowed access to %s %s\n", - hreq.getUserPrincipal().getName(), - meth, - path); - fc.doFilter(req, resp); - } else { - access.printf(Level.AUDIT, "%s is denied access to %s %s\n", - hreq.getUserPrincipal().getName(), - meth, - path); - } - } + @Override + public void doFilter(ServletRequest req, ServletResponse resp, FilterChain fc) throws IOException, ServletException { + HttpServletRequest hreq = (HttpServletRequest)req; + final String meth = hreq.getMethod(); + String path = hreq.getContextPath()+hreq.getPathInfo(); + + if(path == null || path.isEmpty() || "null".equals(path)) + path = hreq.getRequestURI().substring(hreq.getContextPath().length()); + + List<String> list = publicPaths.get(meth); + if(list!=null) { + for( String p : publicPaths.get(meth)) { + if(path.startsWith(p)) { + access.printf(Level.INFO, "%s accessed public API %s %s\n", + hreq.getUserPrincipal().getName(), + meth, + path); + fc.doFilter(req, resp); + return; + } + } + } + if(hreq.isUserInRole(type + '|'+path+'|'+meth)) { + access.printf(Level.INFO, "%s is allowed access to %s %s\n", + hreq.getUserPrincipal().getName(), + meth, + path); + fc.doFilter(req, resp); + } else { + access.printf(Level.AUDIT, "%s is denied access to %s %s\n", + hreq.getUserPrincipal().getName(), + meth, + path); + } + } - @Override - public void destroy() { - } + @Override + public void destroy() { + } } 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 01bf6f2e..50efe8b4 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 @@ -161,7 +161,7 @@ public class CadiFilter implements Filter { cf= (Class<Filter>) Class.forName("org.onap.aaf.cadi.oauth.OAuthFilter"); sideChain.add(cf.newInstance()); } catch (ClassNotFoundException e) { - access.log(Level.DEBUG, "OAuthFilter not enabled"); + access.log(Level.DEBUG, "OAuthFilter not enabled"); } } catch (Exception e) { access.log(Level.INIT, "AAFTrustChecker cannot be loaded",e.getMessage()); @@ -229,7 +229,7 @@ public class CadiFilter implements Filter { // Add API Enforcement Point String enforce = getter.get(Config.CADI_API_ENFORCEMENT, null, true); if(enforce!=null && enforce.length()>0) { - sideChain.add(new CadiApiEnforcementFilter(access,enforce)); + sideChain.add(new CadiApiEnforcementFilter(access,enforce)); } // Remove Getter getter = Get.NULL; @@ -304,11 +304,11 @@ public class CadiFilter implements Filter { if (pathExceptions!=null) { String pi = hreq.getPathInfo(); if (pi==null) { - // Attempt to get from URI only (Daniel Rose) + // Attempt to get from URI only (Daniel Rose) pi = hreq.getRequestURI().substring(hreq.getContextPath().length()); if(pi==null) { - // Nothing works. - return false; // JBoss sometimes leaves null + // Nothing works. + return false; // JBoss sometimes leaves null } } for (String pe : pathExceptions) { 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 5920a260..0a89af0c 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 @@ -56,12 +56,12 @@ import org.onap.aaf.cadi.util.UserChainManip; */ public class CadiHTTPManip { private static final String ACCESS_DENIED = "Access Denied"; - private static final String NO_TAF_WILL_AUTHORIZE = "No TAF will authorize"; - private static final String AUTHENTICATION_FAILURE = "Authentication Failure"; - private static final String AUTHENTICATING_VIA_REDIRECTION = "Authenticating via redirection"; - private static final String MSG_FMT = "user=%s,ip=%s:%d,msg=\"%s: %s\""; - private static final String AUTHENTICATED = "Authenticated"; - private static final String ACCESS_CADI_CONTROL = ".access|cadi|control"; + private static final String NO_TAF_WILL_AUTHORIZE = "No TAF will authorize"; + private static final String AUTHENTICATION_FAILURE = "Authentication Failure"; + private static final String AUTHENTICATING_VIA_REDIRECTION = "Authenticating via redirection"; + private static final String MSG_FMT = "user=%s,ip=%s:%d,msg=\"%s: %s\""; + private static final String AUTHENTICATED = "Authenticated"; + private static final String ACCESS_CADI_CONTROL = ".access|cadi|control"; private static final String METH = "OPTIONS"; private static final String CADI = "/cadi/"; private static final String CADI_CACHE_PRINT = "/cadi/cache/print"; @@ -127,38 +127,38 @@ public class CadiHTTPManip { switch(tresp.isAuthenticated()) { case IS_AUTHENTICATED: access.printf(Level.DEBUG,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), - hreq.getRemotePort(),AUTHENTICATED,tresp.desc()); + hreq.getRemotePort(),AUTHENTICATED,tresp.desc()); break; case TRY_AUTHENTICATING: switch (tresp.authenticate()) { case IS_AUTHENTICATED: - access.printf(Level.DEBUG,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), - hreq.getRemotePort(),AUTHENTICATED,tresp.desc()); + access.printf(Level.DEBUG,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), + hreq.getRemotePort(),AUTHENTICATED,tresp.desc()); break; case HTTP_REDIRECT_INVOKED: - access.printf(Level.DEBUG,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), - hreq.getRemotePort(),AUTHENTICATING_VIA_REDIRECTION,tresp.desc()); + access.printf(Level.DEBUG,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), + hreq.getRemotePort(),AUTHENTICATING_VIA_REDIRECTION,tresp.desc()); break; case NO_FURTHER_PROCESSING: access.printf(Level.AUDIT,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), - hreq.getRemotePort(),AUTHENTICATION_FAILURE,tresp.desc()); + hreq.getRemotePort(),AUTHENTICATION_FAILURE,tresp.desc()); hresp.sendError(403, tresp.desc()); // Forbidden break; default: - access.printf(Level.AUDIT,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), - hreq.getRemotePort(),NO_TAF_WILL_AUTHORIZE,tresp.desc()); + access.printf(Level.AUDIT,MSG_FMT,tresp.getTarget(),hreq.getRemoteAddr(), + hreq.getRemotePort(),NO_TAF_WILL_AUTHORIZE,tresp.desc()); hresp.sendError(403, tresp.desc()); // Forbidden } break; case NO_FURTHER_PROCESSING: access.printf(Level.AUDIT,MSG_FMT, tresp.getTarget(),hreq.getRemoteAddr(), - hreq.getRemotePort(),NO_TAF_WILL_AUTHORIZE,tresp.desc()); + hreq.getRemotePort(),NO_TAF_WILL_AUTHORIZE,tresp.desc()); hresp.sendError(403, ACCESS_DENIED); // FORBIDDEN break; default: - access.printf(Level.AUDIT,MSG_FMT, tresp.getTarget(),hreq.getRemoteAddr(), - hreq.getRemotePort(),NO_TAF_WILL_AUTHORIZE,tresp.desc()); + access.printf(Level.AUDIT,MSG_FMT, tresp.getTarget(),hreq.getRemoteAddr(), + hreq.getRemotePort(),NO_TAF_WILL_AUTHORIZE,tresp.desc()); hresp.sendError(403, ACCESS_DENIED); // FORBIDDEN } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapBathConverter.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapBathConverter.java index 36372eb3..8c616f4a 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapBathConverter.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/MapBathConverter.java @@ -59,7 +59,7 @@ import org.onap.aaf.cadi.util.CSV.Visitor; */ public class MapBathConverter { private static final String BASIC = "Basic "; - private final Map<String,String> map; + private final Map<String,String> map; /** * Create with colon separated name value pairs @@ -78,53 +78,53 @@ public class MapBathConverter { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); final Date now = new Date(); csv.visit(new Visitor() { - @Override - public void visit(List<String> row) throws CadiException { - if(row.size()<3) { - throw new CadiException("CSV file " + csv + " must have at least 2 Basic Auth columns and an Expiration Date(YYYY-MM-DD) in each row"); - } - try { - Date date = sdf.parse(row.get(2)); - String oldID = row.get(0); - String newID = row.get(1); - if(date.after(now)) { - if(!oldID.startsWith(BASIC) && newID.startsWith(BASIC)) { - throw new CadiException("CSV file " + csv + ": Uncredentialed ID " + idFromBasic(oldID,null) + - " may not transfer to credentialed ID " + idFromBasic(newID,null)); - } else { - map.put(oldID,newID); - access.printf(Level.INIT, "ID Conversion from %s to %s enabled", - idFromBasic(oldID,null), - idFromBasic(newID,null)); - } - } else { - access.printf(Level.INIT, "ID Conversion from %s to %s has expired.", - idFromBasic(oldID,null), - idFromBasic(newID,null)); - } - } catch (ParseException e) { - throw new CadiException("Cannot Parse Date: " + row.get(2)); - } catch (IOException e) { - throw new CadiException(e); - } - } - }); + @Override + public void visit(List<String> row) throws CadiException { + if(row.size()<3) { + throw new CadiException("CSV file " + csv + " must have at least 2 Basic Auth columns and an Expiration Date(YYYY-MM-DD) in each row"); + } + try { + Date date = sdf.parse(row.get(2)); + String oldID = row.get(0); + String newID = row.get(1); + if(date.after(now)) { + if(!oldID.startsWith(BASIC) && newID.startsWith(BASIC)) { + throw new CadiException("CSV file " + csv + ": Uncredentialed ID " + idFromBasic(oldID,null) + + " may not transfer to credentialed ID " + idFromBasic(newID,null)); + } else { + map.put(oldID,newID); + access.printf(Level.INIT, "ID Conversion from %s to %s enabled", + idFromBasic(oldID,null), + idFromBasic(newID,null)); + } + } else { + access.printf(Level.INIT, "ID Conversion from %s to %s has expired.", + idFromBasic(oldID,null), + idFromBasic(newID,null)); + } + } catch (ParseException e) { + throw new CadiException("Cannot Parse Date: " + row.get(2)); + } catch (IOException e) { + throw new CadiException(e); + } + } + }); } private static String idFromBasic(String bath, Holder<String> hpass) throws IOException, CadiException { - if(bath.startsWith(BASIC)) { - String cred = Symm.base64noSplit.decode(bath.substring(6)); - int colon = cred.indexOf(':'); - if(colon<0) { - throw new CadiException("Invalid Authentication Credential for " + cred); - } - if(hpass!=null) { - hpass.value = cred.substring(colon+1); - } - return cred.substring(0, colon); - } else { - return bath; - } + if(bath.startsWith(BASIC)) { + String cred = Symm.base64noSplit.decode(bath.substring(6)); + int colon = cred.indexOf(':'); + if(colon<0) { + throw new CadiException("Invalid Authentication Credential for " + cred); + } + if(hpass!=null) { + hpass.value = cred.substring(colon+1); + } + return cred.substring(0, colon); + } else { + return bath; + } } /** @@ -137,40 +137,40 @@ public class MapBathConverter { } public String convert(Access access, final String bath) { - String rv = map.get(bath); + String rv = map.get(bath); - String cred; - String tcred=null; - Holder<String> hpass=null; - try { - if(bath.startsWith(BASIC)) { - cred = idFromBasic(bath,(hpass=new Holder<String>())); - if(rv==null) { - rv = map.get(cred); - } - } else { - cred = bath; - } + String cred; + String tcred=null; + Holder<String> hpass=null; + try { + if(bath.startsWith(BASIC)) { + cred = idFromBasic(bath,(hpass=new Holder<String>())); + if(rv==null) { + rv = map.get(cred); + } + } else { + cred = bath; + } - if(rv==null) { - // Nothing here, just return original - rv = bath; - } else { - if(rv.startsWith(BASIC)) { - tcred = idFromBasic(rv,null); - } else { - if(hpass!=null) { - tcred = rv; - rv = BASIC + Symm.base64noSplit.encode(rv+':'+hpass.value); - } - } - if(tcred != null) { - access.printf(Level.AUDIT, "ID %s converted to %s",cred,tcred); - } - } - } catch (IOException | CadiException e) { - access.log(e,"Invalid Authorization"); - } - return rv==null?bath:rv; + if(rv==null) { + // Nothing here, just return original + rv = bath; + } else { + if(rv.startsWith(BASIC)) { + tcred = idFromBasic(rv,null); + } else { + if(hpass!=null) { + tcred = rv; + rv = BASIC + Symm.base64noSplit.encode(rv+':'+hpass.value); + } + } + if(tcred != null) { + access.printf(Level.AUDIT, "ID %s converted to %s",cred,tcred); + } + } + } catch (IOException | CadiException e) { + access.log(e,"Invalid Authorization"); + } + return rv==null?bath:rv; } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/SideChain.java b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/SideChain.java index 8283b4dd..18e76b96 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/filter/SideChain.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/filter/SideChain.java @@ -38,36 +38,36 @@ import javax.xml.ws.Holder; * */ public class SideChain { - private List<Filter> sideChain; - - public SideChain() { - sideChain = new ArrayList<Filter>(); - } - - public void add(Filter f) { - sideChain.add(f); - } - + private List<Filter> sideChain; + + public SideChain() { + sideChain = new ArrayList<Filter>(); + } + + public void add(Filter f) { + sideChain.add(f); + } + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException { - final Holder<Boolean> hbool = new Holder<Boolean>(Boolean.TRUE); - FilterChain truth = new FilterChain() { - @Override - public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { - hbool.value=Boolean.TRUE; - } - public String toString() { - return hbool.value.toString(); - } - }; - for(Filter f : sideChain) { - hbool.value=Boolean.FALSE; - f.doFilter(request, response, truth); - if(!hbool.value) { - return; - } - } - if(hbool.value) { - chain.doFilter(request, response); - } + final Holder<Boolean> hbool = new Holder<Boolean>(Boolean.TRUE); + FilterChain truth = new FilterChain() { + @Override + public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { + hbool.value=Boolean.TRUE; + } + public String toString() { + return hbool.value.toString(); + } + }; + for(Filter f : sideChain) { + hbool.value=Boolean.FALSE; + f.doFilter(request, response, truth); + if(!hbool.value) { + return; + } + } + if(hbool.value) { + chain.doFilter(request, response); + } } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java index 364a0728..f420f41f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/AbsTafResp.java @@ -127,14 +127,14 @@ public abstract class AbsTafResp implements TafResp { } /* (non-Javadoc) - * @see org.onap.aaf.cadi.taf.TafResp#getTarget() - */ - @Override - public String getTarget() { - return target; - } - - /** + * @see org.onap.aaf.cadi.taf.TafResp#getTarget() + */ + @Override + public String getTarget() { + return target; + } + + /** * getAccess() * * Get the Access object from the TAF, so that appropriate Logging, etc can be coordinated. diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java index fb66ec08..b3b7fb59 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/NullTafResp.java @@ -61,14 +61,14 @@ class NullTafResp implements TafResp { } /* (non-Javadoc) - * @see org.onap.aaf.cadi.taf.TafResp#getTarget() - */ - @Override - public String getTarget() { - return "unknown"; - } + * @see org.onap.aaf.cadi.taf.TafResp#getTarget() + */ + @Override + public String getTarget() { + return "unknown"; + } - public Access getAccess() { + public Access getAccess() { return Access.NULL; } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java index 3bc278e5..6bb57d36 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/PuntTafResp.java @@ -64,14 +64,14 @@ public class PuntTafResp implements TafResp { } /* (non-Javadoc) - * @see org.onap.aaf.cadi.taf.TafResp#getTarget() - */ - @Override - public String getTarget() { - return "punt"; - } + * @see org.onap.aaf.cadi.taf.TafResp#getTarget() + */ + @Override + public String getTarget() { + return "punt"; + } - public Access getAccess() { + public Access getAccess() { return NullTafResp.singleton().getAccess(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java index f397cbab..dee0ba07 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustNotTafResp.java @@ -63,14 +63,14 @@ public class TrustNotTafResp implements TafResp { } /* (non-Javadoc) - * @see org.onap.aaf.cadi.taf.TafResp#getTarget() - */ - @Override - public String getTarget() { - return delegate.getTarget(); - } + * @see org.onap.aaf.cadi.taf.TafResp#getTarget() + */ + @Override + public String getTarget() { + return delegate.getTarget(); + } - @Override + @Override public Access getAccess() { return delegate.getAccess(); } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java index 061d4e2f..2701c27a 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/taf/TrustTafResp.java @@ -65,14 +65,14 @@ public class TrustTafResp implements TafResp { } /* (non-Javadoc) - * @see org.onap.aaf.cadi.taf.TafResp#getTarget() - */ - @Override - public String getTarget() { - return delegate.getTarget(); - } + * @see org.onap.aaf.cadi.taf.TafResp#getTarget() + */ + @Override + public String getTarget() { + return delegate.getTarget(); + } - @Override + @Override public Access getAccess() { return delegate.getAccess(); } 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 dcd27d63..93360761 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 @@ -70,7 +70,7 @@ public class BasicHttpTaf implements HttpTaf { private Map<String,CredVal> rbacs = new TreeMap<>(); private boolean warn; private long timeToLive; - private MapBathConverter mapIds; + private MapBathConverter mapIds; public BasicHttpTaf(Access access, CredVal rbac, String realm, long timeToLive, boolean turnOnWarning) { this.access = access; @@ -80,13 +80,13 @@ public class BasicHttpTaf implements HttpTaf { this.timeToLive = timeToLive; String csvFile = access.getProperty(Config.CADI_BATH_CONVERT, null); if(csvFile==null) { - mapIds=null; + mapIds=null; } else { - try { - mapIds = new MapBathConverter(access, new CSV(access,csvFile)); - } catch (IOException | CadiException e) { - access.log(e,"Bath Map Conversion is not initialzed (non fatal)"); - } + try { + mapIds = new MapBathConverter(access, new CSV(access,csvFile)); + } catch (IOException | CadiException e) { + access.log(e,"Bath Map Conversion is not initialzed (non fatal)"); + } } } @@ -134,7 +134,7 @@ public class BasicHttpTaf implements HttpTaf { access.log(Level.WARN,"WARNING! BasicAuth has been used over an insecure channel"); } if(mapIds != null) { - authz = mapIds.convert(access, authz); + authz = mapIds.convert(access, authz); } try { CachedBasicPrincipal ba = new CachedBasicPrincipal(this,authz,realm,timeToLive); 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 5f5ff574..914c57b5 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 @@ -137,52 +137,52 @@ public class X509Taf implements HttpTaf { access.printf(Level.DEBUG,"Client Certificate found\n Subject '%s'\n Issuer '%s'",subject,issuer); if (cadiIssuers.contains(issuer)) { // avoiding extra object creation, since this is validated EVERY transaction with a Cert - int start = 0; - int end = 1; - int comma; - int length = subject.length(); - - compare: - while(start<length) { - while(Character.isWhitespace(subject.charAt(start))) { - if(++start>length) { - break compare; - } - } - comma = subject.indexOf(',',start); - if(comma<0) { - end = subject.length(); - } else { - end = comma<=0?0:comma-1; - } - while(Character.isWhitespace(subject.charAt(end))) { - if(--end < 0) { - break compare; - } - } - if(subject.regionMatches(start, "OU=", 0, 3) || - subject.regionMatches(start, "CN=", 0, 3)) { - int at = subject.indexOf('@', start); - if(at<end && at>=0) { + int start = 0; + int end = 1; + int comma; + int length = subject.length(); + + compare: + while(start<length) { + while(Character.isWhitespace(subject.charAt(start))) { + if(++start>length) { + break compare; + } + } + comma = subject.indexOf(',',start); + if(comma<0) { + end = subject.length(); + } else { + end = comma<=0?0:comma-1; + } + while(Character.isWhitespace(subject.charAt(end))) { + if(--end < 0) { + break compare; + } + } + if(subject.regionMatches(start, "OU=", 0, 3) || + subject.regionMatches(start, "CN=", 0, 3)) { + int at = subject.indexOf('@', start); + if(at<end && at>=0) { String[] sa = Split.splitTrim(':', subject, start+3,end+1); 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); } else { - access.printf(Level.DEBUG,"Certificate is not for environment '%s'",env); - break; + access.printf(Level.DEBUG,"Certificate is not for environment '%s'",env); + break; } - } - } - start = comma+1; - } - access.log(Level.DEBUG,"Certificate is not acceptable for Authentication"); + } + } + start = comma+1; + } + access.log(Level.DEBUG,"Certificate is not acceptable for Authentication"); } else { - access.log(Level.DEBUG,"Issuer is not trusted for Authentication"); + access.log(Level.DEBUG,"Issuer is not trusted for Authentication"); } } else { - access.log(Level.DEBUG,"There is no client certificate on the transaction"); + access.log(Level.DEBUG,"There is no client certificate on the transaction"); } @@ -266,7 +266,7 @@ public class X509Taf implements HttpTaf { // if Principal is found, check for "AS_USER" and whether this entity is trusted to declare if (prin!=null) { - // Note: Tag for Certs is Fingerprint, but that takes computation... leaving off + // Note: Tag for Certs is Fingerprint, but that takes computation... leaving off return new X509HttpTafResp( access, prin, diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/CSV.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/CSV.java index 35d85b9a..fbaa4a5a 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/CSV.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/CSV.java @@ -41,240 +41,240 @@ import org.onap.aaf.cadi.CadiException; * */ public class CSV { - private File csv; - private Access access; - private boolean processAll; - private char delimiter = ','; - - public CSV(Access access, File file) { - this.access = access; - csv = file; - processAll = false; - } - - public CSV(Access access, String csvFilename) { - this.access = access; - csv = new File(csvFilename); - processAll = false; - } - - public CSV setDelimiter(char delimiter) { - this.delimiter = delimiter; - return this; - } - - public String name() { - return csv.getName(); - } + private File csv; + private Access access; + private boolean processAll; + private char delimiter = ','; + + public CSV(Access access, File file) { + this.access = access; + csv = file; + processAll = false; + } + + public CSV(Access access, String csvFilename) { + this.access = access; + csv = new File(csvFilename); + processAll = false; + } + + public CSV setDelimiter(char delimiter) { + this.delimiter = delimiter; + return this; + } + + public String name() { + return csv.getName(); + } - public CSV processAll() { - processAll = true; - return this; - } - /* - * Create your code to accept the List<String> row. - * - * Your code may keep the List... CSV does not hold onto it. - * - * @author Instrumental(Jonathan) - * - */ - public interface Visitor { - void visit(List<String> row) throws IOException, CadiException; - } - - public void visit(Visitor visitor) throws IOException, CadiException { - BufferedReader br = new BufferedReader(new FileReader(csv)); - try { - String line; - StringBuilder sb = new StringBuilder(); - while((line = br.readLine())!=null) { - line=line.trim(); - if(!line.startsWith("#") && line.length()>0) { -// System.out.println(line); uncomment to debug - List<String> row = new ArrayList<>(); - boolean quotes=false; - boolean escape=false; - char c = 0; - for(int i=0;i<line.length();++i) { - switch(c=line.charAt(i)) { - case '"': - if(quotes) { - if(i<line.length()-1) { // may look ahead - if('"' == line.charAt(i+1)) { - sb.append(c); - ++i; - } else { - quotes = false; - } - } else { - quotes=false; - } - } else { - quotes=true; - } - break; - case '\\': - if(escape) { - sb.append(c); - escape = false; - } else { - escape = true; - } - break; - case 'n': - if(escape) { - sb.append("\\n"); - escape=false; - } else { - sb.append(c); - } - break; - default: - if(delimiter==c) { - if(quotes) { - sb.append(c); - } else { - row.add(sb.toString()); - sb.setLength(0); - } - } else { - sb.append(c); - } - } - } - if(sb.length()>0 || c==',') { - row.add(sb.toString()); - sb.setLength(0); - } - try { - visitor.visit(row); - } catch (CadiException e) { - if(processAll) { - access.log(Level.ERROR,e); - } else { - throw e; - } - } - } - } - } finally { - br.close(); - } - } - - public Writer writer() throws FileNotFoundException { - return new Writer(false); - } + public CSV processAll() { + processAll = true; + return this; + } + /* + * Create your code to accept the List<String> row. + * + * Your code may keep the List... CSV does not hold onto it. + * + * @author Instrumental(Jonathan) + * + */ + public interface Visitor { + void visit(List<String> row) throws IOException, CadiException; + } + + public void visit(Visitor visitor) throws IOException, CadiException { + BufferedReader br = new BufferedReader(new FileReader(csv)); + try { + String line; + StringBuilder sb = new StringBuilder(); + while((line = br.readLine())!=null) { + line=line.trim(); + if(!line.startsWith("#") && line.length()>0) { +// System.out.println(line); uncomment to debug + List<String> row = new ArrayList<>(); + boolean quotes=false; + boolean escape=false; + char c = 0; + for(int i=0;i<line.length();++i) { + switch(c=line.charAt(i)) { + case '"': + if(quotes) { + if(i<line.length()-1) { // may look ahead + if('"' == line.charAt(i+1)) { + sb.append(c); + ++i; + } else { + quotes = false; + } + } else { + quotes=false; + } + } else { + quotes=true; + } + break; + case '\\': + if(escape) { + sb.append(c); + escape = false; + } else { + escape = true; + } + break; + case 'n': + if(escape) { + sb.append("\\n"); + escape=false; + } else { + sb.append(c); + } + break; + default: + if(delimiter==c) { + if(quotes) { + sb.append(c); + } else { + row.add(sb.toString()); + sb.setLength(0); + } + } else { + sb.append(c); + } + } + } + if(sb.length()>0 || c==',') { + row.add(sb.toString()); + sb.setLength(0); + } + try { + visitor.visit(row); + } catch (CadiException e) { + if(processAll) { + access.log(Level.ERROR,e); + } else { + throw e; + } + } + } + } + } finally { + br.close(); + } + } + + public Writer writer() throws FileNotFoundException { + return new Writer(false); + } - public Writer writer(boolean append) throws FileNotFoundException { - return new Writer(append); - } + public Writer writer(boolean append) throws FileNotFoundException { + return new Writer(append); + } - public interface RowSetter { - public void row(Object ... objs); - } - - public static class Saver implements RowSetter { - List<String> ls= new ArrayList<>(); - - @Override - public void row(Object ... objs) { - if(objs.length>0) { - for(Object o : objs) { - if(o != null) { - if(o instanceof String[]) { - for(String str : (String[])o) { - ls.add(str); - } - } else { - ls.add(o.toString()); - } - } - } - } - } - - public List<String> asList() { - List<String> rv = ls; - ls = new ArrayList<>(); - return rv; - } - } + public interface RowSetter { + public void row(Object ... objs); + } + + public static class Saver implements RowSetter { + List<String> ls= new ArrayList<>(); + + @Override + public void row(Object ... objs) { + if(objs.length>0) { + for(Object o : objs) { + if(o != null) { + if(o instanceof String[]) { + for(String str : (String[])o) { + ls.add(str); + } + } else { + ls.add(o.toString()); + } + } + } + } + } + + public List<String> asList() { + List<String> rv = ls; + ls = new ArrayList<>(); + return rv; + } + } - public class Writer implements RowSetter { - private PrintStream ps; - private Writer(final boolean append) throws FileNotFoundException { - ps = new PrintStream(new FileOutputStream(csv,append)); - } - - @Override - public void row(Object ... objs) { - if(objs.length>0) { - boolean first = true; - for(Object o : objs) { - if(first) { - first = false; - } else { - ps.append(delimiter); - } - if(o == null) { - } else if(o instanceof String[]) { - for(String str : (String[])o) { - print(str); - } - } else { - print(o.toString()); - } - } - ps.println(); - } - } - - private void print(String s) { - boolean quote = s.matches(".*[,|\"].*"); - if(quote) { - ps.append('"'); - ps.print(s.replace("\"", "\"\"") - .replace("'", "''") - .replace("\\", "\\\\")); - ps.append('"'); - } else { - ps.append(s); - } + public class Writer implements RowSetter { + private PrintStream ps; + private Writer(final boolean append) throws FileNotFoundException { + ps = new PrintStream(new FileOutputStream(csv,append)); + } + + @Override + public void row(Object ... objs) { + if(objs.length>0) { + boolean first = true; + for(Object o : objs) { + if(first) { + first = false; + } else { + ps.append(delimiter); + } + if(o == null) { + } else if(o instanceof String[]) { + for(String str : (String[])o) { + print(str); + } + } else { + print(o.toString()); + } + } + ps.println(); + } + } + + private void print(String s) { + boolean quote = s.matches(".*[,|\"].*"); + if(quote) { + ps.append('"'); + ps.print(s.replace("\"", "\"\"") + .replace("'", "''") + .replace("\\", "\\\\")); + ps.append('"'); + } else { + ps.append(s); + } - - } - /** - * Note: CSV files do not actually support Comments as a standard, but it is useful - * @param comment - */ - public void comment(String comment, Object ... objs) { - ps.print("# "); - ps.printf(comment,objs); - ps.println(); - } - - public void flush() { - ps.flush(); - } - - public void close() { - flush(); - ps.close(); - } - - public String toString() { - return csv.getAbsolutePath(); - } - } + + } + /** + * Note: CSV files do not actually support Comments as a standard, but it is useful + * @param comment + */ + public void comment(String comment, Object ... objs) { + ps.print("# "); + ps.printf(comment,objs); + ps.println(); + } + + public void flush() { + ps.flush(); + } + + public void close() { + flush(); + ps.close(); + } + + public String toString() { + return csv.getAbsolutePath(); + } + } - public void delete() { - csv.delete(); - } - - public String toString() { - return csv.getAbsolutePath(); - } + public void delete() { + csv.delete(); + } + + public String toString() { + return csv.getAbsolutePath(); + } } diff --git a/cadi/core/src/main/java/org/onap/aaf/cadi/util/FixURIinfo.java b/cadi/core/src/main/java/org/onap/aaf/cadi/util/FixURIinfo.java index b4085361..f2c6be6f 100644 --- a/cadi/core/src/main/java/org/onap/aaf/cadi/util/FixURIinfo.java +++ b/cadi/core/src/main/java/org/onap/aaf/cadi/util/FixURIinfo.java @@ -30,37 +30,37 @@ import java.net.URI; * */ public class FixURIinfo { - private String auth; - private String host; - private int port; - - public FixURIinfo(URI uri) { - auth = uri.getAuthority(); - host = uri.getHost(); - if(host==null || (auth!=null && auth.startsWith(host))) { - if(auth!=null) { - int colon = auth.indexOf(':'); - if(colon >= 0 ) { - host = auth.substring(0, colon); - port = Integer.parseInt(auth.substring(colon+1)); - } else { - host = auth; - port = uri.getPort(); - } - auth=null; - } - } - } - - public String getHost() { - return host; - } - - public int getPort() { - return port; - } + private String auth; + private String host; + private int port; + + public FixURIinfo(URI uri) { + auth = uri.getAuthority(); + host = uri.getHost(); + if(host==null || (auth!=null && auth.startsWith(host))) { + if(auth!=null) { + int colon = auth.indexOf(':'); + if(colon >= 0 ) { + host = auth.substring(0, colon); + port = Integer.parseInt(auth.substring(colon+1)); + } else { + host = auth; + port = uri.getPort(); + } + auth=null; + } + } + } + + public String getHost() { + return host; + } + + public int getPort() { + return port; + } - public String getUserInfo() { - return auth; - } + public String getUserInfo() { + return auth; + } } 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 c6f8bd0a..4f41629d 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 @@ -31,93 +31,93 @@ package org.onap.aaf.cadi.util; */ public class Split { - private static final String[] EMPTY = new String[0]; + private static final String[] EMPTY = new String[0]; - public static String[] split(char c, String value) { - if (value==null) { - return EMPTY; - } + public static String[] split(char c, String value) { + if (value==null) { + return EMPTY; + } - return split(c,value,0,value.length()); - } + return split(c,value,0,value.length()); + } - public static String[] split(char c, String value, int start, int end) { - if (value==null) { - return EMPTY; - } + public static String[] split(char c, String value, int start, int end) { + if (value==null) { + return EMPTY; + } - // 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); - String[] rv = new String[count]; - 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)) { - rv[++count]=value.substring(last,idx); - last = ++idx; - } - rv[++count]=value.substring(last,end); - } - return rv; - } + // 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); + String[] rv = new String[count]; + 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)) { + rv[++count]=value.substring(last,idx); + last = ++idx; + } + rv[++count]=value.substring(last,end); + } + return rv; + } - public static String[] splitTrim(char c, String value, int start, int end) { - if (value==null) { - return EMPTY; - } + public static String[] splitTrim(char c, String value, int start, int end) { + if (value==null) { + return EMPTY; + } - // 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); - String[] rv = new String[count]; - if (count==1) { - rv[0]=value.substring(start,end).trim(); - } else { - int last=start; - count=-1; - for (idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,idx)) { - rv[++count]=value.substring(last,idx).trim(); - last = ++idx; - } - rv[++count]=value.substring(last,end).trim(); - } - return rv; - } + // 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); + String[] rv = new String[count]; + if (count==1) { + rv[0]=value.substring(start,end).trim(); + } else { + int last=start; + count=-1; + for (idx=value.indexOf(c,start);idx>=0 && idx<end;idx=value.indexOf(c,idx)) { + rv[++count]=value.substring(last,idx).trim(); + last = ++idx; + } + rv[++count]=value.substring(last,end).trim(); + } + return rv; + } - public static String[] splitTrim(char c, String value) { - if (value==null) { - return EMPTY; - } - return splitTrim(c,value,0,value.length()); - } + public static String[] splitTrim(char c, String value) { + if (value==null) { + return EMPTY; + } + return splitTrim(c,value,0,value.length()); + } - public static String[] splitTrim(char c, String value, int size) { - if (value==null) { - return EMPTY; - } + public static String[] splitTrim(char c, String value, int size) { + if (value==null) { + return EMPTY; + } - int idx; - String[] rv = new String[size]; - 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)) { - rv[++count]=value.substring(last,idx).trim(); - last = ++idx; - } - if (idx>0) { - rv[++count]=value.substring(last,idx).trim(); - } else { - rv[++count]=value.substring(last).trim(); - } - } - return rv; - } + int idx; + String[] rv = new String[size]; + 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)) { + rv[++count]=value.substring(last,idx).trim(); + last = ++idx; + } + if (idx>0) { + rv[++count]=value.substring(last,idx).trim(); + } else { + rv[++count]=value.substring(last).trim(); + } + } + return rv; + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MapBathConverter.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MapBathConverter.java index d9a5a0eb..2be51ece 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MapBathConverter.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_MapBathConverter.java @@ -50,199 +50,199 @@ import junit.framework.Assert; * */ public class JU_MapBathConverter { - private static final String NEW_USER_SOMETHING_ORG = "NEW_USER@Something.org"; - private static final String OLD_ID = "OLD_ID"; - private static final String SHARED_PASS = "SHARED_PASS"; - private static CSV csv; - private static ArrayList<String> expected; - private static final Access access = new PropAccess(); + private static final String NEW_USER_SOMETHING_ORG = "NEW_USER@Something.org"; + private static final String OLD_ID = "OLD_ID"; + private static final String SHARED_PASS = "SHARED_PASS"; + private static CSV csv; + private static ArrayList<String> expected; + private static final Access access = new PropAccess(); private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); - @BeforeClass - public static void createFile() throws IOException { - // Note, you cate a "MapBathConverter" by access to a File. - // We will create that file now. Local is fine. - csv = new CSV(access,"JU_MapBathConverter.csv"); - } - - @BeforeClass - public static void beforeClass() { - expected = new ArrayList<>(); - } - - @Before - public void before() { - expected.clear(); - } - - @Test - public void test() throws IOException, CadiException { - CSV.Writer cw = csv.writer(); - GregorianCalendar gc = new GregorianCalendar(); - gc.add(GregorianCalendar.MONTH, 6); - try { - try { - // CSV can simply be OLD ID and NEW, no passwords - cw.row(exp(OLD_ID), exp(NEW_USER_SOMETHING_ORG),sdf.format(gc.getTime())); - - // Style 1 - Incoming ID/pass, create new cred with NweID and same Pass - cw.row(exp(bath(OLD_ID,SHARED_PASS)), exp(NEW_USER_SOMETHING_ORG),sdf.format(gc.getTime())); - // the response should be Basic with NEW_ID and OLD_PASS - - // Style 2 - cw.row(exp(bath(OLD_ID,"OLD_PASS")), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS")),sdf.format(gc.getTime())); - - } finally { - cw.close(); - } - - final Iterator<String> exp = expected.iterator(); - csv.visit(new Visitor() { - @Override - public void visit(List<String> row) { - int i=0; - for(String s : row) { - switch(i++) { - case 0: - case 1: - Assert.assertEquals(exp.next(), s); - break; - case 2: - try { - Date.valueOf(s); - } catch (Exception e) { - Assert.assertTrue("Last entry should be a date",false); - } - break; - default: - Assert.fail("There should only be 3 columns in this test case."); - } - } - } - }); - - MapBathConverter mbc = new MapBathConverter(access, csv); - - // Check no lookup just returns the same - Assert.assertEquals("NonKey", "NonKey"); // if not in map, expect same value - - Iterator<String> exp1 = expected.iterator(); - // there's no passwords in CSV - String old = exp1.next(); - String nw = exp1.next(); - Assert.assertEquals(nw, mbc.convert(access,old)); - - Assert.assertEquals(bath(NEW_USER_SOMETHING_ORG,SHARED_PASS), mbc.convert(access,bath(OLD_ID,SHARED_PASS))); - - // Style 1 (new cred, old password) - old = exp1.next(); - nw = bath(exp1.next(),SHARED_PASS); - Assert.assertEquals(nw, mbc.convert(access,old)); - - // Style 2 - old = exp1.next(); - nw = exp1.next(); - Assert.assertEquals(nw, mbc.convert(access,old)); - - } finally { - csv.delete(); - } - } - - @Test - public void testInsecureRole() throws IOException { - CSV.Writer cw = csv.writer(); - GregorianCalendar gc = new GregorianCalendar(); - gc.add(GregorianCalendar.MONTH, 6); - try { - try { - // Invalid Scenario - Non Authenticated ID to authenticated User - cw.row(exp(OLD_ID), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS")),sdf.format(gc.getTime())); - - } finally { - cw.close(); - } - - try { - new MapBathConverter(access, csv); - Assert.fail("Invalid Data should throw Exception"); - } catch (CadiException e) { - Assert.assertTrue("Invalid Data should throw Exception",true); - } - - } finally { - csv.delete(); - } - } - - @Test - public void testTooFewColumns() throws IOException, CadiException { - CSV.Writer cw = csv.writer(); - try { - try { - cw.row(exp(bath(OLD_ID,"OLD_PASS")), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS"))); - } finally { - cw.close(); - } - - try { - new MapBathConverter(access, csv); - Assert.fail("file with too few rows should throw exception"); - } catch(CadiException | IOException e) { - Assert.assertTrue("Correctly thrown Exception",true); - } - } finally { - csv.delete(); - } - } - - @Test - public void testNoFile() { - try { - new MapBathConverter(access, new CSV(access,"Bogus")); - Assert.fail("Non Existent File should throw exception"); - } catch(CadiException | IOException e) { - Assert.assertTrue("Correctly thrown Exception",true); - } - } - - @Test - public void testBadRows() throws IOException { - try { - Writer cw = csv.writer(); - try { - cw.row("Single Column"); - } finally { - cw.close(); - } - - try { - new MapBathConverter(access,csv); - Assert.fail("Non Existent File should throw exception"); - } catch(CadiException | IOException e) { - Assert.assertTrue("Correctly thrown Exception",true); - } - } finally { - csv.delete(); - } - - // Check for deletion - Assert.assertFalse(csv.toString() + "should have been deleted",new File(csv.toString()).exists()); - } - - private String bath(String user, String password) throws IOException { - StringBuilder sb = new StringBuilder(user); - sb.append(':'); - sb.append(password); - byte[] encoded = Symm.base64noSplit.encode(sb.toString().getBytes()); - sb.setLength(0); - sb.append("Basic "); - sb.append(new String(encoded)); - return sb.toString(); - } - - private String exp(String s) { - expected.add(s); - return s; - } + @BeforeClass + public static void createFile() throws IOException { + // Note, you cate a "MapBathConverter" by access to a File. + // We will create that file now. Local is fine. + csv = new CSV(access,"JU_MapBathConverter.csv"); + } + + @BeforeClass + public static void beforeClass() { + expected = new ArrayList<>(); + } + + @Before + public void before() { + expected.clear(); + } + + @Test + public void test() throws IOException, CadiException { + CSV.Writer cw = csv.writer(); + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.MONTH, 6); + try { + try { + // CSV can simply be OLD ID and NEW, no passwords + cw.row(exp(OLD_ID), exp(NEW_USER_SOMETHING_ORG),sdf.format(gc.getTime())); + + // Style 1 - Incoming ID/pass, create new cred with NweID and same Pass + cw.row(exp(bath(OLD_ID,SHARED_PASS)), exp(NEW_USER_SOMETHING_ORG),sdf.format(gc.getTime())); + // the response should be Basic with NEW_ID and OLD_PASS + + // Style 2 + cw.row(exp(bath(OLD_ID,"OLD_PASS")), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS")),sdf.format(gc.getTime())); + + } finally { + cw.close(); + } + + final Iterator<String> exp = expected.iterator(); + csv.visit(new Visitor() { + @Override + public void visit(List<String> row) { + int i=0; + for(String s : row) { + switch(i++) { + case 0: + case 1: + Assert.assertEquals(exp.next(), s); + break; + case 2: + try { + Date.valueOf(s); + } catch (Exception e) { + Assert.assertTrue("Last entry should be a date",false); + } + break; + default: + Assert.fail("There should only be 3 columns in this test case."); + } + } + } + }); + + MapBathConverter mbc = new MapBathConverter(access, csv); + + // Check no lookup just returns the same + Assert.assertEquals("NonKey", "NonKey"); // if not in map, expect same value + + Iterator<String> exp1 = expected.iterator(); + // there's no passwords in CSV + String old = exp1.next(); + String nw = exp1.next(); + Assert.assertEquals(nw, mbc.convert(access,old)); + + Assert.assertEquals(bath(NEW_USER_SOMETHING_ORG,SHARED_PASS), mbc.convert(access,bath(OLD_ID,SHARED_PASS))); + + // Style 1 (new cred, old password) + old = exp1.next(); + nw = bath(exp1.next(),SHARED_PASS); + Assert.assertEquals(nw, mbc.convert(access,old)); + + // Style 2 + old = exp1.next(); + nw = exp1.next(); + Assert.assertEquals(nw, mbc.convert(access,old)); + + } finally { + csv.delete(); + } + } + + @Test + public void testInsecureRole() throws IOException { + CSV.Writer cw = csv.writer(); + GregorianCalendar gc = new GregorianCalendar(); + gc.add(GregorianCalendar.MONTH, 6); + try { + try { + // Invalid Scenario - Non Authenticated ID to authenticated User + cw.row(exp(OLD_ID), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS")),sdf.format(gc.getTime())); + + } finally { + cw.close(); + } + + try { + new MapBathConverter(access, csv); + Assert.fail("Invalid Data should throw Exception"); + } catch (CadiException e) { + Assert.assertTrue("Invalid Data should throw Exception",true); + } + + } finally { + csv.delete(); + } + } + + @Test + public void testTooFewColumns() throws IOException, CadiException { + CSV.Writer cw = csv.writer(); + try { + try { + cw.row(exp(bath(OLD_ID,"OLD_PASS")), exp(bath(NEW_USER_SOMETHING_ORG,"NEW_PASS"))); + } finally { + cw.close(); + } + + try { + new MapBathConverter(access, csv); + Assert.fail("file with too few rows should throw exception"); + } catch(CadiException | IOException e) { + Assert.assertTrue("Correctly thrown Exception",true); + } + } finally { + csv.delete(); + } + } + + @Test + public void testNoFile() { + try { + new MapBathConverter(access, new CSV(access,"Bogus")); + Assert.fail("Non Existent File should throw exception"); + } catch(CadiException | IOException e) { + Assert.assertTrue("Correctly thrown Exception",true); + } + } + + @Test + public void testBadRows() throws IOException { + try { + Writer cw = csv.writer(); + try { + cw.row("Single Column"); + } finally { + cw.close(); + } + + try { + new MapBathConverter(access,csv); + Assert.fail("Non Existent File should throw exception"); + } catch(CadiException | IOException e) { + Assert.assertTrue("Correctly thrown Exception",true); + } + } finally { + csv.delete(); + } + + // Check for deletion + Assert.assertFalse(csv.toString() + "should have been deleted",new File(csv.toString()).exists()); + } + + private String bath(String user, String password) throws IOException { + StringBuilder sb = new StringBuilder(user); + sb.append(':'); + sb.append(password); + byte[] encoded = Symm.base64noSplit.encode(sb.toString().getBytes()); + sb.setLength(0); + sb.append("Basic "); + sb.append(new String(encoded)); + return sb.toString(); + } + + private String exp(String s) { + expected.add(s); + return s; + } } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_RegistrationPropHolder.java b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_RegistrationPropHolder.java index 68235e1a..1fe6a753 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_RegistrationPropHolder.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/config/test/JU_RegistrationPropHolder.java @@ -33,117 +33,117 @@ import org.onap.aaf.cadi.config.RegistrationPropHolder; public class JU_RegistrationPropHolder { - @Test - public void testBlank() { - PropAccess pa = new PropAccess(); - RegistrationPropHolder rph; - int ju_port = 20; - try { - //////////////// - // Check Required Properties - //////////////// - try { - rph = new RegistrationPropHolder(pa,20); - } catch (CadiException e) { - Assert.assertEquals( - "\ncadi_latitude must be defined." + - "\ncadi_longitude must be defined.",e.getMessage()); - } - - try { - pa.setProperty(Config.CADI_LATITUDE, "32.7"); - rph = new RegistrationPropHolder(pa,20); - } catch (CadiException e) { - Assert.assertEquals( - "\ncadi_longitude must be defined.",e.getMessage()); - } - - pa.setProperty(Config.CADI_LONGITUDE, "-72.0"); - rph = new RegistrationPropHolder(pa,ju_port); - - //////////////// - // Validate Default Properties - //////////////// - for(String dot_le : new String[] {"",".helm"}) { - assertEquals(rph.hostname,rph.default_fqdn); - assertEquals("",rph.lcontainer); - assertEquals(rph.hostname,rph.public_fqdn); - assertEquals(ju_port,rph.getEntryPort(dot_le)); - assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); - } + @Test + public void testBlank() { + PropAccess pa = new PropAccess(); + RegistrationPropHolder rph; + int ju_port = 20; + try { + //////////////// + // Check Required Properties + //////////////// + try { + rph = new RegistrationPropHolder(pa,20); + } catch (CadiException e) { + Assert.assertEquals( + "\ncadi_latitude must be defined." + + "\ncadi_longitude must be defined.",e.getMessage()); + } + + try { + pa.setProperty(Config.CADI_LATITUDE, "32.7"); + rph = new RegistrationPropHolder(pa,20); + } catch (CadiException e) { + Assert.assertEquals( + "\ncadi_longitude must be defined.",e.getMessage()); + } + + pa.setProperty(Config.CADI_LONGITUDE, "-72.0"); + rph = new RegistrationPropHolder(pa,ju_port); + + //////////////// + // Validate Default Properties + //////////////// + for(String dot_le : new String[] {"",".helm"}) { + assertEquals(rph.hostname,rph.default_fqdn); + assertEquals("",rph.lcontainer); + assertEquals(rph.hostname,rph.public_fqdn); + assertEquals(ju_port,rph.getEntryPort(dot_le)); + assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); + } - String ns = "myns"; - pa.setProperty(Config.AAF_LOCATOR_APP_NS, ns); - for(String dot_le : new String[] {"",".helm"}) { - assertEquals(rph.hostname,rph.default_fqdn); - assertEquals("",rph.lcontainer); - assertEquals(rph.hostname,rph.public_fqdn); - assertEquals(ju_port,rph.getEntryPort(dot_le)); - assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); - } + String ns = "myns"; + pa.setProperty(Config.AAF_LOCATOR_APP_NS, ns); + for(String dot_le : new String[] {"",".helm"}) { + assertEquals(rph.hostname,rph.default_fqdn); + assertEquals("",rph.lcontainer); + assertEquals(rph.hostname,rph.public_fqdn); + assertEquals(ju_port,rph.getEntryPort(dot_le)); + assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); + } - String ns2 = "onap"; - pa.setProperty(Config.AAF_LOCATOR_APP_NS+".helm", ns2); - for(String dot_le : new String[] {"",".helm"}) { - assertEquals(rph.hostname,rph.default_fqdn); - assertEquals("",rph.lcontainer); - assertEquals(rph.hostname,rph.public_fqdn); - assertEquals(ju_port,rph.getEntryPort(dot_le)); - assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); - } + String ns2 = "onap"; + pa.setProperty(Config.AAF_LOCATOR_APP_NS+".helm", ns2); + for(String dot_le : new String[] {"",".helm"}) { + assertEquals(rph.hostname,rph.default_fqdn); + assertEquals("",rph.lcontainer); + assertEquals(rph.hostname,rph.public_fqdn); + assertEquals(ju_port,rph.getEntryPort(dot_le)); + assertEquals(rph.hostname,rph.getEntryFQDN("",dot_le)); + } - //////////////// - // Validate Public Host and Port settings - //////////////// - String public_hostname = "com.public.hostname"; - int public_port = 999; - pa.setProperty(Config.AAF_LOCATOR_PUBLIC_FQDN, public_hostname); - pa.setProperty(Config.AAF_LOCATOR_PUBLIC_PORT,Integer.toString(public_port)); - RegistrationPropHolder pubRPH = new RegistrationPropHolder(pa,ju_port); - assertEquals(public_hostname,pubRPH.public_fqdn); - assertEquals(public_port,pubRPH.getEntryPort("")); + //////////////// + // Validate Public Host and Port settings + //////////////// + String public_hostname = "com.public.hostname"; + int public_port = 999; + pa.setProperty(Config.AAF_LOCATOR_PUBLIC_FQDN, public_hostname); + pa.setProperty(Config.AAF_LOCATOR_PUBLIC_PORT,Integer.toString(public_port)); + RegistrationPropHolder pubRPH = new RegistrationPropHolder(pa,ju_port); + assertEquals(public_hostname,pubRPH.public_fqdn); + assertEquals(public_port,pubRPH.getEntryPort("")); - final String url = "https://aaf.osaaf.org:8095/org.osaaf.aaf.service:2.1"; - String name="theName"; - assertEquals(url,rph.replacements(getClass().getSimpleName(),url, name, "")); - - String alu = "aaf.osaaf.org:8095"; - String curl = url.replace(alu, Config.AAF_LOCATE_URL_TAG); - pa.setProperty(Config.AAF_LOCATE_URL,"https://"+alu); - assertEquals(url.replace("8095","8095/locate"),rph.replacements(getClass().getSimpleName(),curl, name, "")); - - String root_ns = "org.osaaf.aaf"; - curl = url.replace(root_ns, "AAF_NS"); - pa.setProperty(Config.AAF_ROOT_NS,root_ns); - assertEquals(url,rph.replacements(getClass().getSimpleName(),curl, name, "")); - - curl = url.replace(root_ns, "%AAF_NS"); - pa.setProperty(Config.AAF_ROOT_NS,root_ns); - assertEquals(url,rph.replacements(getClass().getSimpleName(),curl, name, "")); - - final String fqdn = "%C.%CNS.%NS.%N"; - String target = "myns.theName"; - assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, "")); + final String url = "https://aaf.osaaf.org:8095/org.osaaf.aaf.service:2.1"; + String name="theName"; + assertEquals(url,rph.replacements(getClass().getSimpleName(),url, name, "")); + + String alu = "aaf.osaaf.org:8095"; + String curl = url.replace(alu, Config.AAF_LOCATE_URL_TAG); + pa.setProperty(Config.AAF_LOCATE_URL,"https://"+alu); + assertEquals(url.replace("8095","8095/locate"),rph.replacements(getClass().getSimpleName(),curl, name, "")); + + String root_ns = "org.osaaf.aaf"; + curl = url.replace(root_ns, "AAF_NS"); + pa.setProperty(Config.AAF_ROOT_NS,root_ns); + assertEquals(url,rph.replacements(getClass().getSimpleName(),curl, name, "")); + + curl = url.replace(root_ns, "%AAF_NS"); + pa.setProperty(Config.AAF_ROOT_NS,root_ns); + assertEquals(url,rph.replacements(getClass().getSimpleName(),curl, name, "")); + + final String fqdn = "%C.%CNS.%NS.%N"; + String target = "myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, "")); - pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS+".hello", "mycontns"); - target = "mycontns.myns.theName"; - assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, ".hello")); - - pa.setProperty(Config.AAF_LOCATOR_CONTAINER+".hello","helloC"); - target = "helloC.mycontns.myns.theName"; - assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, ".hello")); - - pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS,"c_ns"); - target = "c_ns.myns.theName"; - assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, "")); + pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS+".hello", "mycontns"); + target = "mycontns.myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, ".hello")); + + pa.setProperty(Config.AAF_LOCATOR_CONTAINER+".hello","helloC"); + target = "helloC.mycontns.myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, ".hello")); + + pa.setProperty(Config.AAF_LOCATOR_CONTAINER_NS,"c_ns"); + target = "c_ns.myns.theName"; + assertEquals(target,rph.replacements(getClass().getSimpleName(),fqdn, name, "")); - } catch (UnknownHostException | CadiException e) { - e.printStackTrace(); - Assert.fail(); - } - } - + } catch (UnknownHostException | CadiException e) { + e.printStackTrace(); + Assert.fail(); + } + } + } diff --git a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_CSV.java b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_CSV.java index 9df6de7b..d4feac6f 100644 --- a/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_CSV.java +++ b/cadi/core/src/test/java/org/onap/aaf/cadi/util/test/JU_CSV.java @@ -43,83 +43,83 @@ import org.onap.aaf.cadi.util.CSV.Writer; public class JU_CSV { - private String filename; - private File file; - private static ArrayList<Object> expected; + private String filename; + private File file; + private static ArrayList<Object> expected; - @Before - public void start() { - filename = "Sample.csv"; - file = new File(filename); - } - - @After - public void end() { - if(file!=null) { - file.delete(); - } - } + @Before + public void start() { + filename = "Sample.csv"; + file = new File(filename); + } + + @After + public void end() { + if(file!=null) { + file.delete(); + } + } - @BeforeClass - public static void before() { - expected = new ArrayList<>(); - } - - @Test - public void test() throws IOException, CadiException { - Access access = new PropAccess(); - CSV csv = new CSV(access,file); - // Can't visit for file that doesn't exist - try { - csv.visit(new Visitor() { - @Override - public void visit(List<String> row) { - }}); - } catch(IOException e) { - Assert.assertTrue("CSV correctly created exception",true); - } - - Writer writer = csv.writer(); - try { - writer.row(add("\"hello\"")); - writer.comment("Ignore Comments"); - writer.row(add("dXNlcjpwYXNzd29yZA=="),add("dXNlckBzb21ldGhpbmcub3JnOm90aGVyUGFzc3dvcmQ=")); - writer.row(); // no output - writer.row(add("There is, but one thing to say"), add(" and that is"), add("\"All the best\"")); - } finally { - writer.close(); - } - - PrintStream garbage = new PrintStream(new FileOutputStream(file, true)); - try { - garbage.println("# Ignore empty spaces, etc"); - garbage.println(" "); - garbage.println("# Ignore blank lines"); - garbage.println(); - } finally { - garbage.close(); - } + @BeforeClass + public static void before() { + expected = new ArrayList<>(); + } + + @Test + public void test() throws IOException, CadiException { + Access access = new PropAccess(); + CSV csv = new CSV(access,file); + // Can't visit for file that doesn't exist + try { + csv.visit(new Visitor() { + @Override + public void visit(List<String> row) { + }}); + } catch(IOException e) { + Assert.assertTrue("CSV correctly created exception",true); + } + + Writer writer = csv.writer(); + try { + writer.row(add("\"hello\"")); + writer.comment("Ignore Comments"); + writer.row(add("dXNlcjpwYXNzd29yZA=="),add("dXNlckBzb21ldGhpbmcub3JnOm90aGVyUGFzc3dvcmQ=")); + writer.row(); // no output + writer.row(add("There is, but one thing to say"), add(" and that is"), add("\"All the best\"")); + } finally { + writer.close(); + } + + PrintStream garbage = new PrintStream(new FileOutputStream(file, true)); + try { + garbage.println("# Ignore empty spaces, etc"); + garbage.println(" "); + garbage.println("# Ignore blank lines"); + garbage.println(); + } finally { + garbage.close(); + } - - //////////// - // Tests - //////////// - final Holder<Integer> hi = new Holder<>(0); - csv.visit(new CSV.Visitor() { - @Override - public void visit(List<String> row) { - for(String s: row) { -// System.out.println(hi.value + ") " + s); - Assert.assertEquals(expected.get(hi.value++),s); - } - } - }); + + //////////// + // Tests + //////////// + final Holder<Integer> hi = new Holder<>(0); + csv.visit(new CSV.Visitor() { + @Override + public void visit(List<String> row) { + for(String s: row) { +// System.out.println(hi.value + ") " + s); + Assert.assertEquals(expected.get(hi.value++),s); + } + } + }); - } + } - private String add(String s) { - expected.add(s); - return s; - } + private String add(String s) { + expected.add(s); + return s; + } } 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 b09c2b78..d0c800bf 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 @@ -75,14 +75,14 @@ public class OAuthExample { // Obtain Endpoints for OAuth2 from Properties. Expected is "cadi.properties" file, pointed to by "cadi_prop_files" try { - Map<String, String> aaf_urls = Agent.loadURLs(access); - Agent.fillMissing(access, aaf_urls); - String tokenServiceURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL); // Default to AAF - String tokenIntrospectURL = access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL); // Default to AAF); - // Get Hello Service - final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL); - - final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); + Map<String, String> aaf_urls = Agent.loadURLs(access); + Agent.fillMissing(access, aaf_urls); + String tokenServiceURL = access.getProperty(Config.AAF_OAUTH2_TOKEN_URL); // Default to AAF + String tokenIntrospectURL = access.getProperty(Config.AAF_OAUTH2_INTROSPECT_URL); // Default to AAF); + // Get Hello Service + final String endServicesURL = access.getProperty(Config.AAF_OAUTH2_HELLO_URL); + + final int CALL_TIMEOUT = Integer.parseInt(access.getProperty(Config.AAF_CALL_TIMEOUT,Config.AAF_CALL_TIMEOUT_DEF)); ////////////////////////////////////////////////////////////////////// // Scenario 1: 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 b5d087ea..b8cce9e5 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 @@ -63,10 +63,10 @@ public class OnapClientExample { // Note: This style will load "cadi_prop_files" from VM Args // access = PropAccess(); try { - Map<String, String> aaf_urls = Agent.loadURLs(access); - Agent.fillMissing(access, aaf_urls); + Map<String, String> aaf_urls = Agent.loadURLs(access); + Agent.fillMissing(access, aaf_urls); - // Token aware Client Factory + // Token aware Client Factory tcf = TokenClientFactory.instance(access); } catch (APIException | GeneralSecurityException | IOException | CadiException e1) { access.log(e1, "Unable to setup OAuth Client Factory, Fail Fast"); 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 84eb5ee6..a98d7100 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 @@ -69,18 +69,18 @@ public interface LogTarget { public static final LogTarget SYSERR = new StreamLogTarget(System.err,false);
public static class StreamLogTarget implements LogTarget {
- private final PrintStream out;
- private final boolean closeMe;
-
- public StreamLogTarget(PrintStream ps) {
- this(ps,true);
- }
-
- /* Do NOT close SYSTEM ERR or OUT*/
- protected StreamLogTarget(PrintStream ps, boolean shouldClose) {
- out = ps;
- closeMe = shouldClose;
- }
+ private final PrintStream out;
+ private final boolean closeMe;
+
+ public StreamLogTarget(PrintStream ps) {
+ this(ps,true);
+ }
+
+ /* Do NOT close SYSTEM ERR or OUT*/
+ protected StreamLogTarget(PrintStream ps, boolean shouldClose) {
+ out = ps;
+ closeMe = shouldClose;
+ }
public void log(Object ... msgs) {
out.print(Chrono.dateFmt.format(new Date()));
out.print(": ");
@@ -117,9 +117,9 @@ public interface LogTarget { }
public void close() {
- if(closeMe) {
- out.close();
- }
+ if(closeMe) {
+ out.close();
+ }
}
}
diff --git a/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java b/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java index 58c588f6..2491e16c 100644 --- a/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java +++ b/misc/env/src/main/java/org/onap/aaf/misc/env/TimeTaken.java @@ -78,7 +78,7 @@ public abstract class TimeTaken { }
- /**
+ /**
* For sizable contents, set the size. Implementations can simply write a no-op if they don't wish to
* store the size.
*
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 5ba74369..9edd3bf4 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 @@ -131,11 +131,11 @@ public abstract class AbsTrans<ENV extends Env> implements TransStore { //long end = (first.flag&SUB)==SUB?first.end():trail.get(last).end();
long end = 0L;
for(int i=last;end==0L && i>=0;--i) {
- end= trail.get(i).end();
+ end= trail.get(i).end();
}
metric.total = (end - first.start) / 1000000f;
} else {
- metric.total=0L;
+ metric.total=0L;
}
if (sb==null) {
@@ -170,14 +170,14 @@ public abstract class AbsTrans<ENV extends Env> implements TransStore { sb.append(" ");
}
if((tt.flag & CHECKPOINT)==CHECKPOINT) {
- // Checkpoint
- sb.append(" ");
+ // Checkpoint
+ sb.append(" ");
} else {
- float ms=tt.millis();
+ float ms=tt.millis();
// Add time values to Metric
for (int i=0;i<flags.length;++i) {
if ((tt.flag & flags[i]) == flags[i]) {
- metric.buckets[i]+=ms;
+ metric.buckets[i]+=ms;
}
}
}
diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BaseDataFactory.java b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BaseDataFactory.java index 0c21bda3..15049dcd 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BaseDataFactory.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_BaseDataFactory.java @@ -30,53 +30,53 @@ import org.onap.aaf.misc.env.impl.EnvFactory; public class JU_BaseDataFactory { - @Before - public void setUp() throws Exception { - initMocks(this); - } - - @Test - public void testGenSchemaException() { - Store env = Mockito.mock(Store.class); - Mockito.doReturn("testdir").when(env).get(null, EnvFactory.DEFAULT_SCHEMA_DIR); - try { - BaseDataFactory.genSchema(env, new String[] {}); - } catch (APIException e) { - assertTrue(e.getLocalizedMessage().contains("does not exist. You can set this with")); - } - } - - @Test - public void testGenSchemaXsdException() { - Store env = Mockito.mock(Store.class); - Mockito.doReturn(System.getProperty("user.dir")).when(env).get(null, EnvFactory.DEFAULT_SCHEMA_DIR); - String[] schemaFIles = new String[] {"../auth-client/src/main/xsd/aaf_2_0.xsd"}; - try { - BaseDataFactory.genSchema(env, schemaFIles); - } catch (APIException e) { - assertTrue(e.getLocalizedMessage().contains("for schema validation")); - } - } - - @Test - public void testGenSchemaNoException() { - Store env = Mockito.mock(Store.class); - Mockito.doReturn(System.getProperty("user.dir")).when(env).get(null, EnvFactory.DEFAULT_SCHEMA_DIR); - String[] schemaFIles = new String[] {"../../auth-client/src/main/xsd/aaf_2_0.xsd"}; - try { - BaseDataFactory.genSchema(env, schemaFIles); - } catch (APIException e) { - e.printStackTrace(); - } - } - - @Test - public void testGetQName() { - String[] schemaFIles = new String[] {"../../auth-client/src/main/xsd/aaf_2_0.xsd"}; - try { - BaseDataFactory.getQName(Api.class); - } catch (APIException e) { - assertTrue(e.getLocalizedMessage().contains("package-info does not have an XmlSchema annotation")); - } - } + @Before + public void setUp() throws Exception { + initMocks(this); + } + + @Test + public void testGenSchemaException() { + Store env = Mockito.mock(Store.class); + Mockito.doReturn("testdir").when(env).get(null, EnvFactory.DEFAULT_SCHEMA_DIR); + try { + BaseDataFactory.genSchema(env, new String[] {}); + } catch (APIException e) { + assertTrue(e.getLocalizedMessage().contains("does not exist. You can set this with")); + } + } + + @Test + public void testGenSchemaXsdException() { + Store env = Mockito.mock(Store.class); + Mockito.doReturn(System.getProperty("user.dir")).when(env).get(null, EnvFactory.DEFAULT_SCHEMA_DIR); + String[] schemaFIles = new String[] {"../auth-client/src/main/xsd/aaf_2_0.xsd"}; + try { + BaseDataFactory.genSchema(env, schemaFIles); + } catch (APIException e) { + assertTrue(e.getLocalizedMessage().contains("for schema validation")); + } + } + + @Test + public void testGenSchemaNoException() { + Store env = Mockito.mock(Store.class); + Mockito.doReturn(System.getProperty("user.dir")).when(env).get(null, EnvFactory.DEFAULT_SCHEMA_DIR); + String[] schemaFIles = new String[] {"../../auth-client/src/main/xsd/aaf_2_0.xsd"}; + try { + BaseDataFactory.genSchema(env, schemaFIles); + } catch (APIException e) { + e.printStackTrace(); + } + } + + @Test + public void testGetQName() { + String[] schemaFIles = new String[] {"../../auth-client/src/main/xsd/aaf_2_0.xsd"}; + try { + BaseDataFactory.getQName(Api.class); + } catch (APIException e) { + assertTrue(e.getLocalizedMessage().contains("package-info does not have an XmlSchema annotation")); + } + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_JavaUtilLogTarget.java b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_JavaUtilLogTarget.java index d76d8828..a3063f73 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_JavaUtilLogTarget.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_JavaUtilLogTarget.java @@ -43,44 +43,44 @@ public class JU_JavaUtilLogTarget { @Before public void setup() { - initMocks(this); + initMocks(this); } @Test public void testLoggable() { - JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); - boolean retVal = logObj.isLoggable(); - + JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); + boolean retVal = logObj.isLoggable(); + assertFalse(retVal); } @Test public void testLog() { - JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); - Mockito.doReturn(false).when(log).isLoggable(level); - logObj.log(new Object[] {"test","test2",""}); - Mockito.doReturn(true).when(log).isLoggable(level); - logObj.log(new Object[] {"test","test2",""}); - + JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); + Mockito.doReturn(false).when(log).isLoggable(level); + logObj.log(new Object[] {"test","test2",""}); + Mockito.doReturn(true).when(log).isLoggable(level); + logObj.log(new Object[] {"test","test2",""}); + } @Test public void testLogThrowable() { - JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); - - Mockito.doReturn(true).when(log).isLoggable(level); - logObj.log(new Throwable("test exception"), new Object[] {"test","test2",""}); - logObj.log(new Throwable(), new Object[] {"test","test2",""}); + JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); + + Mockito.doReturn(true).when(log).isLoggable(level); + logObj.log(new Throwable("test exception"), new Object[] {"test","test2",""}); + logObj.log(new Throwable(), new Object[] {"test","test2",""}); } @Test public void testPrintf() { - JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); - - Mockito.doReturn(true).when(log).isLoggable(level); - logObj.printf("test", new Object[] {"test","test2",""}); + JavaUtilLogTarget logObj = new JavaUtilLogTarget( log, level); + + Mockito.doReturn(true).when(log).isLoggable(level); + logObj.printf("test", new Object[] {"test","test2",""}); - Mockito.doReturn(false).when(log).isLoggable(level); - logObj.printf("test", new Object[] {"test","test2",""}); + Mockito.doReturn(false).when(log).isLoggable(level); + logObj.printf("test", new Object[] {"test","test2",""}); } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java index 2388964f..c679d11e 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_LogTargetTest.java @@ -65,9 +65,9 @@ public class JU_LogTargetTest { outTarget.log(t);
outTarget.log(t, "First String Object");
- assertTrue(outTarget.isLoggable());
+ assertTrue(outTarget.isLoggable());
- verify(t, times(2)).printStackTrace(System.out);
+ verify(t, times(2)).printStackTrace(System.out);
}
@Test
@@ -80,9 +80,9 @@ public class JU_LogTargetTest { errTarget.log(t);
errTarget.log(t, "First String Object");
- assertTrue(errTarget.isLoggable());
+ assertTrue(errTarget.isLoggable());
- verify(t, times(2)).printStackTrace(System.err);
+ verify(t, times(2)).printStackTrace(System.err);
}
}
diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_NullLifeCycle.java b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_NullLifeCycle.java index d8e843b4..ed75f4cb 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/JU_NullLifeCycle.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/JU_NullLifeCycle.java @@ -28,16 +28,16 @@ public class JU_NullLifeCycle { @Test public void testServicePrestart() { - NullLifeCycle lifeCycleObj = new NullLifeCycle(); - try { - lifeCycleObj.servicePrestart(null); - lifeCycleObj.serviceDestroy(null); - lifeCycleObj.threadDestroy(null); - lifeCycleObj.threadPrestart(null); - lifeCycleObj.refresh(null); - }catch(APIException a) { - - } + NullLifeCycle lifeCycleObj = new NullLifeCycle(); + try { + lifeCycleObj.servicePrestart(null); + lifeCycleObj.serviceDestroy(null); + lifeCycleObj.threadDestroy(null); + lifeCycleObj.threadPrestart(null); + lifeCycleObj.refresh(null); + }catch(APIException a) { + + } } }
\ No newline at end of file diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTrans.java b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTrans.java index 93821606..e1e7d0e9 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTrans.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTrans.java @@ -39,253 +39,253 @@ import org.onap.aaf.misc.env.TimeTaken; public class JU_AbsTrans { - @Mock - Env delegate; - - @Mock - BasicEnv delegate1; - - @Mock - LogTarget lt; - - @Before - public void setUp() { - initMocks(this); - } - - class AbsTransImpl extends AbsTrans{ + @Mock + Env delegate; + + @Mock + BasicEnv delegate1; + + @Mock + LogTarget lt; + + @Before + public void setUp() { + initMocks(this); + } + + class AbsTransImpl extends AbsTrans{ - public AbsTransImpl(Env delegate) { - super(delegate); - // TODO Auto-generated constructor stub - } - - public AbsTransImpl(BasicEnv delegate) { - super(delegate); - // TODO Auto-generated constructor stub - } + public AbsTransImpl(Env delegate) { + super(delegate); + // TODO Auto-generated constructor stub + } + + public AbsTransImpl(BasicEnv delegate) { + super(delegate); + // TODO Auto-generated constructor stub + } - @Override - public Slot slot(String name) { - // TODO Auto-generated method stub - return new Slot(-1, "test"); - } + @Override + public Slot slot(String name) { + // TODO Auto-generated method stub + return new Slot(-1, "test"); + } - @Override - public <T> T get(StaticSlot slot, T dflt) { - // TODO Auto-generated method stub - return null; - } + @Override + public <T> T get(StaticSlot slot, T dflt) { + // TODO Auto-generated method stub + return null; + } - @Override - public String setProperty(String tag, String value) { - // TODO Auto-generated method stub - return null; - } + @Override + public String setProperty(String tag, String value) { + // TODO Auto-generated method stub + return null; + } - @Override - public String getProperty(String tag) { - // TODO Auto-generated method stub - return null; - } + @Override + public String getProperty(String tag) { + // TODO Auto-generated method stub + return null; + } - @Override - public String getProperty(String tag, String deflt) { - // TODO Auto-generated method stub - return null; - } + @Override + public String getProperty(String tag, String deflt) { + // TODO Auto-generated method stub + return null; + } - @Override - public Decryptor decryptor() { - // TODO Auto-generated method stub - return null; - } + @Override + public Decryptor decryptor() { + // TODO Auto-generated method stub + return null; + } - @Override - public Encryptor encryptor() { - // TODO Auto-generated method stub - return null; - } + @Override + public Encryptor encryptor() { + // TODO Auto-generated method stub + return null; + } - @Override - protected TimeTaken newTimeTaken(String name, int flag, Object ... values) { - // TODO Auto-generated method stub - return new TimeTaken("nameTest", Env.XML) { - - @Override - public void output(StringBuilder sb) { - // TODO Auto-generated method stub - - } - }; - } - - } - - @Test - public void testFatal() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).fatal(); - LogTarget lt = absTransObj.fatal(); - assertTrue(lt instanceof LogTarget); - } - - @Test - public void testError() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).error(); - LogTarget lt = absTransObj.error(); - assertTrue(lt instanceof LogTarget); - } - - @Test - public void testAudit() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).audit(); - LogTarget lt = absTransObj.audit(); - assertTrue(lt instanceof LogTarget); - } + @Override + protected TimeTaken newTimeTaken(String name, int flag, Object ... values) { + // TODO Auto-generated method stub + return new TimeTaken("nameTest", Env.XML) { + + @Override + public void output(StringBuilder sb) { + // TODO Auto-generated method stub + + } + }; + } + + } + + @Test + public void testFatal() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).fatal(); + LogTarget lt = absTransObj.fatal(); + assertTrue(lt instanceof LogTarget); + } + + @Test + public void testError() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).error(); + LogTarget lt = absTransObj.error(); + assertTrue(lt instanceof LogTarget); + } + + @Test + public void testAudit() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).audit(); + LogTarget lt = absTransObj.audit(); + assertTrue(lt instanceof LogTarget); + } - @Test - public void testInit() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).init(); - LogTarget lt = absTransObj.init(); - assertTrue(lt instanceof LogTarget); - } - - @Test - public void testWarn() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).warn(); - LogTarget lt = absTransObj.warn(); - assertTrue(lt instanceof LogTarget); - } - - @Test - public void testInfo() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).info(); - LogTarget lt = absTransObj.info(); - assertTrue(lt instanceof LogTarget); - } - - @Test - public void testDebug() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).debug(); - LogTarget lt = absTransObj.debug(); - assertTrue(lt instanceof LogTarget); - } - - @Test - public void testTrace() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).trace(); - LogTarget lt = absTransObj.trace(); - assertTrue(lt instanceof LogTarget); - } - - @Test - public void testStart() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - TimeTaken lt = absTransObj.start("test",1); - assertEquals("nameTest", lt.name); - } - - @Test - public void testCheckpint() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - absTransObj.checkpoint("test"); - assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); - } - - @Test - public void testCheckpintAddFlag() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - absTransObj.checkpoint("test",1); - assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); - } - - @Test - public void testAuditTrailWithEmptyTrail() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).info(); - Mockito.doReturn(true).when(lt).isLoggable(); - absTransObj.auditTrail(1, new StringBuilder(), 1); - //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); - } - - @Test - public void testAuditTrail() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).info(); - Mockito.doReturn(true).when(lt).isLoggable(); - TimeTaken tt=absTransObj.newTimeTaken("test", 1); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.auditTrail(1, new StringBuilder(), 2); - //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); - } - - @Test - public void testAuditTrailLoggableFalse() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).info(); - Mockito.doReturn(false).when(lt).isLoggable(); - TimeTaken tt=absTransObj.newTimeTaken("test", 1); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.auditTrail(1, new StringBuilder(), 1); - //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); - } - - @Test - public void testAuditTrailNullSB() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).info(); - Mockito.doReturn(true).when(lt).isLoggable(); - TimeTaken tt=absTransObj.newTimeTaken("test", 1); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.auditTrail(1, null, 1); - //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); - } - - @Test - public void testAuditTrailEmpptyFlag() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate); - Mockito.doReturn(lt).when(delegate).info(); - Mockito.doReturn(true).when(lt).isLoggable(); - TimeTaken tt=absTransObj.newTimeTaken("test", 1); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.trail.add(tt); - absTransObj.auditTrail(1, null, new int[] {}); - //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); - } - - @Test - public void testPut() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate1); - try { - absTransObj.put(absTransObj.slot("test"), "test"); - } catch(Exception e){ - assertTrue(e instanceof NullPointerException); - } - } - - @Test - public void testGet() { - AbsTransImpl absTransObj = new AbsTransImpl(delegate1); - try { - absTransObj.get(absTransObj.slot("test"), "test"); - } catch(Exception e){ - e.printStackTrace(); - assertTrue(e instanceof NullPointerException); - } - } + @Test + public void testInit() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).init(); + LogTarget lt = absTransObj.init(); + assertTrue(lt instanceof LogTarget); + } + + @Test + public void testWarn() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).warn(); + LogTarget lt = absTransObj.warn(); + assertTrue(lt instanceof LogTarget); + } + + @Test + public void testInfo() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).info(); + LogTarget lt = absTransObj.info(); + assertTrue(lt instanceof LogTarget); + } + + @Test + public void testDebug() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).debug(); + LogTarget lt = absTransObj.debug(); + assertTrue(lt instanceof LogTarget); + } + + @Test + public void testTrace() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).trace(); + LogTarget lt = absTransObj.trace(); + assertTrue(lt instanceof LogTarget); + } + + @Test + public void testStart() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + TimeTaken lt = absTransObj.start("test",1); + assertEquals("nameTest", lt.name); + } + + @Test + public void testCheckpint() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + absTransObj.checkpoint("test"); + assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); + } + + @Test + public void testCheckpintAddFlag() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + absTransObj.checkpoint("test",1); + assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); + } + + @Test + public void testAuditTrailWithEmptyTrail() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).info(); + Mockito.doReturn(true).when(lt).isLoggable(); + absTransObj.auditTrail(1, new StringBuilder(), 1); + //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); + } + + @Test + public void testAuditTrail() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).info(); + Mockito.doReturn(true).when(lt).isLoggable(); + TimeTaken tt=absTransObj.newTimeTaken("test", 1); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.auditTrail(1, new StringBuilder(), 2); + //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); + } + + @Test + public void testAuditTrailLoggableFalse() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).info(); + Mockito.doReturn(false).when(lt).isLoggable(); + TimeTaken tt=absTransObj.newTimeTaken("test", 1); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.auditTrail(1, new StringBuilder(), 1); + //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); + } + + @Test + public void testAuditTrailNullSB() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).info(); + Mockito.doReturn(true).when(lt).isLoggable(); + TimeTaken tt=absTransObj.newTimeTaken("test", 1); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.auditTrail(1, null, 1); + //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); + } + + @Test + public void testAuditTrailEmpptyFlag() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate); + Mockito.doReturn(lt).when(delegate).info(); + Mockito.doReturn(true).when(lt).isLoggable(); + TimeTaken tt=absTransObj.newTimeTaken("test", 1); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.trail.add(tt); + absTransObj.auditTrail(1, null, new int[] {}); + //assertEquals("nameTest", ((TimeTaken)absTransObj.trail.get(0)).name); + } + + @Test + public void testPut() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate1); + try { + absTransObj.put(absTransObj.slot("test"), "test"); + } catch(Exception e){ + assertTrue(e instanceof NullPointerException); + } + } + + @Test + public void testGet() { + AbsTransImpl absTransObj = new AbsTransImpl(delegate1); + try { + absTransObj.get(absTransObj.slot("test"), "test"); + } catch(Exception e){ + e.printStackTrace(); + assertTrue(e instanceof NullPointerException); + } + } }
\ No newline at end of file diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTransJaxb.java b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTransJaxb.java index 22d979fe..f8b32451 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTransJaxb.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/impl/JU_AbsTransJaxb.java @@ -42,136 +42,136 @@ import org.onap.aaf.misc.env.TimeTaken; public class JU_AbsTransJaxb { - @Mock - EnvJAXB delegate; - - @Mock - LogTarget lt; - - @Before - public void setUp() { - initMocks(this); - } - - class AbsTransJAXBImpl extends AbsTransJAXB{ - - public AbsTransJAXBImpl(EnvJAXB env) { - super(env); - // TODO Auto-generated constructor stub - } - - @Override - public String setProperty(String tag, String value) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getProperty(String tag) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getProperty(String tag, String deflt) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Decryptor decryptor() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Encryptor encryptor() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Slot slot(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - public <T> T get(StaticSlot slot, T dflt) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected TimeTaken newTimeTaken(String name, int flag, Object ... values) { - // TODO Auto-generated method stub - return null; - } - - - } - - - @Test - public void testNewDataFactory() { - AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); - DataFactory<Object> lt = null; - - try { - Mockito.doReturn(lt).when(delegate).newDataFactory(new Class[] {AbsTransJAXB.class}); - lt = absTransObj.newDataFactory(new Class[] {AbsTransJAXB.class}); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //assertTrue(lt instanceof LogTarget); - } - - @Test - public void testNewDataFactorySchema() { - AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); - DataFactory<Object> lt = null; - Schema schema = Mockito.mock(Schema.class); - try { - Mockito.doReturn(lt).when(delegate).newDataFactory(schema, new Class[] {AbsTransJAXB.class}); - lt = absTransObj.newDataFactory(schema, new Class[] {AbsTransJAXB.class}); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //assertTrue(lt instanceof LogTarget); - } - - @Test - public void testNewDataFactoryQname() { - AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); - DataFactory<Object> lt = null; - QName schema = Mockito.mock(QName.class); - try { - Mockito.doReturn(lt).when(delegate).newDataFactory(schema, new Class[] {AbsTransJAXB.class}); - lt = absTransObj.newDataFactory(schema, new Class[] {AbsTransJAXB.class}); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //assertTrue(lt instanceof LogTarget); - } - - @Test - public void testNewDataFactorySchemaQname() { - AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); - DataFactory<Object> lt = null; - QName qname = Mockito.mock(QName.class); - Schema schema = Mockito.mock(Schema.class); - try { - Mockito.doReturn(lt).when(delegate).newDataFactory(schema, qname,new Class[] {AbsTransJAXB.class}); - lt = absTransObj.newDataFactory(schema, qname,new Class[] {AbsTransJAXB.class}); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - //assertTrue(lt instanceof LogTarget); - } - - + @Mock + EnvJAXB delegate; + + @Mock + LogTarget lt; + + @Before + public void setUp() { + initMocks(this); + } + + class AbsTransJAXBImpl extends AbsTransJAXB{ + + public AbsTransJAXBImpl(EnvJAXB env) { + super(env); + // TODO Auto-generated constructor stub + } + + @Override + public String setProperty(String tag, String value) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getProperty(String tag) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getProperty(String tag, String deflt) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Decryptor decryptor() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Encryptor encryptor() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Slot slot(String name) { + // TODO Auto-generated method stub + return null; + } + + @Override + public <T> T get(StaticSlot slot, T dflt) { + // TODO Auto-generated method stub + return null; + } + + @Override + protected TimeTaken newTimeTaken(String name, int flag, Object ... values) { + // TODO Auto-generated method stub + return null; + } + + + } + + + @Test + public void testNewDataFactory() { + AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); + DataFactory<Object> lt = null; + + try { + Mockito.doReturn(lt).when(delegate).newDataFactory(new Class[] {AbsTransJAXB.class}); + lt = absTransObj.newDataFactory(new Class[] {AbsTransJAXB.class}); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //assertTrue(lt instanceof LogTarget); + } + + @Test + public void testNewDataFactorySchema() { + AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); + DataFactory<Object> lt = null; + Schema schema = Mockito.mock(Schema.class); + try { + Mockito.doReturn(lt).when(delegate).newDataFactory(schema, new Class[] {AbsTransJAXB.class}); + lt = absTransObj.newDataFactory(schema, new Class[] {AbsTransJAXB.class}); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //assertTrue(lt instanceof LogTarget); + } + + @Test + public void testNewDataFactoryQname() { + AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); + DataFactory<Object> lt = null; + QName schema = Mockito.mock(QName.class); + try { + Mockito.doReturn(lt).when(delegate).newDataFactory(schema, new Class[] {AbsTransJAXB.class}); + lt = absTransObj.newDataFactory(schema, new Class[] {AbsTransJAXB.class}); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //assertTrue(lt instanceof LogTarget); + } + + @Test + public void testNewDataFactorySchemaQname() { + AbsTransJAXB absTransObj = new AbsTransJAXBImpl(delegate); + DataFactory<Object> lt = null; + QName qname = Mockito.mock(QName.class); + Schema schema = Mockito.mock(Schema.class); + try { + Mockito.doReturn(lt).when(delegate).newDataFactory(schema, qname,new Class[] {AbsTransJAXB.class}); + lt = absTransObj.newDataFactory(schema, qname,new Class[] {AbsTransJAXB.class}); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + //assertTrue(lt instanceof LogTarget); + } + + }
\ No newline at end of file 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 6900d9ed..fe72d01e 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 @@ -34,75 +34,75 @@ import org.onap.aaf.misc.env.APIException; public class JU_Log4JLogTargetTest {
- @Mock
- Level level;
-
+ @Mock
+ Level level;
+
@Mock
Logger log;
@Before
public void setup() {
- initMocks(this);
+ initMocks(this);
}
@Test
public void testLoggable() {
- Log4JLogTarget logObj = null;
- try {
- logObj = new Log4JLogTarget( "testLogger", Level.DEBUG);
- } catch (APIException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- boolean retVal = logObj.isLoggable();
+ Log4JLogTarget logObj = null;
+ try {
+ logObj = new Log4JLogTarget( "testLogger", Level.DEBUG);
+ } catch (APIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ boolean retVal = logObj.isLoggable();
assertTrue(retVal);
}
@Test
public void testLog() {
- Log4JLogTarget logObj = null;
- try {
- logObj = new Log4JLogTarget( null, Level.DEBUG);
- } catch (APIException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- logObj.log(new Object[] {"test"});
+ Log4JLogTarget logObj = null;
+ try {
+ logObj = new Log4JLogTarget( null, Level.DEBUG);
+ } catch (APIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ logObj.log(new Object[] {"test"});
}
@Test
public void testLogThrowable() {
- Log4JLogTarget logObj = null;
- try {
- logObj = new Log4JLogTarget( null, Level.DEBUG);
- } catch (APIException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- logObj.log(new Throwable("test exception"), new Object[] {"test","test2","",null});
+ Log4JLogTarget logObj = null;
+ try {
+ logObj = new Log4JLogTarget( null, Level.DEBUG);
+ } catch (APIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ logObj.log(new Throwable("test exception"), new Object[] {"test","test2","",null});
}
@Test
public void testPrintf() {
- Log4JLogTarget logObj = null;
- try {
- logObj = new Log4JLogTarget( "", level);
- } catch (APIException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- logObj.printf("test", new Object[] {"test","test2",""});
+ Log4JLogTarget logObj = null;
+ try {
+ logObj = new Log4JLogTarget( "", level);
+ } catch (APIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ logObj.printf("test", new Object[] {"test","test2",""});
}
@Test
public void testSetEnv() {
- try {
- Log4JLogTarget.setLog4JEnv("test", Mockito.mock(BasicEnv.class));
- } catch (APIException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
+ try {
+ Log4JLogTarget.setLog4JEnv("test", Mockito.mock(BasicEnv.class));
+ } catch (APIException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
}
}
\ No newline at end of file diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDF.java b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDF.java index 62c49032..7952740b 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDF.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBDF.java @@ -64,651 +64,651 @@ public class JU_JAXBDF { @Before public void setUp() { - initMocks(this); - tt=Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(env).start("JAXB Stringify", Env.XML); - Mockito.doNothing().when(tt).done(); - ttObjectify=Mockito.mock(TimeTaken.class); - Mockito.doReturn(ttObjectify).when(env).start("JAXB Objectify", Env.XML); - Mockito.doNothing().when(ttObjectify).done(); + initMocks(this); + tt=Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(env).start("JAXB Stringify", Env.XML); + Mockito.doNothing().when(tt).done(); + ttObjectify=Mockito.mock(TimeTaken.class); + Mockito.doReturn(ttObjectify).when(env).start("JAXB Objectify", Env.XML); + Mockito.doNothing().when(ttObjectify).done(); } @Test public void testNewInstance() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - Mockito.doThrow(new IllegalAccessException("Test Exception")).when(bdfObj.jumar).newInstance(); - Object retVal = bdfObj.newInstance(); - } catch (IllegalAccessException e) { - assertEquals("Test Exception", e.getLocalizedMessage()); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + Mockito.doThrow(new IllegalAccessException("Test Exception")).when(bdfObj.jumar).newInstance(); + Object retVal = bdfObj.newInstance(); + } catch (IllegalAccessException e) { + assertEquals("Test Exception", e.getLocalizedMessage()); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } @Test public void testNewInstanceNoException() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, new Class[] {this.getClass()}); - Object retVal = bdfObj.newInstance(); - assertTrue(retVal instanceof JU_JAXBDF); - } catch (APIException e) { - e.printStackTrace(); - } - + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, new Class[] {this.getClass()}); + Object retVal = bdfObj.newInstance(); + assertTrue(retVal instanceof JU_JAXBDF); + } catch (APIException e) { + e.printStackTrace(); + } + } @Test public void testPrettyNoException() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(Schema.class), new Class[] {this.getClass()}); - Object retVal = bdfObj.pretty(true); - assertTrue(retVal instanceof JAXBDF); - } catch (APIException e) { - e.printStackTrace(); - } + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(Schema.class), new Class[] {this.getClass()}); + Object retVal = bdfObj.pretty(true); + assertTrue(retVal instanceof JAXBDF); + } catch (APIException e) { + e.printStackTrace(); + } } @Test public void testFragment() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(QName.class), new Class[] {this.getClass()}); - Object retVal = bdfObj.asFragment(true); - assertTrue(retVal instanceof JAXBDF); - bdfObj.servicePrestart(null); - bdfObj.threadPrestart(null); - bdfObj.refresh(null); - bdfObj.threadDestroy(null); - bdfObj.serviceDestroy(null); - } catch (APIException e) { - e.printStackTrace(); - } - + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(QName.class), new Class[] {this.getClass()}); + Object retVal = bdfObj.asFragment(true); + assertTrue(retVal instanceof JAXBDF); + bdfObj.servicePrestart(null); + bdfObj.threadPrestart(null); + bdfObj.refresh(null); + bdfObj.threadDestroy(null); + bdfObj.serviceDestroy(null); + } catch (APIException e) { + e.printStackTrace(); + } + } @Test public void testNewData() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); - Data<?> retVal = bdfObj.newData(); - assertTrue(retVal instanceof JAXBData); - } catch (APIException e) { - e.printStackTrace(); - } + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); + Data<?> retVal = bdfObj.newData(); + assertTrue(retVal instanceof JAXBData); + } catch (APIException e) { + e.printStackTrace(); + } } @Test public void testNewDataENV() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); - Data<?> retVal = bdfObj.newData(Mockito.mock(Env.class)); - assertTrue(retVal instanceof JAXBData); - } catch (APIException e) { - e.printStackTrace(); - } + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); + Data<?> retVal = bdfObj.newData(Mockito.mock(Env.class)); + assertTrue(retVal instanceof JAXBData); + } catch (APIException e) { + e.printStackTrace(); + } } @Test public void testNewDataType() { - JAXBDF<JAXBumar> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); - Data<?> retVal = bdfObj.newData(new JAXBumar(new Class[] {this.getClass()})); - assertTrue(retVal instanceof JAXBData); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<JAXBumar> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); + Data<?> retVal = bdfObj.newData(new JAXBumar(new Class[] {this.getClass()})); + assertTrue(retVal instanceof JAXBData); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testNewDataStream() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - InputStream is = Mockito.mock(InputStream.class); - Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, is); - Data<?> retVal = bdfObj.newDataFromStream(env, is); - assertTrue(retVal instanceof JAXBData); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + InputStream is = Mockito.mock(InputStream.class); + Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, is); + Data<?> retVal = bdfObj.newDataFromStream(env, is); + assertTrue(retVal instanceof JAXBData); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testNewDataStreamException() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - InputStream is = Mockito.mock(InputStream.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, is); - Data<?> retVal = bdfObj.newDataFromStream(env, is); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - assertTrue(e.getMessage().contains("test")); - } + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + InputStream is = Mockito.mock(InputStream.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, is); + Data<?> retVal = bdfObj.newDataFromStream(env, is); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + assertTrue(e.getMessage().contains("test")); + } } @Test public void testNewDataFromString() { - JAXBDF<?> bdfObj = null; - try { - bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); - Data<?> retVal = bdfObj.newDataFromString("test"); - assertTrue(retVal instanceof JAXBData); - } catch (APIException e) { - e.printStackTrace(); - } + JAXBDF<?> bdfObj = null; + try { + bdfObj = new JAXBDF( null, Mockito.mock(Schema.class),Mockito.mock(QName.class), new Class[] {this.getClass()}); + Data<?> retVal = bdfObj.newDataFromString("test"); + assertTrue(retVal instanceof JAXBData); + } catch (APIException e) { + e.printStackTrace(); + } } @Test public void testStringify() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class)); - String retVal = bdfObj.stringify(typeObj); - assertEquals("", retVal); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class)); + String retVal = bdfObj.stringify(typeObj); + assertEquals("", retVal); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testStringifyException() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - bdfObj = new JAXBDF<JAXBmar>( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - Mockito.doThrow(new JAXBException("test") ).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class)); - String retVal = bdfObj.stringify(typeObj); - System.out.println(retVal); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + bdfObj = new JAXBDF<JAXBmar>( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + Mockito.doThrow(new JAXBException("test") ).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class)); + String retVal = bdfObj.stringify(typeObj); + System.out.println(retVal); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } } @Test public void testStringifyWriter() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class)); - bdfObj.stringify(typeObj, Mockito.mock(StringWriter.class)); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class)); + bdfObj.stringify(typeObj, Mockito.mock(StringWriter.class)); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testStringifyWriterException() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - StringWriter sw = Mockito.mock(StringWriter.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw); - bdfObj.stringify(typeObj, sw); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + StringWriter sw = Mockito.mock(StringWriter.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw); + bdfObj.stringify(typeObj, sw); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } } @Test public void testStringifyOS() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(OutputStream.class)); - bdfObj.stringify(typeObj, Mockito.mock(OutputStream.class)); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(OutputStream.class)); + bdfObj.stringify(typeObj, Mockito.mock(OutputStream.class)); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testStringifyOsException() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - OutputStream sw = Mockito.mock(OutputStream.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw); - bdfObj.stringify(typeObj, sw); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + OutputStream sw = Mockito.mock(OutputStream.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw); + bdfObj.stringify(typeObj, sw); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } } @Test public void testStringifyOptions() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(OutputStream.class)); - bdfObj.stringify(env, typeObj, true); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(OutputStream.class)); + bdfObj.stringify(env, typeObj, true); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testStringifyOSOptions() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(OutputStream.class),true); - bdfObj.stringify(env, typeObj, Mockito.mock(OutputStream.class),true); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(OutputStream.class),true); + bdfObj.stringify(env, typeObj, Mockito.mock(OutputStream.class),true); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testStringifyOsOptionsException() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - OutputStream sw = Mockito.mock(OutputStream.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw,true); - bdfObj.stringify(env, typeObj, sw,true); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + OutputStream sw = Mockito.mock(OutputStream.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw,true); + bdfObj.stringify(env, typeObj, sw,true); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } } @Test public void testStringifySWOptions() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class),true); - bdfObj.stringify(env, typeObj, Mockito.mock(StringWriter.class),true); - } catch (APIException e) { - e.printStackTrace(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jmar).marshal(logT, typeObj, Mockito.mock(StringWriter.class),true); + bdfObj.stringify(env, typeObj, Mockito.mock(StringWriter.class),true); + } catch (APIException e) { + e.printStackTrace(); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } @Test public void testStringifySWOptionsException() { - JAXBDF<JAXBmar> bdfObj = null; - try { - JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); - bdfObj.jmar = Mockito.mock(JAXBmar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - StringWriter sw = Mockito.mock(StringWriter.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw,true); - bdfObj.stringify(env, typeObj, sw,true); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } + JAXBDF<JAXBmar> bdfObj = null; + try { + JAXBmar typeObj = new JAXBmar(new Class[] {this.getClass()}); + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF( envJaxb, new Class[] {this.getClass()}); + bdfObj.jmar = Mockito.mock(JAXBmar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + StringWriter sw = Mockito.mock(StringWriter.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jmar).marshal(logT, typeObj, sw,true); + bdfObj.stringify(env, typeObj, sw,true); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } } @Test public void testObjectifyEnv() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(StringReader.class)); - - bdfObj.objectify(env, Mockito.mock(StringReader.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(StringReader.class)); + + bdfObj.objectify(env, Mockito.mock(StringReader.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyEnvException() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - StringReader sr = Mockito.mock(StringReader.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); - - bdfObj.objectify(env, sr); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + StringReader sr = Mockito.mock(StringReader.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); + + bdfObj.objectify(env, sr); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyRdr() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(StringReader.class)); - - bdfObj.objectify( Mockito.mock(StringReader.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(StringReader.class)); + + bdfObj.objectify( Mockito.mock(StringReader.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyRdrException() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - StringReader sr = Mockito.mock(StringReader.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); - - bdfObj.objectify(sr); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + StringReader sr = Mockito.mock(StringReader.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); + + bdfObj.objectify(sr); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyEnvIS() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(InputStream.class)); - - bdfObj.objectify(env, Mockito.mock(InputStream.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(InputStream.class)); + + bdfObj.objectify(env, Mockito.mock(InputStream.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyEnvISException() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - InputStream sr = Mockito.mock(InputStream.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); - - bdfObj.objectify(env, sr); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + InputStream sr = Mockito.mock(InputStream.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); + + bdfObj.objectify(env, sr); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyIs() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(InputStream.class)); - - bdfObj.objectify( Mockito.mock(InputStream.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, Mockito.mock(InputStream.class)); + + bdfObj.objectify( Mockito.mock(InputStream.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyIsException() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - InputStream sr = Mockito.mock(InputStream.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); - - bdfObj.objectify(sr); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + InputStream sr = Mockito.mock(InputStream.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, sr); + + bdfObj.objectify(sr); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyEnvStr() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, "test"); - - bdfObj.objectify(env, "test"); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, "test"); + + bdfObj.objectify(env, "test"); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyEnvStrException() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - InputStream sr = Mockito.mock(InputStream.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, "test"); - - bdfObj.objectify(env, "test"); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + InputStream sr = Mockito.mock(InputStream.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, "test"); + + bdfObj.objectify(env, "test"); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyStr() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, "test"); - - bdfObj.objectify( "test"); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + Mockito.doReturn(this.getClass()).when(bdfObj.jumar).unmarshal(logT, "test"); + + bdfObj.objectify( "test"); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testObjectifyStrException() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); - bdfObj.jumar = Mockito.mock(JAXBumar.class); - LogTarget logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(envJaxb).debug(); - InputStream sr = Mockito.mock(InputStream.class); - Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, "test"); - - bdfObj.objectify("test"); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } catch (JAXBException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + JAXBumar typeObj = new JAXBumar(new Class[] {this.getClass()}); + bdfObj.jumar = Mockito.mock(JAXBumar.class); + LogTarget logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(envJaxb).debug(); + InputStream sr = Mockito.mock(InputStream.class); + Mockito.doThrow(new JAXBException("test")).when(bdfObj.jumar).unmarshal(logT, "test"); + + bdfObj.objectify("test"); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } catch (JAXBException e) { + assertTrue(e.getMessage().contains("test")); + } + } @Test public void testTypeClass() { - JAXBDF<JAXBumar> bdfObj = null; - try { - EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); - bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); - - Object obj = bdfObj.getTypeClass(); - assertFalse(obj instanceof JU_JAXBDF); - } catch (APIException e) { - assertTrue(e.getMessage().contains("test")); - } - + JAXBDF<JAXBumar> bdfObj = null; + try { + EnvJAXB envJaxb = Mockito.mock(EnvJAXB.class); + bdfObj = new JAXBDF<JAXBumar>( envJaxb, new Class[] {this.getClass()}); + + Object obj = bdfObj.getTypeClass(); + assertFalse(obj instanceof JU_JAXBDF); + } catch (APIException e) { + assertTrue(e.getMessage().contains("test")); + } + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBObjectifierTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBObjectifierTest.java index 46feebb1..9330f18b 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBObjectifierTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBObjectifierTest.java @@ -41,178 +41,178 @@ import org.onap.aaf.misc.env.TimeTaken; public class JU_JAXBObjectifierTest { - @Mock - JAXBumar jumar; - - @Mock - Schema schema; - - @Mock - Env env; - - TimeTaken tt,ttObjectify; - - LogTarget logT; - - @Before - public void setUp() { - initMocks(this); - tt=Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(env).start("JAXB Unmarshal", Env.XML); - Mockito.doNothing().when(tt).done(); - logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - } + @Mock + JAXBumar jumar; + + @Mock + Schema schema; + + @Mock + Env env; + + TimeTaken tt,ttObjectify; + + LogTarget logT; + + @Before + public void setUp() { + initMocks(this); + tt=Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(env).start("JAXB Unmarshal", Env.XML); + Mockito.doNothing().when(tt).done(); + logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + } - @Test + @Test public void testObjectify() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier( schema, new Class[] {this.getClass()}); - bdfObj = new JAXBObjectifier(jumar); - Mockito.doReturn(this.getClass()).when(jumar).unmarshal(logT, "test"); - bdfObj.objectify(env, "test"); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier( schema, new Class[] {this.getClass()}); + bdfObj = new JAXBObjectifier(jumar); + Mockito.doReturn(this.getClass()).when(jumar).unmarshal(logT, "test"); + bdfObj.objectify(env, "test"); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void testObjectifyException() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(jumar); - Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).unmarshal(logT, "test"); - bdfObj.objectify(env, "test"); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(jumar); + Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).unmarshal(logT, "test"); + bdfObj.objectify(env, "test"); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void testObjectifyRdr() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(new Class[] {this.getClass()}); - bdfObj = new JAXBObjectifier(jumar); - Mockito.doReturn(this.getClass()).when(jumar).unmarshal(logT, Mockito.mock(StringReader.class)); - bdfObj.objectify(env, Mockito.mock(StringReader.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(new Class[] {this.getClass()}); + bdfObj = new JAXBObjectifier(jumar); + Mockito.doReturn(this.getClass()).when(jumar).unmarshal(logT, Mockito.mock(StringReader.class)); + bdfObj.objectify(env, Mockito.mock(StringReader.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void testObjectifyRdrException() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(jumar); - StringReader sr = Mockito.mock(StringReader.class); - Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).unmarshal(logT, sr); - bdfObj.objectify(env, sr); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(jumar); + StringReader sr = Mockito.mock(StringReader.class); + Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).unmarshal(logT, sr); + bdfObj.objectify(env, sr); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void testObjectifyIs() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(jumar); - Mockito.doReturn(this.getClass()).when(jumar).unmarshal(logT, Mockito.mock(InputStream.class)); - bdfObj.objectify(env, Mockito.mock(InputStream.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(jumar); + Mockito.doReturn(this.getClass()).when(jumar).unmarshal(logT, Mockito.mock(InputStream.class)); + bdfObj.objectify(env, Mockito.mock(InputStream.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void testObjectifyIsException() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(jumar); - InputStream sr = Mockito.mock(InputStream.class); - Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).unmarshal(logT, sr); - bdfObj.objectify(env, sr); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(jumar); + InputStream sr = Mockito.mock(InputStream.class); + Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).unmarshal(logT, sr); + bdfObj.objectify(env, sr); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void testEmptyMethods() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(jumar); - bdfObj.servicePrestart(env); - bdfObj.threadPrestart(env); - bdfObj.threadDestroy(env); - bdfObj.serviceDestroy(env); - bdfObj.refresh(env); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(jumar); + bdfObj.servicePrestart(env); + bdfObj.threadPrestart(env); + bdfObj.threadDestroy(env); + bdfObj.serviceDestroy(env); + bdfObj.refresh(env); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } + } - - @Test + + @Test public void testNewInstance() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(jumar); - Object retVal = bdfObj.newInstance(); - Mockito.doThrow(new IllegalAccessException("Test Exception")).when(jumar).newInstance(); - - } catch (IllegalAccessException e) { - assertEquals("Test Exception", e.getLocalizedMessage()); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(jumar); + Object retVal = bdfObj.newInstance(); + Mockito.doThrow(new IllegalAccessException("Test Exception")).when(jumar).newInstance(); + + } catch (IllegalAccessException e) { + assertEquals("Test Exception", e.getLocalizedMessage()); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } - - @Test + + @Test public void testNewInstanceException() { - JAXBObjectifier<?> bdfObj = null; - try { - bdfObj = new JAXBObjectifier(jumar); - Mockito.doThrow(new IllegalAccessException("Test Exception")).when(jumar).newInstance(); - Object retVal = bdfObj.newInstance(); - } catch (IllegalAccessException e) { - assertEquals("Test Exception", e.getLocalizedMessage()); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (InstantiationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBObjectifier<?> bdfObj = null; + try { + bdfObj = new JAXBObjectifier(jumar); + Mockito.doThrow(new IllegalAccessException("Test Exception")).when(jumar).newInstance(); + Object retVal = bdfObj.newInstance(); + } catch (IllegalAccessException e) { + assertEquals("Test Exception", e.getLocalizedMessage()); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (InstantiationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBStringifierTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBStringifierTest.java index 7d310ae7..84415fdb 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBStringifierTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_JAXBStringifierTest.java @@ -42,145 +42,145 @@ import org.onap.aaf.misc.env.TimeTaken; public class JU_JAXBStringifierTest { - @Mock - JAXBmar jumar; - - @Mock - QName qname; - - @Mock - Env env; - - TimeTaken tt,ttstringify; - - LogTarget logT; - - @Before - public void setUp() { - initMocks(this); - tt=Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(env).start("JAXB Marshal", Env.XML); - Mockito.doNothing().when(tt).done(); - logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - } + @Mock + JAXBmar jumar; + + @Mock + QName qname; + + @Mock + Env env; + + TimeTaken tt,ttstringify; + + LogTarget logT; + + @Before + public void setUp() { + initMocks(this); + tt=Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(env).start("JAXB Marshal", Env.XML); + Mockito.doNothing().when(tt).done(); + logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + } - @Test + @Test public void teststringify() { - JAXBStringifier<JAXBmar> bdfObj = null; - try { - bdfObj = new JAXBStringifier<JAXBmar>( qname, new Class[] {this.getClass()}); - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - Mockito.doReturn(this.getClass()).when(jumar).marshal(logT, jumar, Mockito.mock(StringWriter.class), true); - bdfObj.stringify(env, jumar, true); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBStringifier<JAXBmar> bdfObj = null; + try { + bdfObj = new JAXBStringifier<JAXBmar>( qname, new Class[] {this.getClass()}); + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + Mockito.doReturn(this.getClass()).when(jumar).marshal(logT, jumar, Mockito.mock(StringWriter.class), true); + bdfObj.stringify(env, jumar, true); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void teststringifyWriter() { - JAXBStringifier<JAXBmar> bdfObj = null; - try { - bdfObj = new JAXBStringifier<JAXBmar>(new Class[] {this.getClass()}); - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - Mockito.doReturn(this.getClass()).when(jumar).marshal(logT, jumar, Mockito.mock(StringWriter.class), true); - bdfObj.stringify(env, jumar, Mockito.mock(StringWriter.class), true); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBStringifier<JAXBmar> bdfObj = null; + try { + bdfObj = new JAXBStringifier<JAXBmar>(new Class[] {this.getClass()}); + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + Mockito.doReturn(this.getClass()).when(jumar).marshal(logT, jumar, Mockito.mock(StringWriter.class), true); + bdfObj.stringify(env, jumar, Mockito.mock(StringWriter.class), true); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void teststringifyWriterException() { - JAXBStringifier<JAXBmar> bdfObj = null; - try { - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - StringWriter sr = Mockito.mock(StringWriter.class); - Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).marshal(logT, jumar, sr, true); - bdfObj.stringify(env, jumar, sr, true); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBStringifier<JAXBmar> bdfObj = null; + try { + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + StringWriter sr = Mockito.mock(StringWriter.class); + Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).marshal(logT, jumar, sr, true); + bdfObj.stringify(env, jumar, sr, true); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void teststringifyOs() { - JAXBStringifier<JAXBmar> bdfObj = null; - try { - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - Mockito.doReturn(this.getClass()).when(jumar).marshal(logT, jumar, Mockito.mock(OutputStream.class), true); - bdfObj.stringify(env, jumar, Mockito.mock(OutputStream.class), true); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBStringifier<JAXBmar> bdfObj = null; + try { + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + Mockito.doReturn(this.getClass()).when(jumar).marshal(logT, jumar, Mockito.mock(OutputStream.class), true); + bdfObj.stringify(env, jumar, Mockito.mock(OutputStream.class), true); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void teststringifyOsException() { - JAXBStringifier<JAXBmar> bdfObj = null; - try { - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - OutputStream os = Mockito.mock(OutputStream.class); - Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).marshal(logT, jumar, os, true); - bdfObj.stringify(env, jumar, os, true); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - + JAXBStringifier<JAXBmar> bdfObj = null; + try { + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + OutputStream os = Mockito.mock(OutputStream.class); + Mockito.doThrow(new JAXBException("Test Exception")).when(jumar).marshal(logT, jumar, os, true); + bdfObj.stringify(env, jumar, os, true); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } catch (JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } - - @Test + + @Test public void testEmptyMethods() { - JAXBStringifier<JAXBmar> bdfObj = null; - try { - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - bdfObj.servicePrestart(env); - bdfObj.threadPrestart(env); - bdfObj.threadDestroy(env); - bdfObj.serviceDestroy(env); - bdfObj.refresh(env); - } catch (APIException e) { - assertTrue(e.getMessage().contains("Test Exception")); - } - + JAXBStringifier<JAXBmar> bdfObj = null; + try { + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + bdfObj.servicePrestart(env); + bdfObj.threadPrestart(env); + bdfObj.threadDestroy(env); + bdfObj.serviceDestroy(env); + bdfObj.refresh(env); + } catch (APIException e) { + assertTrue(e.getMessage().contains("Test Exception")); + } + } - - @Test + + @Test public void testPretty() { - JAXBStringifier<JAXBmar> bdfObj = null; - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - Mockito.doReturn(jumar).when(jumar).pretty(true); - Object retVal = bdfObj.pretty(true); - assertTrue(retVal instanceof JAXBStringifier); + JAXBStringifier<JAXBmar> bdfObj = null; + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + Mockito.doReturn(jumar).when(jumar).pretty(true); + Object retVal = bdfObj.pretty(true); + assertTrue(retVal instanceof JAXBStringifier); } - - @Test + + @Test public void testNewInstanceException() { - JAXBStringifier<JAXBmar> bdfObj = null; - bdfObj = new JAXBStringifier<JAXBmar>(jumar); - Mockito.doReturn(jumar).when(jumar).asFragment(true); - Object retVal = bdfObj.asFragment(true); - assertTrue(retVal instanceof JAXBStringifier); - + JAXBStringifier<JAXBmar> bdfObj = null; + bdfObj = new JAXBStringifier<JAXBmar>(jumar); + Mockito.doReturn(jumar).when(jumar).asFragment(true); + Object retVal = bdfObj.asFragment(true); + assertTrue(retVal instanceof JAXBStringifier); + } } diff --git a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_StoreImplTest.java b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_StoreImplTest.java index 39d43066..22c209c2 100644 --- a/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_StoreImplTest.java +++ b/misc/env/src/test/java/org/onap/aaf/misc/env/jaxb/JU_StoreImplTest.java @@ -45,104 +45,104 @@ import org.onap.aaf.misc.env.TimeTaken; @RunWith(MockitoJUnitRunner.class) public class JU_StoreImplTest { - - @Mock - QName qname; - - @Mock - Env env; - - TimeTaken tt,ttstringify; - - LogTarget logT; - - @Before - public void setUp() { - initMocks(this); - tt=Mockito.mock(TimeTaken.class); - Mockito.doReturn(tt).when(env).start("JAXB Marshal", Env.XML); - Mockito.doNothing().when(tt).done(); - logT = Mockito.mock(LogTarget.class); - Mockito.doReturn(logT).when(env).debug(); - } + + @Mock + QName qname; + + @Mock + Env env; + + TimeTaken tt,ttstringify; + + LogTarget logT; + + @Before + public void setUp() { + initMocks(this); + tt=Mockito.mock(TimeTaken.class); + Mockito.doReturn(tt).when(env).start("JAXB Marshal", Env.XML); + Mockito.doNothing().when(tt).done(); + logT = Mockito.mock(LogTarget.class); + Mockito.doReturn(logT).when(env).debug(); + } - @Test + @Test public void testPropsFromArgs() { - StoreImpl bdfObj = new StoreImpl(); - bdfObj = new StoreImpl(""); - bdfObj.propsFromArgs(null, new String[] {"test"}); - bdfObj.propsFromArgs("test", new String[] {"test","te=st","test=1"}); - + StoreImpl bdfObj = new StoreImpl(); + bdfObj = new StoreImpl(""); + bdfObj.propsFromArgs(null, new String[] {"test"}); + bdfObj.propsFromArgs("test", new String[] {"test","te=st","test=1"}); + } - - @Test + + @Test public void testMorePropsConstructor() { - Properties props = Mockito.mock(Properties.class); - new StoreImpl(null,props); - StoreImpl bdfObj = new StoreImpl("test",props); + Properties props = Mockito.mock(Properties.class); + new StoreImpl(null,props); + StoreImpl bdfObj = new StoreImpl("test",props); } - - @Test + + @Test public void testMorePropsFileNOtExists() { - Properties props = Mockito.mock(Properties.class); - Mockito.doReturn("test").when(props).getProperty("test"); - StoreImpl bdfObj = new StoreImpl("test",props); + Properties props = Mockito.mock(Properties.class); + Mockito.doReturn("test").when(props).getProperty("test"); + StoreImpl bdfObj = new StoreImpl("test",props); } - - @Test + + @Test public void testMorePropsExists() { - Properties props = Mockito.mock(Properties.class); - Mockito.doReturn(System.getProperty("user.dir")+"/src/test/java/org/onap/aaf/misc/env/JU_StoreImplTest.java").when(props).getProperty("test"); - StoreImpl bdfObj = new StoreImpl("test",props); + Properties props = Mockito.mock(Properties.class); + Mockito.doReturn(System.getProperty("user.dir")+"/src/test/java/org/onap/aaf/misc/env/JU_StoreImplTest.java").when(props).getProperty("test"); + StoreImpl bdfObj = new StoreImpl("test",props); } - - @Test + + @Test public void testNewTransState() { - StoreImpl bdfObj = new StoreImpl(null, new String[] {}); - bdfObj.newTransState(); - } - - @Test + StoreImpl bdfObj = new StoreImpl(null, new String[] {}); + bdfObj.newTransState(); + } + + @Test public void testSlot() { - StoreImpl bdfObj = new StoreImpl("test", new String[] {}); - Slot slot = bdfObj.slot(null); - assertEquals(slot.toString(),"=0"); - slot = bdfObj.slot("test"); - assertEquals(slot.toString(),"test=1"); - } - - @Test - public void testExistingSlot() { - StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); - Slot retVal = bdfObj.existingSlot("test"); - assertNull(retVal); - } - - @Test - public void testExistingSlotNames() { - StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); - List<String> retVal = bdfObj.existingSlotNames(); - assertTrue(retVal.size()==0); - } - - @Test - public void testGet() { - StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); - Object retVal = bdfObj.get(new StaticSlot(1,"test"),qname); - assertTrue(retVal instanceof QName); - } - - @Test - public void testGetSlot() { - StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); - Object retVal = bdfObj.get(new StaticSlot(1,"test")); - assertNull(retVal); - } - - @Test - public void testExistingStaticSlotNames() { - StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); - List<String> retVal = bdfObj.existingStaticSlotNames(); - assertTrue(retVal.size()==1); - } + StoreImpl bdfObj = new StoreImpl("test", new String[] {}); + Slot slot = bdfObj.slot(null); + assertEquals(slot.toString(),"=0"); + slot = bdfObj.slot("test"); + assertEquals(slot.toString(),"test=1"); + } + + @Test + public void testExistingSlot() { + StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); + Slot retVal = bdfObj.existingSlot("test"); + assertNull(retVal); + } + + @Test + public void testExistingSlotNames() { + StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); + List<String> retVal = bdfObj.existingSlotNames(); + assertTrue(retVal.size()==0); + } + + @Test + public void testGet() { + StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); + Object retVal = bdfObj.get(new StaticSlot(1,"test"),qname); + assertTrue(retVal instanceof QName); + } + + @Test + public void testGetSlot() { + StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); + Object retVal = bdfObj.get(new StaticSlot(1,"test")); + assertNull(retVal); + } + + @Test + public void testExistingStaticSlotNames() { + StoreImpl bdfObj = new StoreImpl("test", new String[] {"test","test=1"}); + List<String> retVal = bdfObj.existingStaticSlotNames(); + assertTrue(retVal.size()==1); + } } diff --git a/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java b/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java index 85aae6f0..35d5038c 100644 --- a/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java +++ b/misc/log4j/src/main/java/org/onap/aaf/misc/env/log4j/LogFileNamer.java @@ -56,24 +56,24 @@ public class LogFileNamer { * @throws IOException
*/
public String setAppender(String appender) throws IOException {
- File f = new File(String.format(FIRST_FILE_FORMAT_STR, dir, root, appender));
- File lock = new File(f.getAbsoluteFile()+".lock");
- if(f.exists()) {
- if(lock.exists()) {
- int i = 0;
- while ((f = new File(String.format(FILE_FORMAT_STR, dir, root, appender, i))).exists() &&
- (lock = new File(f.getAbsoluteFile()+".lock")).exists()) {
- ++i;
- }
- }
- }
+ File f = new File(String.format(FIRST_FILE_FORMAT_STR, dir, root, appender));
+ File lock = new File(f.getAbsoluteFile()+".lock");
+ if(f.exists()) {
+ if(lock.exists()) {
+ int i = 0;
+ while ((f = new File(String.format(FILE_FORMAT_STR, dir, root, appender, i))).exists() &&
+ (lock = new File(f.getAbsoluteFile()+".lock")).exists()) {
+ ++i;
+ }
+ }
+ }
try {
- lock.createNewFile();
- lock.deleteOnExit();
- f.createNewFile();
+ lock.createNewFile();
+ lock.deleteOnExit();
+ f.createNewFile();
} catch (IOException e) {
- throw new IOException("Cannot create file '" + f.getCanonicalPath() + '\'', e);
+ throw new IOException("Cannot create file '" + f.getCanonicalPath() + '\'', e);
}
System.setProperty("LOG4J_FILENAME_" + appender, f.getCanonicalPath());
return appender;
diff --git a/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java b/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java index 8657e1d6..1aaeb7fb 100644 --- a/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java +++ b/misc/log4j/src/test/java/org/onap/aaf/misc/env/log4j/JU_LogFileNamerTest.java @@ -38,55 +38,55 @@ public class JU_LogFileNamerTest { } private void cleanup(String name) { -// System.out.println("XXXX" + dir.getAbsolutePath()); - for(File f : dir.listFiles(new FilenameFilter() { - @Override - public boolean accept(File dir, String name) { - return name.contains(name) && name.endsWith(".log"); - } - })) { -// System.out.println("Deleting " + f.getAbsolutePath()); - f.delete(); - }; +// System.out.println("XXXX" + dir.getAbsolutePath()); + for(File f : dir.listFiles(new FilenameFilter() { + @Override + public boolean accept(File dir, String name) { + return name.contains(name) && name.endsWith(".log"); + } + })) { +// System.out.println("Deleting " + f.getAbsolutePath()); + f.delete(); + }; } @Test public void test() throws IOException { - String name = "Append"; - try { - LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), "log"); - assertEquals(logFileNamer, logFileNamer.noPID()); - - logFileNamer.setAppender(name); - assertEquals(System.getProperty("LOG4J_FILENAME_Append"), - dir.getCanonicalFile() + File.separator + "log-" + name + ".log"); - - logFileNamer.setAppender(name); - assertEquals(System.getProperty("LOG4J_FILENAME_Append"), - dir.getCanonicalFile() + File.separator + "log-" + name + ".0.log"); - } finally { - cleanup("log-" + name); - } + String name = "Append"; + try { + LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), "log"); + assertEquals(logFileNamer, logFileNamer.noPID()); + + logFileNamer.setAppender(name); + assertEquals(System.getProperty("LOG4J_FILENAME_Append"), + dir.getCanonicalFile() + File.separator + "log-" + name + ".log"); + + logFileNamer.setAppender(name); + assertEquals(System.getProperty("LOG4J_FILENAME_Append"), + dir.getCanonicalFile() + File.separator + "log-" + name + ".0.log"); + } finally { + cleanup("log-" + name); + } } @Test public void testBlankRoot() throws IOException { - String name = "Different"; - try { - LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), ""); - assertEquals(logFileNamer, logFileNamer.noPID()); - - logFileNamer.setAppender(name); - assertEquals(System.getProperty("LOG4J_FILENAME_Different"), - dir.getCanonicalPath() + File.separator + name + ".log"); - - logFileNamer.setAppender(name); - assertEquals(System.getProperty("LOG4J_FILENAME_Different"), - dir.getCanonicalPath() + File.separator + name + ".0.log"); - } finally { - cleanup(name); - } + String name = "Different"; + try { + LogFileNamer logFileNamer = new LogFileNamer(dir.getCanonicalPath(), ""); + assertEquals(logFileNamer, logFileNamer.noPID()); + + logFileNamer.setAppender(name); + assertEquals(System.getProperty("LOG4J_FILENAME_Different"), + dir.getCanonicalPath() + File.separator + name + ".log"); + + logFileNamer.setAppender(name); + assertEquals(System.getProperty("LOG4J_FILENAME_Different"), + dir.getCanonicalPath() + File.separator + name + ".0.log"); + } finally { + cleanup(name); + } } } 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 bb590e1c..36ebde68 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 @@ -60,7 +60,7 @@ public class RosettaData<T> implements Data<T>{ //Added for junits void setSaved(Saved saved) { - this.saved = saved; + this.saved = saved; } // // @Override diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/JU_ParseException.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/JU_ParseException.java index 1eb55916..1a31b0fb 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/JU_ParseException.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/JU_ParseException.java @@ -26,24 +26,24 @@ import org.junit.Test; public class JU_ParseException { - @Test - public void test() { - ParseException pe = new ParseException(); - } - @Test - public void test1() { - ParseException pe = new ParseException("exception"); - } - @Test - public void test2() { - ParseException pe = new ParseException(new NullPointerException("exception")); - } - @Test - public void test3() { - ParseException pe = new ParseException("exception",new NullPointerException("exception")); - } + @Test + public void test() { + ParseException pe = new ParseException(); + } + @Test + public void test1() { + ParseException pe = new ParseException("exception"); + } + @Test + public void test2() { + ParseException pe = new ParseException(new NullPointerException("exception")); + } + @Test + public void test3() { + ParseException pe = new ParseException("exception",new NullPointerException("exception")); + } - - + + } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaData.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaData.java index cbf7e2dc..9ab3b258 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaData.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaData.java @@ -56,608 +56,608 @@ import org.onap.aaf.misc.rosetta.Saved; public class JU_RosettaData { - @Mock - Env env; - - @Mock - RosettaDF df; - - @Mock - JAXBmar bmar; - - @Mock - Saved saved; - - @Before - public void setUp() { - initMocks(this); - } - - @Test - public void testLoad() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - StringReader sr= Mockito.mock(StringReader.class); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(sr,(Writer)null,inxml); - - rosettaObj = rosettaObj.load(sr); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testLoadException() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - rosettaObj = rosettaObj.load(Mockito.mock(StringReader.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("NullPointerException")); - } - } - - @Test - public void testLoadIs() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - InputStream sr= Mockito.mock(InputStream.class); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new InputStreamReader(sr),(Writer)null,inxml); - - rosettaObj = rosettaObj.load(sr); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testLoadIsException() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - rosettaObj = rosettaObj.load(Mockito.mock(InputStream.class)); - } catch (APIException e) { - assertTrue(e.getMessage().contains("NullPointerException")); - } - } - - @Test - public void testLoadStr() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - - rosettaObj = rosettaObj.load("test"); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testLoadStrJson() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.JSON); - rosettaObj.setSaved(saved); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.JSON); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - - rosettaObj = rosettaObj.load("test"); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testLoadStrException() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - rosettaObj = rosettaObj.load("test"); - } catch (APIException e) { - assertTrue(e.getMessage().contains("NullPointerException")); - } - } - - @Test - public void testLoadT() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - df.jaxMar = Mockito.mock(JAXBmar.class); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - - rosettaObj = rosettaObj.load(bmar); - df.marshal = null; - rosettaObj = rosettaObj.load(bmar); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testLoadTMarshalNull() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - df.jaxMar = Mockito.mock(JAXBmar.class); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - df.marshal = Mockito.mock(Marshal.class);; - rosettaObj = rosettaObj.load(bmar); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testLoadTException() { - RosettaData rosettaObj = new RosettaData(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - rosettaObj = rosettaObj.load(bmar); - } catch (APIException e) { - assertTrue(e.getMessage().contains("NullPointerException")); - } - } - - @Test - public void testGetEvents() { - RosettaData rosettaObj = new RosettaData(env, df); - Saved saved = rosettaObj.getEvents(); - assertEquals("Rosetta Saved", saved.logName()); - } - - @Test - public void testAsObject() { - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - try { - Out outxml = Mockito.mock(OutXML.class); - Mockito.doReturn(outxml).when(df).getOut(Data.TYPE.XML); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - df.jaxMar = Mockito.mock(JAXBmar.class); - df.jaxUmar = Mockito.mock(JAXBumar.class); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",0); - LogTarget lt = Mockito.mock(LogTarget.class); - Mockito.doReturn( lt).when(env).debug(); - Mockito.doNothing().when(saved).extract(null,new StringWriter(),saved); - Mockito.doReturn(bmar).when(df.jaxUmar).unmarshal(lt,""); - - bmar = rosettaObj.asObject(); - - } catch (APIException | IOException | ParseException | JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testAsObjectException() { - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - try { - Out outxml = Mockito.mock(OutXML.class); - Mockito.doReturn(outxml).when(df).getOut(Data.TYPE.XML); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - df.jaxMar = Mockito.mock(JAXBmar.class); - df.jaxUmar = Mockito.mock(JAXBumar.class); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",0); - LogTarget lt = Mockito.mock(LogTarget.class); - Mockito.doReturn( lt).when(env).debug(); - Mockito.doThrow(new IOException("test Exception")).when(saved).extract(null,new StringWriter(),saved); - Mockito.doThrow(new JAXBException("test Exception")).when(df.jaxUmar).unmarshal(lt,""); - - bmar = rosettaObj.asObject(); - - } catch (APIException | IOException | ParseException | JAXBException e) { - assertTrue(e.getMessage().contains("test Exception")); - } - } + @Mock + Env env; + + @Mock + RosettaDF df; + + @Mock + JAXBmar bmar; + + @Mock + Saved saved; + + @Before + public void setUp() { + initMocks(this); + } + + @Test + public void testLoad() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + StringReader sr= Mockito.mock(StringReader.class); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(sr,(Writer)null,inxml); + + rosettaObj = rosettaObj.load(sr); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testLoadException() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + rosettaObj = rosettaObj.load(Mockito.mock(StringReader.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("NullPointerException")); + } + } + + @Test + public void testLoadIs() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + InputStream sr= Mockito.mock(InputStream.class); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new InputStreamReader(sr),(Writer)null,inxml); + + rosettaObj = rosettaObj.load(sr); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testLoadIsException() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + rosettaObj = rosettaObj.load(Mockito.mock(InputStream.class)); + } catch (APIException e) { + assertTrue(e.getMessage().contains("NullPointerException")); + } + } + + @Test + public void testLoadStr() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + + rosettaObj = rosettaObj.load("test"); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testLoadStrJson() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.JSON); + rosettaObj.setSaved(saved); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.JSON); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + + rosettaObj = rosettaObj.load("test"); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testLoadStrException() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + rosettaObj = rosettaObj.load("test"); + } catch (APIException e) { + assertTrue(e.getMessage().contains("NullPointerException")); + } + } + + @Test + public void testLoadT() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + df.jaxMar = Mockito.mock(JAXBmar.class); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + + rosettaObj = rosettaObj.load(bmar); + df.marshal = null; + rosettaObj = rosettaObj.load(bmar); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testLoadTMarshalNull() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + df.jaxMar = Mockito.mock(JAXBmar.class); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + df.marshal = Mockito.mock(Marshal.class);; + rosettaObj = rosettaObj.load(bmar); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testLoadTException() { + RosettaData rosettaObj = new RosettaData(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + rosettaObj = rosettaObj.load(bmar); + } catch (APIException e) { + assertTrue(e.getMessage().contains("NullPointerException")); + } + } + + @Test + public void testGetEvents() { + RosettaData rosettaObj = new RosettaData(env, df); + Saved saved = rosettaObj.getEvents(); + assertEquals("Rosetta Saved", saved.logName()); + } + + @Test + public void testAsObject() { + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + try { + Out outxml = Mockito.mock(OutXML.class); + Mockito.doReturn(outxml).when(df).getOut(Data.TYPE.XML); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + df.jaxMar = Mockito.mock(JAXBmar.class); + df.jaxUmar = Mockito.mock(JAXBumar.class); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",0); + LogTarget lt = Mockito.mock(LogTarget.class); + Mockito.doReturn( lt).when(env).debug(); + Mockito.doNothing().when(saved).extract(null,new StringWriter(),saved); + Mockito.doReturn(bmar).when(df.jaxUmar).unmarshal(lt,""); + + bmar = rosettaObj.asObject(); + + } catch (APIException | IOException | ParseException | JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testAsObjectException() { + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + try { + Out outxml = Mockito.mock(OutXML.class); + Mockito.doReturn(outxml).when(df).getOut(Data.TYPE.XML); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + df.jaxMar = Mockito.mock(JAXBmar.class); + df.jaxUmar = Mockito.mock(JAXBumar.class); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",0); + LogTarget lt = Mockito.mock(LogTarget.class); + Mockito.doReturn( lt).when(env).debug(); + Mockito.doThrow(new IOException("test Exception")).when(saved).extract(null,new StringWriter(),saved); + Mockito.doThrow(new JAXBException("test Exception")).when(df.jaxUmar).unmarshal(lt,""); + + bmar = rosettaObj.asObject(); + + } catch (APIException | IOException | ParseException | JAXBException e) { + assertTrue(e.getMessage().contains("test Exception")); + } + } - @Test - public void testAsString() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - - String retVal = rosettaObj.asString(); - assertTrue("".equals(retVal)); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testAsStringJson() { - TYPE type = TYPE.JSON; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.JSON); - rosettaObj.setSaved(saved); - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); - - String retVal = rosettaObj.asString(); - assertTrue("".equals(retVal)); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - @Test - public void testToXml() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - - rosettaObj = rosettaObj.load("test"); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(OutputStream.class)); - - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testToJson() { - TYPE type = TYPE.JSON; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.JSON); - rosettaObj.setSaved(saved); - - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.JSON); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - - rosettaObj = rosettaObj.load("test"); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); - RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(OutputStream.class)); - - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testTo() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(OutputStream.class)); - - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testToWriterXml() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - - rosettaObj = rosettaObj.load("test"); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(StringWriter.class)); - - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testToWriterJson() { - TYPE type = TYPE.JSON; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.JSON); - rosettaObj.setSaved(saved); - - try { - InXML inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.JSON); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); - Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); - - rosettaObj = rosettaObj.load("test"); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); - RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(StringWriter.class)); - - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testToWriter() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj = rosettaObj.in(Data.TYPE.XML); - rosettaObj.setSaved(saved); - - try { - Out outxml = Mockito.mock(OutXML.class); - - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(StringWriter.class)); - - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testGetTypeClass() { - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - rosettaObj.getTypeClass(); - } - - @Test - public void testDirect() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - try { - Out outxml = Mockito.mock(OutXML.class); - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - rosettaObj.direct(Mockito.mock(InputStream.class), Mockito.mock(OutputStream.class)); - } catch (APIException | IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testDirectException() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - Mockito.doReturn(type).when(df).getInType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - InXML inxml = null; - - inxml = Mockito.mock(InXML.class); - Mockito.doReturn(inxml).when(df).getIn(type); - - - StringReader is = Mockito.mock(StringReader.class); - StringWriter os= Mockito.mock(StringWriter.class); - try { - Out outxml = Mockito.mock(OutXML.class); - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - Mockito.doThrow( new IOException("testException")).when(outxml).extract(is, os, inxml, true); - - rosettaObj.direct(is,os, true); - } catch (APIException | IOException | ParseException e) { - // TODO Auto-generated catch block - assertTrue(e.getMessage().contains("testException")); - } - } - - @Test - public void testDirectT() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - try { - Out outxml = Mockito.mock(OutXML.class); - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + @Test + public void testAsString() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + + String retVal = rosettaObj.asString(); + assertTrue("".equals(retVal)); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testAsStringJson() { + TYPE type = TYPE.JSON; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.JSON); + rosettaObj.setSaved(saved); + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); + + String retVal = rosettaObj.asString(); + assertTrue("".equals(retVal)); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + @Test + public void testToXml() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + + rosettaObj = rosettaObj.load("test"); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(OutputStream.class)); + + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testToJson() { + TYPE type = TYPE.JSON; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.JSON); + rosettaObj.setSaved(saved); + + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.JSON); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + + rosettaObj = rosettaObj.load("test"); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); + RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(OutputStream.class)); + + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testTo() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(OutputStream.class)); + + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testToWriterXml() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.XML); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + + rosettaObj = rosettaObj.load("test"); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(StringWriter.class)); + + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testToWriterJson() { + TYPE type = TYPE.JSON; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.JSON); + rosettaObj.setSaved(saved); + + try { + InXML inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(Data.TYPE.JSON); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(inxml).start(env); + Mockito.doNothing().when(saved).extract(new StringReader("test"),(Writer)null,inxml); + + rosettaObj = rosettaObj.load("test"); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); + RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(StringWriter.class)); + + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testToWriter() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj = rosettaObj.in(Data.TYPE.XML); + rosettaObj.setSaved(saved); + + try { + Out outxml = Mockito.mock(OutXML.class); + + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + RosettaData<JAXBmar> retVal = rosettaObj.to(Mockito.mock(StringWriter.class)); + + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testGetTypeClass() { + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + rosettaObj.getTypeClass(); + } + + @Test + public void testDirect() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + try { + Out outxml = Mockito.mock(OutXML.class); + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + rosettaObj.direct(Mockito.mock(InputStream.class), Mockito.mock(OutputStream.class)); + } catch (APIException | IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testDirectException() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + Mockito.doReturn(type).when(df).getInType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + InXML inxml = null; + + inxml = Mockito.mock(InXML.class); + Mockito.doReturn(inxml).when(df).getIn(type); + + + StringReader is = Mockito.mock(StringReader.class); + StringWriter os= Mockito.mock(StringWriter.class); + try { + Out outxml = Mockito.mock(OutXML.class); + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + Mockito.doThrow( new IOException("testException")).when(outxml).extract(is, os, inxml, true); + + rosettaObj.direct(is,os, true); + } catch (APIException | IOException | ParseException e) { + // TODO Auto-generated catch block + assertTrue(e.getMessage().contains("testException")); + } + } + + @Test + public void testDirectT() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + try { + Out outxml = Mockito.mock(OutXML.class); + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - df.jaxMar = Mockito.mock(JAXBmar.class); - LogTarget lt = Mockito.mock(LogTarget.class); - Mockito.doReturn( lt).when(env).debug(); - Mockito.doReturn(bmar).when(df.jaxMar).marshal(lt,bmar, new StringWriter(),true); - - rosettaObj.direct(bmar, Mockito.mock(StringWriter.class), true); - df.marshal =Mockito.mock(Marshal.class);; - rosettaObj.direct(bmar, Mockito.mock(StringWriter.class), true); - } catch (APIException | IOException | JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testDirectTOS() { - TYPE type = TYPE.XML; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - try { - Out outxml = Mockito.mock(OutXML.class); - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); + df.jaxMar = Mockito.mock(JAXBmar.class); + LogTarget lt = Mockito.mock(LogTarget.class); + Mockito.doReturn( lt).when(env).debug(); + Mockito.doReturn(bmar).when(df.jaxMar).marshal(lt,bmar, new StringWriter(),true); + + rosettaObj.direct(bmar, Mockito.mock(StringWriter.class), true); + df.marshal =Mockito.mock(Marshal.class);; + rosettaObj.direct(bmar, Mockito.mock(StringWriter.class), true); + } catch (APIException | IOException | JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testDirectTOS() { + TYPE type = TYPE.XML; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + try { + Out outxml = Mockito.mock(OutXML.class); + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.XML).when(df).logType(Data.TYPE.XML); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",2); - df.jaxMar = Mockito.mock(JAXBmar.class); - LogTarget lt = Mockito.mock(LogTarget.class); - Mockito.doReturn( lt).when(env).debug(); - Mockito.doReturn(bmar).when(df.jaxMar).marshal(lt,bmar, new StringWriter(),true); - - rosettaObj.direct(bmar, Mockito.mock(OutputStream.class), true); - df.marshal =Mockito.mock(Marshal.class);; - rosettaObj.direct(bmar, Mockito.mock(OutputStream.class), true); - } catch (APIException | IOException | JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testDirectTOSJson() { - TYPE type = TYPE.JSON; - Mockito.doReturn(type).when(df).getOutType(); - RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); - try { - Out outxml = Mockito.mock(OutXML.class); - Mockito.doReturn(outxml).when(df).getOut(type); - Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); - Mockito.doReturn("test").when(outxml).logName(); - Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); + df.jaxMar = Mockito.mock(JAXBmar.class); + LogTarget lt = Mockito.mock(LogTarget.class); + Mockito.doReturn( lt).when(env).debug(); + Mockito.doReturn(bmar).when(df.jaxMar).marshal(lt,bmar, new StringWriter(),true); + + rosettaObj.direct(bmar, Mockito.mock(OutputStream.class), true); + df.marshal =Mockito.mock(Marshal.class);; + rosettaObj.direct(bmar, Mockito.mock(OutputStream.class), true); + } catch (APIException | IOException | JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testDirectTOSJson() { + TYPE type = TYPE.JSON; + Mockito.doReturn(type).when(df).getOutType(); + RosettaData<JAXBmar> rosettaObj = new RosettaData<JAXBmar>(env, df); + try { + Out outxml = Mockito.mock(OutXML.class); + Mockito.doReturn(outxml).when(df).getOut(type); + Mockito.doReturn(Env.JSON).when(df).logType(Data.TYPE.JSON); + Mockito.doReturn("test").when(outxml).logName(); + Mockito.doReturn( Mockito.mock(TimeTaken.class)).when(env).start("test",4); - df.jaxMar = Mockito.mock(JAXBmar.class); - LogTarget lt = Mockito.mock(LogTarget.class); - Mockito.doReturn( lt).when(env).debug(); - Mockito.doReturn(bmar).when(df.jaxMar).marshal(lt,bmar, new StringWriter(),true); - - rosettaObj.direct(bmar, Mockito.mock(OutputStream.class), true); - } catch (APIException | IOException | JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - + df.jaxMar = Mockito.mock(JAXBmar.class); + LogTarget lt = Mockito.mock(LogTarget.class); + Mockito.doReturn( lt).when(env).debug(); + Mockito.doReturn(bmar).when(df.jaxMar).marshal(lt,bmar, new StringWriter(),true); + + rosettaObj.direct(bmar, Mockito.mock(OutputStream.class), true); + } catch (APIException | IOException | JAXBException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaEnv.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaEnv.java index b5889b45..c8771519 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaEnv.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/env/JU_RosettaEnv.java @@ -41,58 +41,58 @@ import org.onap.aaf.misc.rosetta.Saved; public class JU_RosettaEnv { - @Before - public void setUp() { - initMocks(this); - } - - @Test - public void testNewDataFactoryClass() { - RosettaEnv rosettaObj = new RosettaEnv(); - try { - Object retVal = rosettaObj.newDataFactory(Api.class); - assertTrue(retVal instanceof RosettaDF); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testNewDataFactorySchema() { - RosettaEnv rosettaObj = new RosettaEnv(Mockito.mock(Applet.class),"test"); - try { - Object retVal = rosettaObj.newDataFactory(Mockito.mock(Schema.class),Api.class); - assertTrue(retVal instanceof RosettaDF); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testNewDataFactoryQname() { - RosettaEnv rosettaObj = new RosettaEnv(new String[] {"test"}); - rosettaObj = new RosettaEnv(Mockito.mock(Properties.class)); - try { - Object retVal = rosettaObj.newDataFactory(Mockito.mock(QName.class),Api.class); - assertTrue(retVal instanceof RosettaDF); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - @Test - public void testNewDataFactoryQnameSchema() { - RosettaEnv rosettaObj = new RosettaEnv("test", new String[] {"test"}); - rosettaObj = new RosettaEnv("test", Mockito.mock(Properties.class)); - try { - Object retVal = rosettaObj.newDataFactory(Mockito.mock(Schema.class),Mockito.mock(QName.class),Api.class); - assertTrue(retVal instanceof RosettaDF); - } catch (APIException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } + @Before + public void setUp() { + initMocks(this); + } + + @Test + public void testNewDataFactoryClass() { + RosettaEnv rosettaObj = new RosettaEnv(); + try { + Object retVal = rosettaObj.newDataFactory(Api.class); + assertTrue(retVal instanceof RosettaDF); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testNewDataFactorySchema() { + RosettaEnv rosettaObj = new RosettaEnv(Mockito.mock(Applet.class),"test"); + try { + Object retVal = rosettaObj.newDataFactory(Mockito.mock(Schema.class),Api.class); + assertTrue(retVal instanceof RosettaDF); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testNewDataFactoryQname() { + RosettaEnv rosettaObj = new RosettaEnv(new String[] {"test"}); + rosettaObj = new RosettaEnv(Mockito.mock(Properties.class)); + try { + Object retVal = rosettaObj.newDataFactory(Mockito.mock(QName.class),Api.class); + assertTrue(retVal instanceof RosettaDF); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + @Test + public void testNewDataFactoryQnameSchema() { + RosettaEnv rosettaObj = new RosettaEnv("test", new String[] {"test"}); + rosettaObj = new RosettaEnv("test", Mockito.mock(Properties.class)); + try { + Object retVal = rosettaObj.newDataFactory(Mockito.mock(Schema.class),Mockito.mock(QName.class),Api.class); + assertTrue(retVal instanceof RosettaDF); + } catch (APIException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } diff --git a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/marshal/JU_FieldBlob.java b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/marshal/JU_FieldBlob.java index c28e83d5..5b7875f7 100644 --- a/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/marshal/JU_FieldBlob.java +++ b/misc/rosetta/src/test/java/org/onap/aaf/misc/rosetta/marshal/JU_FieldBlob.java @@ -26,24 +26,24 @@ import org.onap.aaf.misc.env.jaxb.JAXBumar; public class JU_FieldBlob { - class FieldBlobImpl extends FieldBlob{ + class FieldBlobImpl extends FieldBlob{ - public FieldBlobImpl(String name) { - super(name); - // TODO Auto-generated constructor stub - } + public FieldBlobImpl(String name) { + super(name); + // TODO Auto-generated constructor stub + } - @Override - protected byte[] data(Object t) { - // TODO Auto-generated method stub - return null; - } - - } - @Test - public void testData() { - FieldBlob<JAXBumar> obj = new FieldBlobImpl("test"); - obj.data(Mockito.mock(JAXBumar.class), new StringBuilder()); - } + @Override + protected byte[] data(Object t) { + // TODO Auto-generated method stub + return null; + } + + } + @Test + public void testData() { + FieldBlob<JAXBumar> obj = new FieldBlobImpl("test"); + obj.data(Mockito.mock(JAXBumar.class), new StringBuilder()); + } } |