aboutsummaryrefslogtreecommitdiffstats
path: root/aai-core
diff options
context:
space:
mode:
Diffstat (limited to 'aai-core')
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java42
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java1
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java164
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/dbgen/DbMeth.java3643
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResource.java675
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResourceKey.java103
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResources.java86
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/ingestModel/ConvertXmlToJsonMoxyOxm.java105
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java82
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/ingestModel/DbMaps.java64
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelListener.java83
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelMoxyOxm.java862
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java11
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java15
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java7
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java8
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java23
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java4
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java (renamed from aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResourceKeys.java)38
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java6
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java14
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java4
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java29
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/util/AAITxnLog.java22
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java (renamed from aai-core/src/main/java/org/openecomp/aai/util/AAIUtils.java)46
-rw-r--r--aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java664
-rw-r--r--aai-core/src/test/resources/bundleconfig-local/etc/auth/aai_policy.json37
27 files changed, 307 insertions, 6531 deletions
diff --git a/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java b/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java
new file mode 100644
index 00000000..b5ebcb91
--- /dev/null
+++ b/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java
@@ -0,0 +1,42 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.aai.auth.exceptions;
+
+import org.openecomp.aai.exceptions.AAIException;
+
+public class AAIUnrecognizedFunctionException extends AAIException {
+
+ private static final long serialVersionUID = 3297064867724071290L;
+
+ public AAIUnrecognizedFunctionException() {}
+
+ public AAIUnrecognizedFunctionException(String message) {
+ super("AAI_3012", message);
+ }
+
+ public AAIUnrecognizedFunctionException(Throwable cause) {
+ super("AAI_3012",cause);
+ }
+
+ public AAIUnrecognizedFunctionException(String message, Throwable cause) {
+ super("AAI_3012", cause, message);
+ }
+}
diff --git a/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java b/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java
index 3c452a88..2b335e17 100644
--- a/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java
+++ b/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java
@@ -34,5 +34,6 @@ public class AAIProperties {
public static final Version LATEST = Version.v10;
public static final Integer MAXIMUM_DEPTH = 10000;
public static final String LINKED = "linked";
+ public static final String DB_ALIAS_SUFFIX = "-local";
}
diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java
index 18f43ba8..d1480d15 100644
--- a/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java
+++ b/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java
@@ -26,35 +26,37 @@ import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
-import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
-import java.util.TimeZone;
import java.util.UUID;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
-
+import org.openecomp.aai.db.props.AAIProperties;
import org.openecomp.aai.dbmap.AAIGraph;
import org.openecomp.aai.exceptions.AAIException;
-import org.openecomp.aai.ingestModel.DbMaps;
-import org.openecomp.aai.ingestModel.IngestModelMoxyOxm;
+import org.openecomp.aai.introspection.Introspector;
+import org.openecomp.aai.introspection.Loader;
+import org.openecomp.aai.introspection.LoaderFactory;
+import org.openecomp.aai.introspection.ModelType;
+import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException;
import org.openecomp.aai.logging.ErrorLogHelper;
import org.openecomp.aai.util.AAIConfig;
import org.openecomp.aai.util.AAIConstants;
+import org.openecomp.aai.util.FormatDate;
+
import com.att.eelf.configuration.Configuration;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
@@ -88,6 +90,7 @@ public class DataGrooming {
Boolean doAutoFix = false;
Boolean edgesOnlyFlag = false;
Boolean dontFixOrphansFlag = false;
+ Boolean skipHostCheck = false;
Boolean singleCommits = false;
Boolean dupeCheckOff = false;
Boolean dupeFixOn = false;
@@ -114,9 +117,8 @@ public class DataGrooming {
String prevFileName = "";
dupeGrpsDeleted = 0;
- SimpleDateFormat d = new SimpleDateFormat("yyyyMMddHHmm");
- d.setTimeZone(TimeZone.getTimeZone("GMT"));
- String dteStr = d.format(new Date()).toString();
+ FormatDate fd = new FormatDate("yyyyMMddHHmm", "GMT");
+ String dteStr = fd.getDateTime();
String groomOutFileName = "dataGrooming." + dteStr + ".out";
if (args.length > 0) {
@@ -127,6 +129,8 @@ public class DataGrooming {
edgesOnlyFlag = true;
} else if (thisArg.equals("-autoFix")) {
doAutoFix = true;
+ } else if (thisArg.equals("-skipHostCheck")) {
+ skipHostCheck = true;
} else if (thisArg.equals("-dontFixOrphans")) {
dontFixOrphansFlag = true;
} else if (thisArg.equals("-singleCommits")) {
@@ -186,14 +190,12 @@ public class DataGrooming {
}
- IngestModelMoxyOxm moxyMod = new IngestModelMoxyOxm();
try {
- ArrayList <String> defaultVerLst = new ArrayList <> ();
- defaultVerLst.add( AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP) );
- moxyMod.init( defaultVerLst, false);
+ LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST);
+
}
catch (Exception ex){
- LOGGER.error("ERROR - Could not do the moxyMod.init()", ex);
+ LOGGER.error("ERROR - Could not create loader", ex);
System.exit(1);
}
@@ -239,9 +241,7 @@ public class DataGrooming {
System.exit(0);
}
- d = new SimpleDateFormat("yyyyMMddHHmm");
- d.setTimeZone(TimeZone.getTimeZone("GMT"));
- dteStr = d.format(new Date()).toString();
+ dteStr = fd.getDateTime();
String secondGroomOutFileName = "dataGrooming." + dteStr
+ ".out";
LOGGER.info(" Now, call doTheGrooming() a second time and pass in the name of the file "
@@ -342,9 +342,6 @@ public class DataGrooming {
deleteCandidateList = new LinkedHashSet<>();
}
- SimpleDateFormat d = new SimpleDateFormat("yyyyMMddHHmm");
- d.setTimeZone(TimeZone.getTimeZone("GMT"));
-
String fullOutputFileName = targetDir + AAIConstants.AAI_FILESEP
+ groomOutFileName;
File groomOutFile = new File(fullOutputFileName);
@@ -394,11 +391,10 @@ public class DataGrooming {
HashMap<String, String> emptyVertexHash = new HashMap<String, String>();
HashMap<String, TitanVertex> ghostNodeHash = new HashMap<String, TitanVertex>();
ArrayList<String> dupeGroups = new ArrayList<>();
-
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
- Iterator<String> nodeMapKPropsIterator = dbMaps.NodeKeyProps.keySet().iterator();
+ Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST);
+
+ Set<Entry<String, Introspector>> entrySet = loader.getAllObjects().entrySet();
String ntList = "";
LOGGER.info(" Starting DataGrooming Processing ");
@@ -407,8 +403,8 @@ public class DataGrooming {
LOGGER.info(" NOTE >> Skipping Node processing as requested. Will only process Edges. << ");
}
else {
- while (nodeMapKPropsIterator.hasNext()) {
- String nType = nodeMapKPropsIterator.next();
+ for (Entry<String, Introspector> entry : entrySet) {
+ String nType = entry.getKey();
int thisNtCount = 0;
int thisNtDeleteCount = 0;
LOGGER.debug(" > Look at : [" + nType + "] ...");
@@ -416,19 +412,10 @@ public class DataGrooming {
// Get a collection of the names of the key properties for this nodeType to use later
// Determine what the key fields are for this nodeType
- Collection <String> keyProps = new ArrayList <>();
- if( dbMaps.NodeKeyProps.containsKey(nType) ){
- keyProps = dbMaps.NodeKeyProps.get(nType);
- }
- else {
- throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + nType + ")");
- }
+ Collection <String> keyProps = entry.getValue().getKeys();
// Get the types of nodes that this nodetype depends on for uniqueness (if any)
- Collection <String> depNodeTypes = new ArrayList <>();
- if( dbMaps.NodeDependencies.containsKey(nType) ){
- depNodeTypes = dbMaps.NodeDependencies.get(nType);
- }
+ Collection <String> depNodeTypes = loader.introspectorFromName(nType).getDependentOn();
// Loop through all the nodes of this Node type
int lastShownForNt = 0;
@@ -595,7 +582,7 @@ public class DataGrooming {
List<String> tmpDupeGroups = checkAndProcessDupes(
TRANSID, FROMAPPID, g, version,
nType, secondGetList, dupeFixOn,
- deleteCandidateList, singleCommits, dupeGroups, dbMaps);
+ deleteCandidateList, singleCommits, dupeGroups, loader);
Iterator<String> dIter = tmpDupeGroups.iterator();
while (dIter.hasNext()) {
// Add in any newly found dupes to our running list
@@ -732,7 +719,7 @@ public class DataGrooming {
Object ob = vIn.<Object>property("aai-node-type").orElse(null);
if (ob != null) {
vNtI = ob.toString();
- keysMissing = anyKeyFieldsMissing(vNtI, vIn, dbMaps);
+ keysMissing = anyKeyFieldsMissing(vNtI, vIn, loader);
}
ob = vIn.id();
long vIdLong = 0L;
@@ -845,7 +832,7 @@ public class DataGrooming {
if (ob != null) {
vNtO = ob.toString();
keysMissing = anyKeyFieldsMissing(vNtO,
- vOut, dbMaps);
+ vOut, loader);
}
ob = vOut.id();
long vIdLong = 0L;
@@ -1315,11 +1302,13 @@ public class DataGrooming {
* @param v the v
* @return the boolean
*/
- private static Boolean anyKeyFieldsMissing(String nType, Vertex v, DbMaps dbMaps) {
+ private static Boolean anyKeyFieldsMissing(String nType, Vertex v, Loader loader) {
try {
- if( nType != null && !nType.trim().equals("")
- && !dbMaps.NodeKeyProps.containsKey(nType) ){
+ Introspector obj = null;
+ try {
+ obj = loader.introspectorFromName(nType);
+ } catch (AAIUnknownObjectException e) {
// They gave us a non-empty nodeType but our NodeKeyProps does
// not have data for it. Since we do not know what the
// key params are for this type of node, we will just
@@ -1327,19 +1316,11 @@ public class DataGrooming {
String emsg = " -- WARNING -- Unrecognized nodeType: [" + nType
+ "]. We cannot determine required keys for this nType. ";
// NOTE - this will be caught below and a "false" returned
- throw new AAIException("AAI_6121", emsg);
- }
+ throw new AAIException("AAI_6121", emsg);
+ }
// Determine what the key fields are for this nodeType
- Collection <String> keyPropNamesColl = new ArrayList <>();
- if( dbMaps.NodeKeyProps.containsKey(nType) ){
- keyPropNamesColl = dbMaps.NodeKeyProps.get(nType);
- }
- else {
- // NOTE - this will be caught below and a "false" returned
- throw new AAIException("AAI_6121", "Definition of key props not found for nodeType = " + nType + ")");
- }
-
+ Collection <String> keyPropNamesColl = obj.getKeys();
Iterator<String> keyPropI = keyPropNamesColl.iterator();
while (keyPropI.hasNext()) {
String propName = keyPropI.next();
@@ -1422,7 +1403,7 @@ public class DataGrooming {
*/
public static TitanVertex getPreferredDupe(String transId,
String fromAppId, TitanTransaction g,
- ArrayList<TitanVertex> dupeVertexList, String ver, DbMaps dbMaps)
+ ArrayList<TitanVertex> dupeVertexList, String ver, Loader loader)
throws AAIException {
// This method assumes that it is being passed a List of vertex objects
@@ -1447,7 +1428,7 @@ public class DataGrooming {
for (int i = 1; i < listSize; i++) {
TitanVertex vtxB = (TitanVertex) dupeVertexList.get(i);
vtxPreferred = pickOneOfTwoDupes(transId, fromAppId, g,
- currentFaveVtx, vtxB, ver, dbMaps);
+ currentFaveVtx, vtxB, ver, loader);
if (vtxPreferred == null) {
// We couldn't choose one
return nullVtx;
@@ -1474,7 +1455,7 @@ public class DataGrooming {
*/
public static TitanVertex pickOneOfTwoDupes(String transId,
String fromAppId, TitanTransaction g, TitanVertex vtxA,
- TitanVertex vtxB, String ver, DbMaps dbMaps) throws AAIException {
+ TitanVertex vtxB, String ver, Loader loader) throws AAIException {
TitanVertex nullVtx = null;
TitanVertex preferredVtx = null;
@@ -1484,13 +1465,13 @@ public class DataGrooming {
String vtxANodeType = "";
String vtxBNodeType = "";
- Object obj = vtxA.<Object>property("aai-node-type").orElse(null);
- if (obj != null) {
- vtxANodeType = obj.toString();
+ Object objType = vtxA.<Object>property("aai-node-type").orElse(null);
+ if (objType != null) {
+ vtxANodeType = objType.toString();
}
- obj = vtxB.<Object>property("aai-node-type").orElse(null);
- if (obj != null) {
- vtxBNodeType = obj.toString();
+ objType = vtxB.<Object>property("aai-node-type").orElse(null);
+ if (objType != null) {
+ vtxBNodeType = objType.toString();
}
if (vtxANodeType.equals("") || (!vtxANodeType.equals(vtxBNodeType))) {
@@ -1504,10 +1485,9 @@ public class DataGrooming {
// (We'll check dep-node later)
// Determine what the key fields are for this nodeType
Collection <String> keyProps = new ArrayList <>();
- if( dbMaps.NodeKeyProps.containsKey(vtxANodeType) ){
- keyProps = dbMaps.NodeKeyProps.get(vtxANodeType);
- }
- else {
+ try {
+ keyProps = loader.introspectorFromName(vtxANodeType).getKeys();
+ } catch (AAIUnknownObjectException e) {
throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + vtxANodeType + ")");
}
@@ -1515,14 +1495,14 @@ public class DataGrooming {
while (keyPropI.hasNext()) {
String propName = keyPropI.next();
String vtxAKeyPropVal = "";
- obj = vtxA.<Object>property(propName).orElse(null);
- if (obj != null) {
- vtxAKeyPropVal = obj.toString();
+ objType = vtxA.<Object>property(propName).orElse(null);
+ if (objType != null) {
+ vtxAKeyPropVal = objType.toString();
}
String vtxBKeyPropVal = "";
- obj = vtxB.<Object>property(propName).orElse(null);
- if (obj != null) {
- vtxBKeyPropVal = obj.toString();
+ objType = vtxB.<Object>property(propName).orElse(null);
+ if (objType != null) {
+ vtxBKeyPropVal = objType.toString();
}
if (vtxAKeyPropVal.equals("")
@@ -1547,9 +1527,9 @@ public class DataGrooming {
TitanVertex tvCon = iter.next();
String conVid = tvCon.id().toString();
String nt = "";
- obj = tvCon.<Object>property("aai-node-type").orElse(null);
- if (obj != null) {
- nt = obj.toString();
+ objType = tvCon.<Object>property("aai-node-type").orElse(null);
+ if (objType != null) {
+ nt = objType.toString();
}
nodeTypesConn2A.put(nt, conVid);
vtxIdsConn2A.add(conVid);
@@ -1563,9 +1543,9 @@ public class DataGrooming {
TitanVertex tvCon = iter.next();
String conVid = tvCon.id().toString();
String nt = "";
- obj = tvCon.<Object>property("aai-node-type").orElse(null);
- if (obj != null) {
- nt = obj.toString();
+ objType = tvCon.<Object>property("aai-node-type").orElse(null);
+ if (objType != null) {
+ nt = objType.toString();
}
nodeTypesConn2B.put(nt, conVid);
vtxIdsConn2B.add(conVid);
@@ -1581,11 +1561,8 @@ public class DataGrooming {
// different ways. But for a particular node, it will only have one
// dependent node that it's
// connected to.
- Collection <String> depNodeTypes = new ArrayList <>();
- if( dbMaps.NodeDependencies.containsKey(vtxANodeType) ){
- depNodeTypes = dbMaps.NodeDependencies.get(vtxANodeType);
- }
-
+ Collection <String> depNodeTypes = loader.introspectorFromName(vtxANodeType).getDependentOn();
+
if (depNodeTypes.isEmpty()) {
// This kind of node is not dependent on any other. That is ok.
} else {
@@ -1689,7 +1666,7 @@ public class DataGrooming {
String fromAppId, TitanTransaction g, String version, String nType,
List<TitanVertex> passedVertList, Boolean dupeFixOn,
Set<String> deleteCandidateList, Boolean singleCommits,
- ArrayList<String> alreadyFoundDupeGroups, DbMaps dbMaps ) {
+ ArrayList<String> alreadyFoundDupeGroups, Loader loader ) {
ArrayList<String> returnList = new ArrayList<>();
ArrayList<TitanVertex> checkVertList = new ArrayList<>();
@@ -1748,7 +1725,7 @@ public class DataGrooming {
return returnList;
}
- if (!dbMaps.NodeDependencies.containsKey(nType)) {
+ if (loader.introspectorFromName(nType).isTopLevel()) {
// If this was a node that does NOT depend on other nodes for
// uniqueness, and we
// found more than one node using its key -- record the found
@@ -1761,7 +1738,7 @@ public class DataGrooming {
}
if (dupesStr != "") {
TitanVertex prefV = getPreferredDupe(transId, fromAppId,
- g, checkVertList, version, dbMaps);
+ g, checkVertList, version, loader);
if (prefV == null) {
// We could not determine which duplicate to keep
dupesStr = dupesStr + "KeepVid=UNDETERMINED";
@@ -1792,7 +1769,7 @@ public class DataGrooming {
// could be more than one set of duplicates.
HashMap<String, ArrayList<TitanVertex>> vertsGroupedByParentHash = groupVertsByDepNodes(
transId, fromAppId, g, version, nType,
- checkVertList, dbMaps);
+ checkVertList, loader);
for (Map.Entry<String, ArrayList<TitanVertex>> entry : vertsGroupedByParentHash
.entrySet()) {
ArrayList<TitanVertex> thisParentsVertList = entry
@@ -1809,7 +1786,7 @@ public class DataGrooming {
if (dupesStr != "") {
TitanVertex prefV = getPreferredDupe(transId,
fromAppId, g, thisParentsVertList,
- version, dbMaps);
+ version, loader);
if (prefV == null) {
// We could not determine which duplicate to
@@ -1860,7 +1837,7 @@ public class DataGrooming {
*/
private static HashMap<String, ArrayList<TitanVertex>> groupVertsByDepNodes(
String transId, String fromAppId, TitanTransaction g, String version,
- String nType, ArrayList<TitanVertex> passedVertList, DbMaps dbMaps)
+ String nType, ArrayList<TitanVertex> passedVertList, Loader loader)
throws AAIException {
// Given a list of Titan Vertices of one nodeType (see AAI-8956), group
// them together by the parent node they depend on.
@@ -1871,7 +1848,7 @@ public class DataGrooming {
// allow for the case where more than one is under the same parent node.
HashMap<String, ArrayList<TitanVertex>> retHash = new HashMap<String, ArrayList<TitanVertex>>();
- if (!dbMaps.NodeDependencies.containsKey(nType)) {
+ if (loader.introspectorFromName(nType).isTopLevel()) {
// This method really should not have been called if this is not the
// kind of node
// that depends on a parent for uniqueness, so just return the empty
@@ -1881,7 +1858,7 @@ public class DataGrooming {
// Find out what types of nodes the passed in nodes can depend on
ArrayList<String> depNodeTypeL = new ArrayList<>();
- Collection<String> depNTColl = dbMaps.NodeDependencies.get(nType);
+ Collection<String> depNTColl = loader.introspectorFromName(nType).getDependentOn();
Iterator<String> ntItr = depNTColl.iterator();
while (ntItr.hasNext()) {
depNodeTypeL.add(ntItr.next());
@@ -2250,5 +2227,4 @@ public class DataGrooming {
}// End of getConnectedParent()
-
}
diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/DbMeth.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/DbMeth.java
deleted file mode 100644
index 17266d11..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/dbgen/DbMeth.java
+++ /dev/null
@@ -1,3643 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.dbgen;
-
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.VertexProperty;
-
-import org.openecomp.aai.dbmodel.DbEdgeRules;
-import org.openecomp.aai.exceptions.AAIException;
-import org.openecomp.aai.ingestModel.DbMaps;
-import org.openecomp.aai.ingestModel.IngestModelMoxyOxm;
-import org.openecomp.aai.serialization.db.EdgeRule;
-import org.openecomp.aai.serialization.db.EdgeRules;
-import org.openecomp.aai.util.AAIConfig;
-import org.openecomp.aai.util.AAIConstants;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.google.common.net.InetAddresses;
-import com.thinkaurelius.titan.core.TitanEdge;
-import com.thinkaurelius.titan.core.TitanGraph;
-import com.thinkaurelius.titan.core.TitanTransaction;
-import com.thinkaurelius.titan.core.TitanVertex;
-
-
-/**
- * General Database-level Utility class. These methods deal with the database one dataNode / Edge at a time.
- * Transactions are managed at a higher level by the calling classes by passing in a TitanTransaction object.
- */
-public class DbMeth{
-
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DbMeth.class);
-
- /**
- * Patch aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param depNodeVal the dep node val
- * @param apiVersion the api version
- * @return TitanVertex
- * @throws AAIException the AAI exception
- */
- public static TitanVertex patchAaiNode(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, TitanVertex depNodeVal, String apiVersion ) throws AAIException{
- // If they're calling patchAaiNode, then we only want to add/update the properties that they
- // pass us in the propHash. If there are others already in the DB, we leave them alone.
-
- // Note: to be really official, we'd throw an error if the node wasn't already in the db.
- boolean[] objectExists = new boolean[1];
- objectExists[0] = true;
- Boolean patchOnly = true;
- TitanVertex tv = persistAaiNodeBASE(transId, fromAppId, graph, nodeType, propHash, depNodeVal, patchOnly, apiVersion, objectExists);
- return( tv );
-
- } // end of patchAaiNode()
-
- /**
- * Patch aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param depNodeVal the dep node val
- * @return the titan vertex
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanVertex patchAaiNode(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, TitanVertex depNodeVal) throws AAIException{
- return patchAaiNode( transId, fromAppId, graph, nodeType,
- propHash, depNodeVal, null );
- }
-
- /**
- * Persist aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param depNodeVal the dep node val
- * @param patchOnly the patch only
- * @param apiVersion the api version
- * @return the titan vertex
- * @throws AAIException the AAI exception
- */
- public static TitanVertex persistAaiNode(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, TitanVertex depNodeVal, Boolean patchOnly, String apiVersion) throws AAIException{
- boolean[] objectExists = new boolean[1];
- objectExists[0] = false;
- return persistAaiNodeBASE( transId, fromAppId, graph, nodeType,
- propHash, depNodeVal, patchOnly, apiVersion, objectExists);
- }
-
- /**
- * Persist aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param addIfNotFound the add if not found
- * @param depNodeVal the dep node val
- * @param apiVersion the api version
- * @return the titan vertex
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanVertex persistAaiNode(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, Boolean addIfNotFound, TitanVertex depNodeVal, String apiVersion) throws AAIException{
- // If they're calling persistAaiNode, then we want to make the Db look like whatever they pass us. That is, if
- // there is already a record in the DB, but they do not pass some of the existing properties, they should
- // be cleared from the DB. Since we want to take care of all properties, we pass patchOnly = false
- Boolean patchOnly = false;
- boolean[] objectExists = new boolean[1];
- objectExists[0] = false;
- TitanVertex tv = persistAaiNodeBASE(transId, fromAppId, graph, nodeType, propHash, depNodeVal, patchOnly, apiVersion, objectExists);
- return( tv );
- }
-
- /**
- * Persist aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param addIfNotFound the add if not found
- * @param depNodeVal the dep node val
- * @return the titan vertex
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanVertex persistAaiNode(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, Boolean addIfNotFound, TitanVertex depNodeVal) throws AAIException{
- // If they're calling persistAaiNode, then we want to make the Db look like whatever they pass us. That is, if
- // there is already a record in the DB, but they do not pass some of the existing properties, they should
- // be cleared from the DB. Since we want to take care of all properties, we pass patchOnly = false
- Boolean patchOnly = false;
- boolean[] objectExists = new boolean[1];
- objectExists[0] = false;
- TitanVertex tv = persistAaiNodeBASE(transId, fromAppId, graph, nodeType, propHash, depNodeVal, patchOnly, null, objectExists);
- return( tv );
- } // end of persistAaiNode()
-
- /**
- * Persist aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param addIfNotFound the add if not found
- * @param depNodeVal the dep node val
- * @param apiVersion the api version
- * @param objectExists the object exists
- * @return TitanVertex
- * @throws AAIException the AAI exception
- */
- public static TitanVertex persistAaiNode(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, Boolean addIfNotFound, TitanVertex depNodeVal, String apiVersion, boolean[] objectExists) throws AAIException{
- Boolean patchOnly = false;
- // If they're calling persistAaiNode, then we want to make the Db look like whatever they pass us. That is, if
- // there is already a record in the DB, but they do not pass some of the existing properties, they should
- // be cleared from the DB. Since we want to take care of all properties, we pass patchOnly = false
- TitanVertex tv = persistAaiNodeBASE(transId, fromAppId, graph, nodeType, propHash, depNodeVal, patchOnly, apiVersion, objectExists, null);
- return( tv );
- }
-
- /**
- * Persist aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param addIfNotFound the add if not found
- * @param depNodeVal the dep node val
- * @param apiVersion the api version
- * @param objectExists the object exists
- * @param thisNodeVertex the this node vertex
- * @return the titan vertex
- * @throws AAIException the AAI exception
- */
- public static TitanVertex persistAaiNode(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, Boolean addIfNotFound, TitanVertex depNodeVal, String apiVersion, boolean[] objectExists, TitanVertex thisNodeVertex) throws AAIException{
- Boolean patchOnly = false;
- // If they're calling persistAaiNode, then we want to make the Db look like whatever they pass us. That is, if
- // there is already a record in the DB, but they do not pass some of the existing properties, they should
- // be cleared from the DB. Since we want to take care of all properties, we pass patchOnly = false
- TitanVertex tv = persistAaiNodeBASE(transId, fromAppId, graph, nodeType, propHash, depNodeVal, patchOnly, apiVersion, objectExists, thisNodeVertex);
- return( tv );
- }
-
- /**
- * Persist aai node BASE.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param depNodeVal the dep node val
- * @param patchOnly the patch only
- * @param apiVersion the api version
- * @param objectExists the object exists
- * @return the titan vertex
- * @throws AAIException the AAI exception
- */
- public static TitanVertex persistAaiNodeBASE(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, TitanVertex depNodeVal, Boolean patchOnly,
- String apiVersion, boolean[] objectExists) throws AAIException{
- return persistAaiNodeBASE(transId, fromAppId, graph, nodeType, propHash, depNodeVal, patchOnly, apiVersion, objectExists, null);
- }
-
- /**
- * Persist aai node BASE.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propHash the prop hash
- * @param depNodeVal the dep node val
- * @param patchOnly the patch only
- * @param apiVersion the api version
- * @param objectExists the object exists
- * @param thisNodeVertex the this node vertex
- * @return the titan vertex
- * @throws AAIException the AAI exception
- */
- public static TitanVertex persistAaiNodeBASE(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap <String,Object> propHash, TitanVertex depNodeVal, Boolean patchOnly,
- String apiVersion, boolean[] objectExists, TitanVertex thisNodeVertex) throws AAIException{
-
- if( graph == null ){
- throw new AAIException("AAI_6101", "null graph object passed to persistAaiNodeBASE()");
- }
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- boolean useDepNode = false;
- String resourceVersion = null;
- if( propHash.containsKey("resource-version") ){
- resourceVersion = (String)(propHash.get("resource-version"));
- }
- String aaiUniqueKeyVal = null;
- if( propHash.containsKey("aai-unique-key") ){
- // Note -- we are assuming that nobody is monkeying with this. The 16-07 first-pass theory
- // is that the REST layer is always gonna generate this or pass it through.
- aaiUniqueKeyVal = (String)(propHash.get("aai-unique-key"));
- propHash.remove("aai-unique-key");
- }
-
- if( needsADepNode4Uniqueness(transId, fromAppId, nodeType, apiVersion) ){
- // This kind of node needs a dependent node (for uniqueness)
- if( depNodeVal == null ){
- // They should have passed in the node that this one depends on
- throw new AAIException("AAI_6109", "null dependentNode object passed to persistAaiNodeBASE() but " + nodeType + " requires one.");
- }
- else if( ! nodeTypeACanDependOnB(transId, fromAppId, nodeType, depNodeVal.<String>property("aai-node-type").orElse(null), apiVersion) ){
- // They should have passed in the right type of node as the dependent node
- throw new AAIException("AAI_6109", "dependentNode of type " + depNodeVal.<String>property("aai-node-type").orElse(null) + " passed to persistAaiNodeBASE() for nodeType" + nodeType + ".");
- }
- useDepNode = true;
- }
- else {
- depNodeVal = null;
- }
-
- // Note: as of 1607, we no longer validate property names since that's covered by the REST layer.
- // Same goes for required fields (as of 1602)
-
- // Special ip-address validation for ipAddr nodes only... This will go away when we go to YANG and
- // do validations like this up at that layer.
- if( nodeType.equals("ipaddress") ){
- // Note - this will throw an exception if the ipAddress is using a bad format
- ipAddressFormatOK( transId, fromAppId, (String)propHash.get("addr"), (String)propHash.get("version") );
- }
-
- // Use the key-fields/dependentNode to check if this is an add or an update
- // We assume that all NodeTypes at least one key-property defined. A dependentNode is optional.
- if( ! dbMaps.NodeKeyProps.containsKey(nodeType) ){
- // Problem if no key Properties defined for this nodeType
- String defVer = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- throw new AAIException("AAI_6105", "No node-key-properties defined in dbMaps for nodeType = " + nodeType + " (ver=" + defVer + ")");
- }
-
- Boolean hasAltKey1 = false;
- HashMap <String,Object>nodeAltKey1PropsHash = new HashMap<String,Object>();
- Collection <String> altKey1Props = getNodeAltKey1PropNames(transId, fromAppId, nodeType, apiVersion);
- if( altKey1Props != null ){
- Iterator <String> altKey1PropI = altKey1Props.iterator();
- while( altKey1PropI.hasNext() ){
- String propName = altKey1PropI.next();
- // NOTE: alt-keys are not always required fields. If it is null or blank, we won't
- // do alt-key checks on it.
- Object value = propHash.get(propName);
- if( value != null && !value.toString().equals("") ){
- hasAltKey1 = true;
- nodeAltKey1PropsHash.put(propName, value);
- }
- }
- }
- HashMap <String,Object>nodeKeyPropsHash = new HashMap<String,Object>();
- Collection <String> keyProps = getNodeKeyPropNames(transId, fromAppId, nodeType, apiVersion);
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- String propName = keyPropI.next();
-
- Object value = propHash.get(propName);
- nodeKeyPropsHash.put(propName, value);
- }
-
- // Check if this node is already in the database based on the Primary Key Info
- TitanVertex existingVert = thisNodeVertex;
- boolean foundTheNodeInDb = true;
-
- if (existingVert == null) {
- try {
- existingVert = getUniqueNode( transId, fromAppId, graph, nodeType, nodeKeyPropsHash, depNodeVal, apiVersion );
- }
- catch (AAIException e) {
- if (e.getErrorObject().getErrorCode().equals("6114")) {
- foundTheNodeInDb = false;
- }
- else {
- throw e;
- }
- }
- }
-
- // this is so the notification knows whether or not the operation was an UPDATE or a CREATe
- objectExists[0] = foundTheNodeInDb;
- if( foundTheNodeInDb ){
- // A record was found in the DB using the PK.
- if( needToDoResourceVerCheck(apiVersion, patchOnly) ){
- // Need to check that they knew what they were updating
- String existingResVer = existingVert.<String>property("resource-version").orElse(null);
- if( resourceVersion == null || resourceVersion.equals("") ){
- throw new AAIException("AAI_6130", "Resource-version not passed for update of = " + nodeType + ", " + nodeKeyPropsHash.toString());
- }
- else if( (existingResVer != null) && !resourceVersion.equals(existingResVer) ){
- throw new AAIException("AAI_6131", "Resource-version " + resourceVersion + " MISMATCH WITH EXISTING " + existingResVer + " for update of = " + nodeType + ", " + nodeKeyPropsHash.toString());
- }
- }
-
- // Need to ensure that the Alternate key isn't changing to a value that points to a different existing node.
- // It is ok if it points to nothing -- that would just be an update for this node. It's also ok if
- // it points to this (existing) node - that just means that it wasn't being updated.
- if( hasAltKey1 ){
- try {
- TitanVertex chkVert = getUniqueNode( transId, fromAppId, graph, nodeType, nodeAltKey1PropsHash, depNodeVal, apiVersion );
- if( ! chkVert.id().toString().equals(existingVert.id().toString()) ){
- throw new AAIException("AAI_6117", "In-Use AlternateKey value passed for update of nodeType = " + nodeType);
- }
- }
- catch (AAIException e) {
- if(! e.getErrorObject().getErrorCode().equals("6114") ){
- throw e;
- }
- }
- }
- }
- else {
- // Note not in the DB -- This will be an ADD of a new node
- // a) make sure they didn't say they were just doing "patchOnly" which cannot be an ADD.
- // b) if there is an alternate key, we need to make sure the AK isn't already in use by somebody else.
- if( patchOnly ){
- String depMsg = "";
- if( useDepNode ){
- depMsg = " plus dependent node. ";
- }
- throw new AAIException("AAI_6114", "Patch Request, but no Node of type " + nodeType + " found for properties: [" + propHash + "] " + depMsg);
- }
-
- if( needToDoResourceVerCheck(apiVersion, patchOnly) && (resourceVersion != null) && !resourceVersion.equals("") ){
- throw new AAIException("AAI_6131", "Resource-version was passed in, but this is an ADD of a " + nodeType + ", with these params: " + nodeKeyPropsHash.toString());
- }
- if( hasAltKey1 ){
- try {
- getUniqueNode( transId, fromAppId, graph, nodeType, nodeAltKey1PropsHash, depNodeVal, apiVersion );
- // Since the Primary Key for this nodeType wasn't found in the DB yet, the fact that
- // we are able to find a record (no "6114" exception thrown) using the Alternate-Key is an error.
- // We can't create a new node that uses an AK that's already in use.
- throw new AAIException("AAI_6117", "Conflicting Key and Alternate-Key values passed for add of nodeType = " + nodeType);
- }
- catch (AAIException e) {
- if(! e.getErrorObject().getErrorCode().equals("6114") ){
- throw e;
- }
- }
- }
- }
-
- // ------------- Done with checking. Do the add or update to the dB -----------------------
-
- if( foundTheNodeInDb ){
- long unixTimeNow = System.currentTimeMillis() / 1000L;
- // ----- This is an UPDATE ------
-
-
- String existingSourceOfTruth = fromAppId; // default value if we can't get the old one
- Object tmpOb = existingVert.<Object>property("source-of-truth").orElse(null);
- if( tmpOb != null ){
- existingSourceOfTruth = tmpOb.toString();
- }
- long existingCreateTs = unixTimeNow; // default value if we can't get the old one
- tmpOb = existingVert.<Object>property("aai-created-ts").orElse(null);
- if( tmpOb != null ){
- existingCreateTs = (long) tmpOb;
- }
-
- String msg = "UPDATE vertex of type = [" + nodeType + "] ";
- if( useDepNode ){
- String depNType = depNodeVal.<String>property("aai-node-type").orElse(null);
- HashMap <String, Object> depNodePropKeysHash = getNodeKeyPropHash(transId, fromAppId, graph, depNodeVal);
- LOGGER.info("UPDATE existing node: type = " + nodeType + ", key(s) = [" + nodeKeyPropsHash +
- "] which rides on dependent node: type = " + depNType + ", with key(s) = [" + depNodePropKeysHash + "].");
- }
- else {
- LOGGER.info("UPDATE existing node: type = " + nodeType + ", key(s) = [" + nodeKeyPropsHash + "] (no dep. node).");
- }
- String removeList = "";
- if( ! patchOnly ){
- // They are updating an existing record, and they want us to "process all defined properties" (not just patch)
- // So we will see if the node has any properties that were not passed-in. Those need to be removed.
- Collection <String> propCol = dbMaps.NodeProps.get(nodeType);
- Iterator <String> propIter = propCol.iterator();
- while( propIter.hasNext() ){
- String propName = propIter.next();
- if( ! propHash.containsKey(propName) && !DbEdgeRules.ReservedPropNames.containsKey(propName)){
- if( thisPropertyWasPutByNewerVersionOfCode(apiVersion, nodeType, propName) ){
- // we must be using an older version of code here - but the property that
- // has not been passed in this persist call is one that this older version of
- // the database did not know about. So leave it alone.
- }
- else {
- removeList = removeList + "," + propName;
- existingVert.property(propName).remove();
- }
- }
- }
- }
- if( !removeList.equals("") ){
- LOGGER.info("Removed these props on update: [" + removeList + "]");
- }
- for( Map.Entry<String, Object> entry : propHash.entrySet() ){
- // update the parameters that have been passed in (except the key-properties)
- // taking away the key-property check. We will now allow this since
- // the keys were used to identify this node, so they should be good and
- // there are times when Titan resolves conflicts by only using the
- // data set in an update - and was losing our key info...
- // Similar to the change noted below.
- //if( ! nodeKeyPropsHash.containsKey(entry.getKey()) ){
- // existingVert.setProperty( entry.getKey(), entry.getValue() );
- //}
- if( ! entry.getKey().equals("resource-version") ){
- boolean nonSingleCardinality = false;
- boolean setSoNoDupes = false;
- if( checkPropCardinality(entry.getKey(), "Set") ){
- nonSingleCardinality = true;
- setSoNoDupes = true;
- }
- else if( checkPropCardinality(entry.getKey(), "List") ){
- nonSingleCardinality = true;
- }
-
- Iterator <Object> valIter = null;
- if( nonSingleCardinality ){
- String className = entry.getValue().getClass().getSimpleName();
- if( className.equals("ArrayList") ){
- valIter = ((ArrayList)(entry.getValue())).iterator();
- }
- else if( className.equals("List") ){
- valIter = ((List)(entry.getValue())).iterator();
- }
- else if( className.equals("Set") ){
- valIter = ((Set)(entry.getValue())).iterator();
- }
- }
-
- if( nonSingleCardinality ){
- // This property has Cardinality of List or Set - which need to be handled carefully
- // Note -- for Lists or Sets, we assume they are of dataType String - that is all
- // the Rest layer supports at the moment (16-02)
- ArrayList <String> currentData = new ArrayList <String> ();
- if( patchOnly ){
- // When patching - gotta know what's already in the db
- Iterator<VertexProperty<Object>> existingPropsIter = (existingVert.properties(entry.getKey()));
- if( existingPropsIter != null ){
- while( existingPropsIter.hasNext() ){
- String existingVal = existingPropsIter.next().value().toString();
- currentData.add( existingVal );
- }
- }
- }
- else {
- // Since this is not a patch-update, we first have to clear out what is currently in the db.
- existingVert.property(entry.getKey()).remove();
- }
-
- if( valIter != null ){
- while( valIter.hasNext() ){
- Object thisVal = valIter.next();
- if( setSoNoDupes ){
- // For Sets, we need to check that the data isn't already in the db or wasn't passed
- // in to us twice in the propHash. Otherwise Titan throws an exception (instead of just ignoring it...)
- if( !currentData.contains(thisVal) ){
- // We don't have this data yet, so add it to the Set
- existingVert.property( entry.getKey(), thisVal );
- currentData.add( thisVal.toString() );
- }
- }
- else {
- // For List data types, it's ok to have duplicate values in the db (why would we want this?)
- existingVert.property( entry.getKey(), thisVal );
- }
- }
- }
- }
- else {
- // This is a normal, "Cardinality = SINGLE" kind of property
- // ResourceVersion is not populated based on passed-in data, it is set along with other internal properties below.
- //Object cleanVal = convertTypeIfNeeded( entry.getKey(), entry.getValue() );
- //existingVert.setProperty( entry.getKey(), cleanVal );
- // ********************************
- existingVert.property( entry.getKey(), entry.getValue() );
- }
- }
- }
-
- // DEBUG - trying to deal with the case where simultaneous PUTs
- // cause our db to wind up with a vertex that does not have these three properties filled in.
- existingVert.property( "aai-node-type", nodeType );
- existingVert.property( "aai-created-ts", existingCreateTs );
- existingVert.property( "source-of-truth", existingSourceOfTruth );
-
- if( aaiUniqueKeyVal != null ){
- existingVert.property( "aai-unique-key", aaiUniqueKeyVal );
- }
-
- existingVert.property( "aai-last-mod-ts", unixTimeNow );
- String resVers = "" + unixTimeNow;
- existingVert.property( "resource-version", resVers );
- existingVert.property( "last-mod-source-of-truth", fromAppId );
-
- LOGGER.info(msg + ", [aai-last-mod-ts]/[" + unixTimeNow + "]");
-
- return( existingVert );
- }
- else{
- // ----- Not found in the DB, This must be an ADD ------
- if( DbEdgeRules.NodeTypeCategory.containsKey(nodeType) ){
- throw new AAIException("AAI_6120", "nodeTypeCategory " + nodeType + " cannot be used to ADD a node. Need to pass a valid nodeType");
- }
-
- TitanVertex tiVnew = graph.addVertex( nodeType );
-
- String msg = "ADD vertex of type = [" + nodeType + "] ";
- if( depNodeVal != null ){
- String depNType = depNodeVal.<String>property("aai-node-type").orElse(null);
- HashMap <String, Object> depNodePropKeysHash = getNodeKeyPropHash(transId, fromAppId, graph, depNodeVal);
- msg = msg + " onto dependent node: type = " + depNType + ", which has key(s) = [" + depNodePropKeysHash +
- "]. New Node Prop/values = ";
- }
- else {
- msg = msg + " Note: no dependent node. New Node Prop/values = ";
- }
- boolean first = true;
- for( Map.Entry<String, Object> entry : propHash.entrySet() ){
- if( ! entry.getKey().equals("resource-version") ){
- if( first ){
- msg = msg + " [" + entry.getKey() + "]/[" + entry.getValue() + "]";
- first = false;
- }
- else {
- msg = msg + ", [" + entry.getKey() + "]/[" + entry.getValue() + "]";
- }
-
- boolean nonSingleCardinality = false;
- boolean setSoNoDupes = false;
- if( checkPropCardinality(entry.getKey(), "Set") ){
- nonSingleCardinality = true;
- setSoNoDupes = true;
- }
- else if( checkPropCardinality(entry.getKey(), "List") ){
- nonSingleCardinality = true;
- }
-
- Iterator <Object> valIter = null;
- if( nonSingleCardinality ){
- String className = entry.getValue().getClass().getSimpleName();
- if( className.equals("ArrayList") ){
- valIter = ((ArrayList)(entry.getValue())).iterator();
- }
- else if( className.equals("List") ){
- valIter = ((List)(entry.getValue())).iterator();
- }
- else if( className.equals("Set") ){
- valIter = ((Set)(entry.getValue())).iterator();
- }
- }
-
- if( nonSingleCardinality ){
- // This property has Cardinality of List or Set - which need to be handled carefully
- ArrayList <String> currentData = new ArrayList <String> ();
- if( valIter != null ){
- while( valIter.hasNext() ){
- Object thisVal = valIter.next();
- if( setSoNoDupes ){
- // For Sets, we need to check that they're not passing us duplicate data in propHash.
- // Otherwise Titan throws an exception (instead of just ignoring it...)
- if( !currentData.contains(thisVal) ){
- // We don't have this data yet, so add it to the Set
- tiVnew.property( entry.getKey(), thisVal );
- currentData.add( thisVal.toString() );
- }
- }
- else {
- // For List data types, it's ok to have duplicate values in the db (why would we want this?)
- tiVnew.property( entry.getKey(), thisVal );
- }
- }
- }
- }
- else {
- // This is a normal, "Cardinality = SINGLE" kind of property
- // ResourceVersion is not populated based on passed-in data, it is set along with other internal properties below.
- tiVnew.property( entry.getKey(), entry.getValue() );
- }
- }
- }
-
- tiVnew.property( "aai-node-type", nodeType );
- //long unixTime = System.currentTimeMillis() / 1000L;
- long unixTime = System.currentTimeMillis();
- tiVnew.property( "aai-created-ts", unixTime );
- tiVnew.property( "aai-last-mod-ts", unixTime );
- String resVers = "" + unixTime;
- tiVnew.property( "resource-version", resVers );
- tiVnew.property( "source-of-truth", fromAppId );
- tiVnew.property( "last-mod-source-of-truth", fromAppId );
- if( aaiUniqueKeyVal != null ){
- tiVnew.property( "aai-unique-key", aaiUniqueKeyVal );
- }
-
- LOGGER.info(msg + ", [aai-created-ts]/[" + unixTime + "]");
- return( tiVnew );
- }
-
- } // end of persistAaiNodeBASE()
-
-
- /**
- * Need to do resource ver check.
- *
- * @param apiVersion the api version
- * @param patchOnlyFlag the patch only flag
- * @return the boolean
- * @throws AAIException the AAI exception
- */
- public static Boolean needToDoResourceVerCheck(String apiVersion, Boolean patchOnlyFlag)
- throws AAIException{
-
- if( patchOnlyFlag ){
- // we do not do resource checking for patch requests.
- return false;
- }
-
- String resourceCheckOnFlag = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG);
-
- int apiVerInt = cleanUpApiVersion(apiVersion);
-
- if( (resourceCheckOnFlag != null) && resourceCheckOnFlag.equals("true") ){
- // Only do the check if the resource enable flag is set to "true"
- if( apiVerInt > 4 ){
- // We're only doing the resource version checks for v5 and later
- return true;
- }
- }
-
- return false;
- }// End needToDoResourceVerCheck()
-
-
- /**
- * Clean up api version.
- *
- * @param apiVersionString the api version string
- * @return the int
- * @throws AAIException the AAI exception
- */
- private static int cleanUpApiVersion( String apiVersionString ) throws AAIException {
- // Note: we expect an apiVersion to start with the letter "v", followed by an integer.
-
- int versionInt = 0;
- String verStr = apiVersionString;
- if( (apiVersionString == null) || (apiVersionString.length() < 2) ){
- // Passed in version doesn't look right
- verStr = org.openecomp.aai.util.AAIApiVersion.get();
- }
- versionInt = getVerNumFromVerString( verStr );
-
- return versionInt;
- }
-
- /**
- * Gets the ver num from ver string.
- *
- * @param versionString the version string
- * @return the ver num from ver string
- * @throws AAIException the AAI exception
- */
- private static int getVerNumFromVerString( String versionString )throws AAIException {
- int versionInt = 0;
- if( versionString == null || versionString.length() < 2 ){
- throw new AAIException("AAI_6121", " Bad Version (format) passed to getVerNumFromVerString: [" + versionString + "].");
- }
-
- int strLen = versionString.length();
- // We assume that a version looks like "v" followed by an integer
- if( ! versionString.substring(0,1).equals("v") ){
- String detail = " Bad Version (format) passed to getVerNumFromVerString: [" + versionString + "].";
- throw new AAIException("AAI_6121", detail);
- }
- else {
- String intPart = versionString.substring(1,strLen);
- try {
- versionInt = Integer.parseInt( intPart );
- }
- catch( Exception e ){
- String detail = " Bad Version passed to getVerNumFromVerString: [" + versionString + "].";
- throw new AAIException("AAI_6121", detail);
- }
- }
- return versionInt;
- }
-
-
- /**
- * Gets the node key prop names.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param apiVersion the api version
- * @return HashMap of keyProperties
- * @throws AAIException the AAI exception
- */
- public static Collection <String> getNodeKeyPropNames( String transId, String fromAppId, String nodeType, String apiVersion ) throws AAIException{
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- Collection <String> keyProps = new ArrayList <String>();
- if( dbMaps.NodeKeyProps.containsKey(nodeType) ){
- keyProps = dbMaps.NodeKeyProps.get(nodeType);
- }
- else if( DbEdgeRules.NodeTypeCategory.containsKey(nodeType) ){
- // The passed-in nodeType was really a nodeCategory, so we need to look up the key params
- Collection <String> nTypeCatCol = DbEdgeRules.NodeTypeCategory.get(nodeType);
- Iterator <String> catItr = nTypeCatCol.iterator();
- String catInfo = "";
- if( catItr.hasNext() ){
- // For now, we only look for one.
- catInfo = catItr.next();
- }
- else {
- String defVer = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + nodeType+ " (ver=" + defVer + ")");
- }
-
- String [] flds = catInfo.split(",");
- if( flds.length != 4 ){
- throw new AAIException("AAI_6121", "Bad EdgeRule.NodeTypeCategory data for nodeType = [" + nodeType + "].");
- }
-
- String keyPropsString = flds[0];
- String [] propNames = keyPropsString.split("\\|");
- for( int i = 0; i < propNames.length; i++ ){
- keyProps.add(propNames[i]);
- }
- }
- else {
- String defVer = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + nodeType+ " (ver=" + defVer + ")");
- }
-
- return keyProps;
-
- }// end of getNodeKeyPropNames
-
- /**
- * Gets the node key prop names.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @return the node key prop names
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static Collection <String> getNodeKeyPropNames( String transId, String fromAppId, String nodeType ) throws AAIException{
- return getNodeKeyPropNames( transId, fromAppId, nodeType, null);
- }
-
- /**
- * Gets the node alt key 1 prop names.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param apiVersion the api version
- * @return HashMap of keyProperties
- * @throws AAIException the AAI exception
- */
- public static Collection <String> getNodeAltKey1PropNames( String transId, String fromAppId, String nodeType, String apiVersion ) throws AAIException{
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- Collection <String> altKey1Props = new ArrayList <String>();
- if( dbMaps.NodeAltKey1Props.containsKey(nodeType) ){
- altKey1Props = dbMaps.NodeAltKey1Props.get(nodeType);
- }
- else if( DbEdgeRules.NodeTypeCategory.containsKey(nodeType) ){
- // The passed-in nodeType was really a nodeCategory, so we need to look up the key params
- Collection <String> nTypeCatCol = DbEdgeRules.NodeTypeCategory.get(nodeType);
- Iterator <String> catItr = nTypeCatCol.iterator();
- String catInfo = "";
- if( catItr.hasNext() ){
- catInfo = catItr.next();
- String [] flds = catInfo.split(",");
- if( flds.length != 4 ){
- throw new AAIException("AAI_6121", "Bad EdgeRule.NodeTypeCategory data (itemCount=" + flds.length + ") for nodeType = [" + nodeType + "].");
- }
-
- String altKeyPropsString = flds[1];
- String [] propNames = altKeyPropsString.split("\\|");
- for( int i = 0; i < propNames.length; i++ ){
- altKey1Props.add(propNames[i]);
- }
- }
- }
-
- return altKey1Props;
-
- }// end of getNodeAltKey1PropNames
-
- /**
- * Gets the node alt key 1 prop names.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @return the node alt key 1 prop names
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static Collection <String> getNodeAltKey1PropNames( String transId, String fromAppId, String nodeType ) throws AAIException{
- return getNodeAltKey1PropNames( transId, fromAppId, nodeType, null);
- }
-
-
- /**
- * Gets the unique node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param keyPropsHash the key props hash
- * @param depNodeVal the dep node val
- * @param apiVersion the api version
- * @return TitanVertex
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanVertex getUniqueNode( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> keyPropsHash, TitanVertex depNodeVal, String apiVersion ) throws AAIException{
-
- // NOTE - this is really for use by the PersistNode method -- it is looking to see if
- // a node exists in the database given either Primary or Alternate Key data and dependent
- // node data (if required for uniqueness).
-
- // Note - the passed in nodeType could really be a nodeTypeCategory ---
- Boolean nodeTypeIsCategory = DbEdgeRules.NodeTypeCategory.containsKey(nodeType);
-
- Boolean useDepNode = false;
- if( needsADepNode4Uniqueness(transId, fromAppId, nodeType, apiVersion) ){
- // This kind of node depends on another node for uniqueness
- if( depNodeVal == null ){
- // They should have passed in the node that this one depends on
- throw new AAIException("AAI_6109", "null dependentNode object passed to getUniqueNode() but " + nodeType + " requires one.");
- }
- else if( ! nodeTypeACanDependOnB(transId, fromAppId, nodeType, depNodeVal.<String>property("aai-node-type").orElse(null), apiVersion) ){
- // They should have passed in the right type of node as the dependent node
- throw new AAIException("AAI_6109", "dependentNode of type " + depNodeVal.<String>property("aai-node-type").orElse(null) + " passed to getUniqueNode() for nodeType" + nodeType + ".\n");
- }
- useDepNode = true;
- }
- else {
- depNodeVal = null;
- }
-
- // We assume that all NodeTypes have at least one key-property defined. A dependentNode is optional.
- // Note - instead of key-properties (the primary key properties), a user could pass
- // alternate-key values if they are defined for the nodeType.
- ArrayList<String> kName = new ArrayList<String>();
- ArrayList<Object> kVal = new ArrayList<Object>();
-
- Collection <String> keyProps = getNodeKeyPropNames(transId, fromAppId, nodeType, apiVersion);
- Iterator <String> keyPropI = keyProps.iterator();
- Boolean haveSomePrimKeyProps = false;
- Boolean primaryKeyComplete = true;
- while( keyPropI.hasNext() ){
- haveSomePrimKeyProps = true;
-
- String propName = keyPropI.next();
- if( ! keyPropsHash.containsKey(propName) ){
- primaryKeyComplete = false;
- }
- else {
- Object valObj = keyPropsHash.get(propName);
- if( valObj == null ){
- primaryKeyComplete = false;
- }
- else {
- String value = valObj.toString();
- if( value == null || value.equals("") ){
- // They passed the property name, but no value
- primaryKeyComplete = false;
- }
- }
- }
- }
-
- int i = -1;
- if( haveSomePrimKeyProps && primaryKeyComplete ){
- keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- String propName = keyPropI.next();
- String value = (keyPropsHash.get(propName)).toString();
- i++;
- kName.add(i, propName);
- kVal.add(i, (Object)value);
- }
- }
- else {
- // See if they're using the alternate key
- Collection <String> altKey1Props = getNodeAltKey1PropNames(transId, fromAppId, nodeType, apiVersion);
- Iterator <String> altKey1PropI = altKey1Props.iterator();
- Boolean haveSomeAltKey1Props = false;
- Boolean altKey1Complete = true;
- while( altKey1PropI.hasNext() ){
- haveSomeAltKey1Props = true;
- String propName = altKey1PropI.next();
- if( ! keyPropsHash.containsKey(propName) ){
- altKey1Complete = false;
- }
- else {
- Object valObj = keyPropsHash.get(propName);
- if( valObj == null ){
- altKey1Complete = false;
- }
- else {
- String value = valObj.toString();
- if( value == null || value.equals("") ){
- // They passed the property name, but no value
- altKey1Complete = false;
- }
- }
- }
- }
- if( haveSomeAltKey1Props && altKey1Complete ){
- altKey1PropI = altKey1Props.iterator();
- while( altKey1PropI.hasNext() ){
- String propName = altKey1PropI.next();
- String value = (keyPropsHash.get(propName)).toString();
- i++;
- kName.add(i, propName);
- kVal.add(i, (Object)value);
- }
- }
- }
-
- int topPropIndex = i;
- TitanVertex tiV = null;
- String propsAndValuesForMsg = "";
- if( !useDepNode ){
- // There is no node that this type of node depends on, so we can look for it based
- // solely on the Aai-defined key fields.
- Iterable <?> verts = null;
-
- if( topPropIndex == -1 ){
- // Problem if no key Properties defined for this nodeType
- String defVer = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- throw new AAIException("AAI_6105", "Bad or Incomplete Key Property params: (" + keyPropsHash.toString() +
- ") for nodeType: " + nodeType + " (ver=" + defVer + ")");
- }
- else if( topPropIndex == 0 ){
- if (nodeTypeIsCategory) // dont know real type
- verts= graph.query().has(kName.get(0),kVal.get(0)).vertices();
- else // need this to find dvs switch: dvs.switch-name and port-group.switch-name issue
- verts= graph.query().has(kName.get(0),kVal.get(0)).has("aai-node-type",nodeType).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ") ";
- }
- else if( topPropIndex == 1 ){
- verts = graph.query().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
- + kName.get(1) + " = " + kVal.get(1) + ") ";
- }
- else if( topPropIndex == 2 ){
- verts= graph.query().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
- + kName.get(1) + " = " + kVal.get(1) + ", "
- + kName.get(2) + " = " + kVal.get(2) + ") ";
- }
- else if( topPropIndex == 3 ){
- verts= graph.query().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has(kName.get(3),kVal.get(3)).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
- + kName.get(1) + " = " + kVal.get(1) + ", "
- + kName.get(2) + " = " + kVal.get(2) + ", "
- + kName.get(3) + " = " + kVal.get(3) + ") ";
- }
- else {
- String emsg = " We only support 4 keys per nodeType for now \n";
- throw new AAIException("AAI_6114", emsg);
- }
-
- Iterator <?> vertI = verts.iterator();
- if( vertI != null && vertI.hasNext()) {
- // We found a vertex that meets the input criteria.
- tiV = (TitanVertex) vertI.next();
-
- if( vertI.hasNext() ){
- // Since this routine is looking for a unique node for the given input values, if
- // more than one is found - it's a problem.
- throw new AAIException("AAI_6112", "More than one Node found by getUniqueNode for params: " + propsAndValuesForMsg);
- }
- }
- else {
- // No Vertex was found for this key - throw a not-found exception
- throw new AAIException("AAI_6114", "No Node of type " + nodeType + " found for properties: " + propsAndValuesForMsg);
- }
- }
- else {
- // Need to use the dependent vertex to look for this one.
- // filter this to the actual keys because
- HashMap<String,Object> onlyKeysHash = new HashMap<String,Object>();
-
- Collection <String> onlyKeyProps = getNodeKeyPropNames(transId, fromAppId, nodeType, apiVersion);
-
- Iterator <String> onlyKeyPropsI = onlyKeyProps.iterator();
-
- while( onlyKeyPropsI.hasNext() ){
- String keyName = onlyKeyPropsI.next();
- onlyKeysHash.put(keyName, keyPropsHash.get(keyName));
- }
-
- propsAndValuesForMsg = onlyKeysHash.toString() + " combined with a Dependent [" + depNodeVal.<String>property("aai-node-type").orElse(null) + "] node.";
- ArrayList<TitanVertex> resultList = DbMeth.getConnectedNodes(transId, fromAppId, graph, nodeType, onlyKeysHash,
- depNodeVal, apiVersion, false);
- if( resultList.size() > 1 ){
- // More than one vertex found when we thought there should only be one.
- throw new AAIException("AAI_6112", "More than one Node found by getUniqueNode for params: " + propsAndValuesForMsg);
- }
- else if( resultList.size() == 1 ){
- tiV = resultList.get(0);
- }
- }
-
- if( tiV == null ){
- // No Vertex was found for this key - throw a not-found exception
- throw new AAIException("AAI_6114", "No Node of type " + nodeType + " found for properties: " + propsAndValuesForMsg);
- }
- else {
- if( !DbEdgeRules.NodeTypeCategory.containsKey(nodeType) ){
- // The nodeType passed in was a real one, not a nodeTypeCategory, so we will
- // use it as part of the query to make sure we find the right type of node.
- // This can be an issue if they're using nodeTypes covered by a nodeTypeCategory but
- // pass in the wrong nodeType. We don't want them to ask for one thing and get the other.
- String foundNodeType = tiV.<String>property("aai-node-type").orElse(null);
- if( foundNodeType != null && !foundNodeType.equals(nodeType) ){
- throw new AAIException("AAI_6114", "No Node of type " + nodeType + " found for properties: " + propsAndValuesForMsg + " (did find a " + foundNodeType + " though.)");
- }
- }
-
- return tiV;
- }
-
- }// End of getUniqueNode()
-
- /**
- * Gets the unique node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param keyPropsHash the key props hash
- * @param depNodeVal the dep node val
- * @return the unique node
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanVertex getUniqueNode( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> keyPropsHash, TitanVertex depNodeVal) throws AAIException {
- return getUniqueNode( transId, fromAppId, graph, nodeType,
- keyPropsHash, depNodeVal, null );
- }
- // End getUniqueNode()
-
-
- /**
- * Gets the unique node with dep params.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param nodePropsHash the node props hash
- * @param apiVersion the api version
- * @return TitanVertex
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanVertex getUniqueNodeWithDepParams( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> nodePropsHash, String apiVersion )
- throws AAIException{
- /*
- * This method uses the nodePropsHash to walk back over dependent nodes until it finds one that
- * does not depend on any other for uniqueness. It uses the getUniqueNode() method as it finds
- * dependent nodes. NOTE -- it is passed a hash of all the nodeProperties -- for itself and
- * for any dependent nodes that it will need to find. There are some types of nodes that can
- * depend on more than one node, we assume that there wouldn't be a case where BOTH types of
- * dependent nodes are in the trail that we need to traverse. Ie. an ipaddress can depend on
- * either a vserver or pserver. NOTE this case can now happen -- nodePropsHash
- * should now be sent as a LinkedHashMap in this case so we can search in order.
- */
-
- // NOTE ALSO -- We're currently supporting 6 layers of dependency. We never thought there would be this
- // many layers before hitting a node-type that would be uniquely identifiable on it's own. So the
- // code is a little ugly with all these nested if-then-else's. Since we're supporting so many
- // layers, it should be re-written so we can support "n" layers instead of having to go in hear
- // and adding code... But as of 15-07, we really don't NEED more than 5.
-
- // NOTE: The passed in nodeType could really be a nodeTypeCategory --
- // The calls to figureDepNodeTypeForRequest() below will deal with it for the dep nodes, the
- // call to getUniqueNode() takes care of it for the node itself.
-
- TitanVertex nullVert = null;
- String depNodeType = figureDepNodeTypeForRequest( transId, fromAppId, nodeType, nodePropsHash, apiVersion );
- if( depNodeType.equals("")){
- // This kind of node does not depend on another node for uniqueness, so
- // we can just use the "getUniqueNode()" method to get it.
- HashMap <String,Object> thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, nodeType, nodePropsHash, apiVersion);
- return( getUniqueNode(transId, fromAppId, graph, nodeType, thisNodeTypeParamHash, nullVert, apiVersion) );
- }
- else {
- // Will need to find the second-layer dependent node
- String secondLayerDepNodeType = figureDepNodeTypeForRequest( transId, fromAppId, depNodeType, nodePropsHash, apiVersion );
- if( secondLayerDepNodeType.equals("")){
- // This second-layer kind of node does not depend on another node for uniqueness.
- // So once we find the second-layer node, we can use it to get the top-layer guy.
- HashMap <String,Object> thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, depNodeType, nodePropsHash, apiVersion);
- TitanVertex secLayerDepVert = getUniqueNode(transId, fromAppId, graph, depNodeType, thisNodeTypeParamHash, nullVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, nodeType, nodePropsHash, apiVersion);
- return( getUniqueNode(transId, fromAppId, graph, nodeType, thisNodeTypeParamHash, secLayerDepVert, apiVersion) );
- }
- else {
- // Will need to find the third-layer dependent node
- /// String thirdLayerDepNodeType = dbMaps.NodeDependencies.get(secondLayerDepNodeType);
- String thirdLayerDepNodeType = figureDepNodeTypeForRequest( transId, fromAppId, secondLayerDepNodeType, nodePropsHash, apiVersion );
-
- if( thirdLayerDepNodeType.equals("")){
- // This third-layer kind of node does not depend on another node for uniqueness.
- // So we can find it, and then use it to find the second-layer and then use that to find the top guy.
- HashMap <String,Object> thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, secondLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex thirdLayerDepVert = getUniqueNode(transId, fromAppId, graph, secondLayerDepNodeType, thisNodeTypeParamHash, nullVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, depNodeType, nodePropsHash, apiVersion);
- TitanVertex secLayerDepVert = getUniqueNode(transId, fromAppId, graph, depNodeType, thisNodeTypeParamHash, thirdLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, nodeType, nodePropsHash, apiVersion);
-
- return( getUniqueNode(transId, fromAppId, graph, nodeType, thisNodeTypeParamHash, secLayerDepVert, apiVersion) );
- }
- else {
- // Will need to find the third-layer dependent node
- String forthLayerDepNodeType = figureDepNodeTypeForRequest( transId, fromAppId, thirdLayerDepNodeType, nodePropsHash, apiVersion );
- if( forthLayerDepNodeType == null || forthLayerDepNodeType.equals("")){
- // This forth-layer kind of node does not depend on another node for uniqueness.
- // So we can find it, and then use it to find the third, then second-layer and then use that to find the top guy.
- HashMap <String,Object> thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, thirdLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex forthLayerDepVert = getUniqueNode(transId, fromAppId, graph, thirdLayerDepNodeType, thisNodeTypeParamHash, nullVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, secondLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex thirdLayerDepVert = getUniqueNode(transId, fromAppId, graph, secondLayerDepNodeType, thisNodeTypeParamHash, forthLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, depNodeType, nodePropsHash, apiVersion);
- TitanVertex secLayerDepVert = getUniqueNode(transId, fromAppId, graph, depNodeType, thisNodeTypeParamHash, thirdLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, nodeType, nodePropsHash, apiVersion);
- return( getUniqueNode(transId, fromAppId, graph, nodeType, thisNodeTypeParamHash, secLayerDepVert, apiVersion) );
- }
- else {
- // Will need to find the forth-layer dependent node
- String fifthLayerDepNodeType = figureDepNodeTypeForRequest( transId, fromAppId, forthLayerDepNodeType, nodePropsHash, apiVersion );
- if( fifthLayerDepNodeType == null || fifthLayerDepNodeType.equals("")){
- // This fifth-layer kind of node does not depend on another node for uniqueness.
- // So we can find it, and then use it to find the forth, third, then second-layer and then use that to find the top guy.
- HashMap <String,Object> thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, forthLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex fifthLayerDepVert = getUniqueNode(transId, fromAppId, graph, forthLayerDepNodeType, thisNodeTypeParamHash, nullVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, thirdLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex forthLayerDepVert = getUniqueNode(transId, fromAppId, graph, thirdLayerDepNodeType, thisNodeTypeParamHash, fifthLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, secondLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex thirdLayerDepVert = getUniqueNode(transId, fromAppId, graph, secondLayerDepNodeType, thisNodeTypeParamHash, forthLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, depNodeType, nodePropsHash, apiVersion);
- TitanVertex secLayerDepVert = getUniqueNode(transId, fromAppId, graph, depNodeType, thisNodeTypeParamHash, thirdLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, nodeType, nodePropsHash, apiVersion);
- return( getUniqueNode(transId, fromAppId, graph, nodeType, thisNodeTypeParamHash, secLayerDepVert, apiVersion) );
- }
- else {
- // Will need to find the fifth-layer dependent node
- String sixthLayerDepNodeType = figureDepNodeTypeForRequest( transId, fromAppId, fifthLayerDepNodeType, nodePropsHash, apiVersion );
- if( sixthLayerDepNodeType == null || sixthLayerDepNodeType.equals("")){
- // This six-layer kind of node does not depend on another node for uniqueness.
- // So we can find it, and then use it to find the fifth, forth, third, then second-layer and then use that to find the top guy.
- HashMap <String,Object> thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, fifthLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex sixthLayerDepVert = getUniqueNode(transId, fromAppId, graph, fifthLayerDepNodeType, thisNodeTypeParamHash, nullVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, forthLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex fifthLayerDepVert = getUniqueNode(transId, fromAppId, graph, forthLayerDepNodeType, thisNodeTypeParamHash, sixthLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, thirdLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex forthLayerDepVert = getUniqueNode(transId, fromAppId, graph, thirdLayerDepNodeType, thisNodeTypeParamHash, fifthLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, secondLayerDepNodeType, nodePropsHash, apiVersion);
- TitanVertex thirdLayerDepVert = getUniqueNode(transId, fromAppId, graph, secondLayerDepNodeType, thisNodeTypeParamHash, forthLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, depNodeType, nodePropsHash, apiVersion);
- TitanVertex secLayerDepVert = getUniqueNode(transId, fromAppId, graph, depNodeType, thisNodeTypeParamHash, thirdLayerDepVert, apiVersion);
-
- thisNodeTypeParamHash = getThisNodeTypeParams(transId, fromAppId, nodeType, nodePropsHash, apiVersion);
- return( getUniqueNode(transId, fromAppId, graph, nodeType, thisNodeTypeParamHash, secLayerDepVert, apiVersion) );
- }
- else {
- // We don't currently support more layers. We can later if we need to.
- // Hopefully, we'll never need to go this deep -- there should be unique keys in there somewhere!
- throw new AAIException("AAI_6114", "CODE-LIMITATION - Can't resolve dependant node layers for nodeType = " + nodeType);
- }
- }
- }
- }
- }
- }
- } // End getUniqueNodeWithDepParams()
-
- /**
- * Gets the unique node with dep params.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param nodePropsHash the node props hash
- * @return the unique node with dep params
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanVertex getUniqueNodeWithDepParams( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> nodePropsHash ) throws AAIException {
- return getUniqueNodeWithDepParams(transId, fromAppId, graph, nodeType, nodePropsHash, null);
- }
-
-
- /**
- * Gets the this node type params.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param targetNodeType the target node type
- * @param passedHash the passed hash
- * @param apiVersion the api version
- * @return the this node type params
- * @throws AAIException the AAI exception
- */
- private static HashMap <String, Object> getThisNodeTypeParams(String transId, String fromAppId, String targetNodeType,
- HashMap<String,Object> passedHash, String apiVersion )throws AAIException{
- /*
- * For the passed-in hash, each key is assumed to look like, "nodeType.paramName". We want to
- * pick out the entries that match the targetNodeType and return those with the values they go with. The
- * returned keys will have the "nodeType." stripped off.
- *
- * NOTE - the nodeType passed to this method could actually be a nodeTypeCategory. Just keepin it ugly.
- */
-
- if( passedHash == null ){
- throw new AAIException("AAI_6120", "Bad param: null passedHash ");
- }
-
- String targetNodeTypeCat = "";
- if( DbEdgeRules.NodeTypeCatMap.containsKey(targetNodeType) ){
- targetNodeTypeCat = DbEdgeRules.NodeTypeCatMap.get(targetNodeType);
- }
-
- HashMap <String,Object> returnHash = new HashMap <String,Object> ();
- Iterator <Map.Entry<String,Object>>it = passedHash.entrySet().iterator();
- while( it.hasNext() ){
- Map.Entry <String,Object>pairs = (Map.Entry<String,Object>)it.next();
- String k = (pairs.getKey()).toString();
- int periodLoc = k.indexOf(".");
- if( periodLoc <= 0 ){
- throw new AAIException("AAI_6120", "Bad filter param key passed in: [" + k + "]. Expected format = [nodeName.paramName]\n");
- }
- else {
- String nty = k.substring(0,periodLoc);
- String paramName = k.substring(periodLoc + 1);
- if( nty.equals(targetNodeType) || (!targetNodeTypeCat.equals("") && nty.equals(targetNodeTypeCat)) ){
- String newK = paramName;
- returnHash.put( newK,pairs.getValue() );
- }
- }
- }
-
- //aaiLogger.debug(logline, " - end ");
- return returnHash;
-
- }// End of getThisNodeTypeParams()
-
- /**
- * Gets the this node type params.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param targetNodeType the target node type
- * @param passedHash the passed hash
- * @return the this node type params
- * @throws AAIException the AAI exception
- */
- @Deprecated
- private static HashMap <String, Object> getThisNodeTypeParams(String transId, String fromAppId, String targetNodeType,
- HashMap<String,Object> passedHash )throws AAIException{
- return getThisNodeTypeParams( transId, fromAppId, targetNodeType,
- passedHash, null);
-
- }
-
- /**
- * Gets the dep node types.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param apiVersion the api version
- * @return the dep node types
- * @throws AAIException the AAI exception
- */
- public static ArrayList <String> getDepNodeTypes(String transId, String fromAppId, String nodeType, String apiVersion)throws AAIException{
- /*
- * This returns any nodeTypes that this nodeType can be dependent on. A particular instance of a node will only
- * depend on one other node - we don't currently support dependence on multiple nodes.
- */
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- ArrayList <String> depNodeTypeL = new ArrayList <String> ();
- if( !DbEdgeRules.NodeTypeCategory.containsKey(nodeType) ){
- // This is a good-ole nodeType
- Collection <String> depNTColl = dbMaps.NodeDependencies.get(nodeType);
- Iterator <String> ntItr = depNTColl.iterator();
- while( ntItr.hasNext() ){
- depNodeTypeL.add(ntItr.next());
- }
- }
- else {
- // The passed-in nodeType must really be a nodeTypeCategory
- Collection <String> nTypeCatCol = DbEdgeRules.NodeTypeCategory.get(nodeType);
- Iterator <String> catItr = nTypeCatCol.iterator();
- String catInfo = "";
- if( catItr.hasNext() ){
- // For now, we only look for one.
- catInfo = catItr.next();
- }
- else {
- throw new AAIException("AAI_6121", "Error getting DbEdgeRules.NodeTypeCategory info for nodeTypeCat = " + nodeType);
- }
-
- String [] flds = catInfo.split(",");
- if( flds.length != 4 ){
- throw new AAIException("AAI_6121", "Bad EdgeRule.NodeTypeCategory data (itemCount=" + flds.length + ") for nodeType = [" + nodeType + "].");
- }
-
- String nodeTypesString = flds[0];
- String hasDepNodes = flds[3];
- if( hasDepNodes.equals("true") ){
- String [] ntNames = nodeTypesString.split("\\|");
- for( int i = 0; i < ntNames.length; i++ ){
- Collection <String> depNTColl = dbMaps.NodeDependencies.get(nodeType);
- Iterator <String> ntItr = depNTColl.iterator();
- while( ntItr.hasNext() ){
- String depNode = ntItr.next();
- if( !depNodeTypeL.contains(depNode) ){
- depNodeTypeL.add(depNode);
- }
- }
- }
- }
- }
-
-
- return depNodeTypeL;
-
- }// End getDepNodeTypes()
-
- /**
- * Gets the dep node types.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @return the dep node types
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static ArrayList <String> getDepNodeTypes(String transId, String fromAppId, String nodeType)throws AAIException{
- return getDepNodeTypes( transId, fromAppId, nodeType, null);
- }
-
- /**
- * Gets the default delete scope.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param apiVersion the api version
- * @return the default delete scope
- * @throws AAIException the AAI exception
- */
- private static String getDefaultDeleteScope(String transId, String fromAppId, String nodeType, String apiVersion)throws AAIException{
-
- // At some point we may have different delete rules for different services, so this is
- // a list for now even thought there's only one scope per nodeType.
- Collection <String> scopeList = DbEdgeRules.DefaultDeleteScope.get(nodeType);
- if( scopeList.isEmpty() ){
- throw new AAIException("AAI_6121", "No default deleteScope found for nodeType = [" + nodeType + "] ");
- }
- else {
- Iterator <String> ito = scopeList.iterator();
- return ito.next();
- }
-
- }// End getDefaultDeleteScope()
-
- /**
- * Gets the default delete scope.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @return the default delete scope
- * @throws AAIException the AAI exception
- */
- @Deprecated
- private static String getDefaultDeleteScope(String transId, String fromAppId, String nodeType)throws AAIException{
- return getDefaultDeleteScope( transId, fromAppId, nodeType, null);
- }
-
- /**
- * Needs A dep node 4 uniqueness.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param apiVersion the api version
- * @return the boolean
- * @throws AAIException the AAI exception
- */
- public static Boolean needsADepNode4Uniqueness(String transId, String fromAppId, String nodeType, String apiVersion)throws AAIException{
- // Note: the passed in nodeType could really be a nodeTypeCategory. That is handled by getDepNodeTypes()
-
- ArrayList <String> depList = getDepNodeTypes(transId, fromAppId, nodeType, apiVersion);
- if( depList.isEmpty() ){
- return false;
- }
- else {
- return true;
- }
-
- }// End needsADepNode4Uniqueness()
-
- /**
- * Needs A dep node 4 uniqueness.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @return the boolean
- * @throws AAIException the AAI exception
- */
- @Deprecated
- private static Boolean needsADepNode4Uniqueness(String transId, String fromAppId, String nodeType)throws AAIException{
- return needsADepNode4Uniqueness( transId, fromAppId, nodeType, null);
- }
-
- /**
- * Node type A can depend on B.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeTypeA the node type A
- * @param nodeTypeB the node type B
- * @param apiVersion the api version
- * @return the boolean
- * @throws AAIException the AAI exception
- */
- public static Boolean nodeTypeACanDependOnB(String transId, String fromAppId, String nodeTypeA, String nodeTypeB, String apiVersion)
- throws AAIException{
- // Note: the passed in nodeType could really be a nodeTypeCategory. That is handled by getDepNodeTypes()
-
- ArrayList <String> depList = getDepNodeTypes(transId, fromAppId, nodeTypeA, apiVersion);
- if( depList.isEmpty() ){
- return false;
- }
- else if( depList.contains(nodeTypeB) ){
- return true;
- }
- else {
- return false;
- }
-
- }// End nodeTypeACanDependOnB()
-
- /**
- * Node type A can depend on B.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeTypeA the node type A
- * @param nodeTypeB the node type B
- * @return the boolean
- * @throws AAIException the AAI exception
- */
- @Deprecated
- private static Boolean nodeTypeACanDependOnB(String transId, String fromAppId, String nodeTypeA, String nodeTypeB)
- throws AAIException{
- return nodeTypeACanDependOnB( transId, fromAppId, nodeTypeA, nodeTypeB, null);
- }
-
- /**
- * Figure dep node type for request.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param requestParamHash the request param hash
- * @param apiVersion the api version
- * @return the string
- * @throws AAIException the AAI exception
- */
- public static String figureDepNodeTypeForRequest(String transId, String fromAppId, String nodeType,
- HashMap<String,Object> requestParamHash, String apiVersion )throws AAIException{
- /*
- * This is ugly. But if the passed-in nodeType is dependent on another nodeType for
- * uniqueness, we need to return what that dependent node-type is. The ugly comes in
- * because a node can be dependent on more than one type of node. So, to tell which one
- * is going to apply, we root through the passed request parameters to see which of
- * the possible dependent node types is being used.
- * Note -- if there comes a day when there are so many dependencies that the request could
- * have more than one that match -- Then we need to think up something new. But for now,
- * we have to assume that if there are more than one legal dep-node-types, only one will
- * be represented in the requestHash data. >>> NOTE >>> That day has come. For
- * the upstreamers will send in a LinkedHashMap instead of just an unordered
- * HashMap so we can look in order for the dependent node.
- *
- */
-
- if( requestParamHash == null ){
- throw new AAIException("AAI_6120", "Bad param: null requestParamHash ");
- }
-
- ArrayList <String> depNodeTypes = getDepNodeTypes(transId, fromAppId, nodeType, apiVersion);
- if( depNodeTypes.isEmpty() ){
- // This kind of node is not dependent on any other
- //aaiLogger.debug(logline, " (not dependent) - end ");
- return "";
- }
- else if( depNodeTypes.size() == 1 ){
- // This kind of node can only depend on one other nodeType - so return that.
- //aaiLogger.debug(logline, " (depends on " + depNodeTypes.get(0) + " - end ");
- return depNodeTypes.get(0);
- }
- else {
- // We need to look to find the first of the dep-node types that is represented in the passed-in
- // request data. That will be the one we need to use.
-
- // first find out what node-types are represented in the requestHash
-
- Iterator <Map.Entry<String,Object>>it = requestParamHash.entrySet().iterator();
- while( it.hasNext() ){
- Map.Entry <String,Object>pairs = (Map.Entry<String,Object>)it.next();
- String k = (pairs.getKey()).toString();
- int periodLoc = k.indexOf(".");
- if( periodLoc <= 0 ){
- throw new AAIException("AAI_6120", "Bad filter param key passed in: [" + k + "]. Expected format = [nodeName.paramName]\n");
- }
- else {
- String nty = k.substring(0,periodLoc);
- if( depNodeTypes.contains(nty) ){
- // This is the first possible dep. node type we've found for the passed in data set
- return nty;
- }
- }
- }
-
- }
-
- // It's not an error if none is found - the caller needs to deal with cases where there
- // should be a dep. node identified but isn't.
- //aaiLogger.debug(logline, " no dep NT found - end ");
- return "";
-
- }// End of figureDepNodeTypeForRequest()
-
- /**
- * Figure dep node type for request.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param requestParamHash the request param hash
- * @return the string
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static String figureDepNodeTypeForRequest(String transId, String fromAppId, String nodeType,
- HashMap<String,Object> requestParamHash )throws AAIException{
- return figureDepNodeTypeForRequest( transId, fromAppId, nodeType, requestParamHash, null);
- }
-
- /**
- * Detach connected nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param startNodeVal the start node val
- * @param autoDeleteOrphans the auto delete orphans
- * @param apiVersion the api version
- * @return deletedNodeCount
- * @throws AAIException the AAI exception
- */
- public static int detachConnectedNodes( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, TitanVertex startNodeVal, boolean autoDeleteOrphans, String apiVersion ) throws AAIException{
-
- /* Find nodes that are attached to this node which meet the nodeType/filterParams criteria.
- * Remove the edges that go to those nodes.
- * If that turns any of the nodes into an orphan, then delete it if the autoDeleteOrphans flag is set.
- * Return a count of how many nodes were actually deleted (not just detached).
- */
-
- int deletedCount = 0;
-
- if( startNodeVal == null ){
- // They should have passed in the node that this query starts from
- throw new AAIException("AAI_6109", "null startNode object passed to detachConnectedNodes().");
- }
-
- // We want to loop through the connected Nodes that we found.
- // For each connected Node, we'll get the all edges that start from that node and look for the one
- // that connects back to our startNode.
- // Only delete the edge that connects back to our startNode.
- // then autoDeleteOrphans flag is set, then delete the connectedNode if it's now orphaned.
- //
-
- String startNodeVId = startNodeVal.id().toString();
- ArrayList<TitanVertex> conNodeList = getConnectedNodes( transId, fromAppId, graph, nodeType, propFilterHash, startNodeVal, apiVersion, false );
- Iterator<TitanVertex> conVIter = conNodeList.iterator();
- while( conVIter.hasNext() ){
- TitanVertex connectedVert = conVIter.next();
- boolean isFirstOne = true;
- Iterator<Edge> eI = connectedVert.edges(Direction.BOTH);
- while( eI.hasNext() ){
- TitanEdge ed = (TitanEdge) eI.next();
- TitanVertex otherVtx = (TitanVertex) ed.otherVertex(connectedVert);
- String otherSideLookingBackVId = otherVtx.id().toString();
- if( startNodeVId.equals(otherSideLookingBackVId) ){
- // This is an edge from the connected node back to our starting node
- if( isFirstOne && !eI.hasNext() && autoDeleteOrphans ){
- // This was the one and only edge for this connectedNode, so
- // delete the node and edge since flag was set
- String resVers = connectedVert.<String>property("resource-version").orElse(null);
- removeAaiNode( transId, fromAppId, graph, connectedVert, "USE_DEFAULT", apiVersion, resVers);
- deletedCount = deletedCount + 1;
- }
- else {
- removeAaiEdge( transId, fromAppId, graph, ed );
- }
- }
- isFirstOne = false;
- }
- }
- return deletedCount;
-
- } // end of detachConnectedNodes()
-
-
-
- /**
- * Detach connected nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param startNodeVal the start node val
- * @param autoDeleteOrphans the auto delete orphans
- * @return the int
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static int detachConnectedNodes( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, TitanVertex startNodeVal, boolean autoDeleteOrphans ) throws AAIException{
- return detachConnectedNodes( transId, fromAppId, graph, nodeType,
- propFilterHash, startNodeVal, autoDeleteOrphans, null);
- }
-
- /**
- * Gets the nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param noFilterOnPurpose the no filter on purpose
- * @param apiVersion the api version
- * @return ArrayList<TitanVertex>
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static ArrayList<TitanVertex> getNodes( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, Boolean noFilterOnPurpose, String apiVersion ) throws AAIException{
- boolean skipGroomingFlag = true;
- // we will only do real-time grooming if a system variable is set, telling us not to skip it.
- String skipGroomingStr = AAIConstants.AAI_SKIPREALTIME_GROOMING;
- if( skipGroomingStr.equals("false") ){
- skipGroomingFlag = false;
- }
- return( getNodes(transId, fromAppId, graph, nodeType, propFilterHash, noFilterOnPurpose, apiVersion, skipGroomingFlag) );
- }
-
- /**
- * Gets the nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param noFilterOnPurpose the no filter on purpose
- * @param apiVersion the api version
- * @param skipGroomCheck the skip groom check
- * @return ArrayList<TitanVertex>
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static ArrayList<TitanVertex> getNodes( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, Boolean noFilterOnPurpose, String apiVersion, boolean skipGroomCheck )
- throws AAIException{
- // Note - the skipGroomCheck flag is set to true when the DataGrooming tool is using this method to collect
- // node data. When the grooming tool is collecting data, we don't want any nodes skipped, because we
- // want details about what nodes/edges are bad - more detail than the check in this method does
- // as it checks if a node is ok to return to a caller.
-
- /* Use the nodeType + filterParams to find nodes.
- */
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- ArrayList<TitanVertex> returnVertList = new ArrayList<TitanVertex>();
- if( nodeType == null || nodeType.equals("") ){
- // They should have passed in a nodeType
- throw new AAIException("AAI_6118", "Required field: nodeType not passed to getNodes().");
- }
-
- if( !noFilterOnPurpose && (propFilterHash == null || propFilterHash.isEmpty()) ){
- // They should have passed at least one property to filter on
- throw new AAIException("AAI_6118", "Required field: propFilterHash not passed to getNodes().");
- }
-
- ArrayList<String> kName = new ArrayList<String>();
- ArrayList<Object> kVal = new ArrayList<Object>();
- int i = -1;
- Collection <String> indexedProps = dbMaps.NodeMapIndexedProps.get(nodeType);
- // First loop through to pick up the indexed-properties if there are any being used
-
- if( propFilterHash != null ){
- Iterator <?> it = propFilterHash.entrySet().iterator();
- while( it.hasNext() ){
- Map.Entry<?,?> propEntry = (Map.Entry<?,?>) it.next();
- String propName = (propEntry.getKey()).toString();
- // Don't allow search on properties that do not have SINGLE cardinality
- if( !checkPropCardinality(propName, "Set") && !checkPropCardinality(propName, "List") ){
- if( indexedProps.contains(propName) ){
- i++;
- kName.add(i, propName);
- kVal.add(i, (Object)propEntry.getValue());
- }
- }
- }
-
- // Now go through again and pick up the non-indexed properties
- it = propFilterHash.entrySet().iterator();
- while( it.hasNext() ){
- Map.Entry <?,?> propEntry = (Map.Entry<?,?>)it.next();
- String propName = (propEntry.getKey()).toString();
- // Don't allow search on properties that do not have SINGLE cardinality
- if( !checkPropCardinality(propName, "Set") && !checkPropCardinality(propName, "List") ){
- if( ! indexedProps.contains(propName) ){
- i++;
- kName.add(i, propName);
- kVal.add(i, (Object)propEntry.getValue());
- }
- }
- }
- }
-
- Iterable <?> verts = null;
- String propsAndValuesForMsg = "";
- int topPropIndex = i;
- if( topPropIndex == -1 ){
- // No Filtering -- just go get them all
- verts= graph.query().has("aai-node-type",nodeType).vertices();
- propsAndValuesForMsg = " ( no filter props ) ";
- }
- else if( topPropIndex == 0 ){
- verts= graph.query().has(kName.get(0),kVal.get(0)).has("aai-node-type",nodeType).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ") ";
- }
- else if( topPropIndex == 1 ){
- verts= graph.query().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has("aai-node-type",nodeType).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
- + kName.get(1) + " = " + kVal.get(1) + ") ";
- }
- else if( topPropIndex == 2 ){
- verts= graph.query().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has("aai-node-type",nodeType).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
- + kName.get(1) + " = " + kVal.get(1) + ", "
- + kName.get(2) + " = " + kVal.get(2) + ") ";
- }
- else if( topPropIndex == 3 ){
- verts= graph.query().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has(kName.get(3),kVal.get(3)).has("aai-node-type",nodeType).vertices();
- propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", "
- + kName.get(1) + " = " + kVal.get(1) + ", "
- + kName.get(2) + " = " + kVal.get(2) + ", "
- + kName.get(3) + " = " + kVal.get(3) + ") ";
- }
- else {
- String emsg = " -- Sorry -- we only support 4 filter properties in getNodes() for now... \n";
- throw new AAIException("AAI_6114", emsg);
- }
- if( verts != null ){
- // We did find some matching vertices
- Iterator <?> it = verts.iterator();
- while( it.hasNext() ){
- TitanVertex v = (TitanVertex)it.next();
-
- if( skipGroomCheck ){
- // Good or bad, just return everything we find
- returnVertList.add( v );
- }
- else {
- // Weed out any bad vertices we find
- if( thisVertexNotReachable(transId, fromAppId, graph, v, apiVersion) ){
- LOGGER.info("IN-LINE GROOMING - Unreachable Node DETECTED > skipping it. ");
- }
- else if( thisVertexHasBadEdges(transId, fromAppId, graph, v, apiVersion) ){
- LOGGER.info("IN-LINE GROOMING - BAD EDGE DETECTED > skipping vtxId = [" + v.id() + "] ");
- }
- else if( thisVertexIsAPhantom(transId, fromAppId, graph, v, apiVersion) ){
- LOGGER.info("IN-LINE GROOMING - BAD NODE DETECTED > skipping vtxId = [" + v.id() + "] ");
- }
- else {
- returnVertList.add( v );
- }
- }
- }
- }
-
- return returnVertList;
- }
-
- /**
- * Gets the nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param noFilterOnPurpose the no filter on purpose
- * @return the nodes
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static ArrayList<TitanVertex> getNodes( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, Boolean noFilterOnPurpose ) throws AAIException{
- return getNodes(transId, fromAppId, graph, nodeType,
- propFilterHash, noFilterOnPurpose, null );
- }
- // End of getNodes()
-
-
- /**
- * Gets the connected children.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param startVtx the start vtx
- * @param limitToThisNodeType the limit to this node type
- * @return ArrayList <TitanVertex>
- * @throws AAIException the AAI exception
- */
- public static ArrayList<TitanVertex> getConnectedChildren( String transId, String fromAppId, TitanTransaction graph,
- TitanVertex startVtx, String limitToThisNodeType ) throws AAIException{
-
- // Just get child nodes (ie. other end of an OUT edge that is tagged as a parent/Child edge)
-
- ArrayList <TitanVertex> childList = new ArrayList <TitanVertex> ();
- Boolean doNodeTypeCheck = false;
- if( limitToThisNodeType != null && ! limitToThisNodeType.equals("") ){
- doNodeTypeCheck = true;
- }
-
-
- List<Vertex> verts = graph.traversal().V(startVtx).union(__.inE().has("isParent-REV", true).outV(), __.outE().has("isParent", true).inV()).toList();
- TitanVertex tmpVtx = null;
- int vertsSize = verts.size();
- for (int i = 0; i < vertsSize; i++){
- tmpVtx = (TitanVertex) verts.get(i);
- if( ! doNodeTypeCheck ){
- childList.add(tmpVtx);
- }
- else {
- String tmpNT = tmpVtx.<String>property("aai-node-type").orElse(null);
- if( tmpNT != null && tmpNT.equals(limitToThisNodeType) ){
- childList.add(tmpVtx);
- }
- }
- }
-
- return childList;
-
- }// End of getConnectedChildren()
-
-
-
- /**
- * Gets the connected nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param startNodeVal the start node val
- * @param apiVersion the api version
- * @param excludeRecurComingIn the exclude recur coming in
- * @return ArrayList <TitanVertex>
- * @throws AAIException the AAI exception
- */
- public static ArrayList<TitanVertex> getConnectedNodes( String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, TitanVertex startNodeVal, String apiVersion, Boolean excludeRecurComingIn ) throws AAIException{
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
- /* Get (almost) all the nodes that are connected to this vertex.
- * Narrow down what is returned using optional filter parameters nodeType and propFilterHash
- * NOTE - the default behavior has changed slightly. For start-Nodes that
- * can be recursivly connected, this method will only bring back the same kind of
- * connected node by following an OUT edge. Ie. if the start node is an "model-element",
- * then this method will only follow OUT edges to get to other "model-element" type nodes.
- */
-
- String startNodeNT = "";
- if( startNodeVal == null ){
- // They should have passed in the node that this query starts from
- throw new AAIException("AAI_6109", "null startNode object passed to getConnectedNodes().");
- }
- else {
- startNodeNT = startNodeVal.<String>property("aai-node-type").orElse(null);
- }
-
- boolean nodeTypeFilter = false;
- if( nodeType != null && !nodeType.equals("") ){
- // They want to filter using nodeType
- if( ! dbMaps.NodeProps.containsKey(nodeType) ){
- throw new AAIException("AAI_6115", "Unrecognized nodeType [" + nodeType + "] passed to getConnectedNodes().");
- }
- nodeTypeFilter = true;
- }
-
- ArrayList <String> excludeVidList = new <String> ArrayList ();
- if( DbEdgeRules.CanBeRecursiveNT.containsKey(startNodeNT) && excludeRecurComingIn ){
- // If we're starting on a nodeType that supports recursion, then find any connected
- // nodes that are coming from IN edges so we can exclude them later.
-
- Iterable <?> vertsR = startNodeVal.query().direction(Direction.IN).vertices();
- Iterator <?> vertIR = vertsR.iterator();
- while( vertIR != null && vertIR.hasNext() ){
- TitanVertex tmpVertIN = (TitanVertex) vertIR.next();
- String tmpNT = tmpVertIN.<String>property("aai-node-type").orElse(null);
- if( tmpNT != null && tmpNT.equals(startNodeNT) ){
- // We're on a nodetype that supports recursion (like model-element) and we've
- // found an connected Node of this same type on an IN edge - put this
- // on our excludeList.
- excludeVidList.add( tmpVertIN.id().toString() );
- }
- }
- }
-
- boolean propertyFilter = false;
- if( propFilterHash != null && !propFilterHash.isEmpty() ){
- // They want to filter using some properties
- Iterator <?> it = propFilterHash.entrySet().iterator();
- while( it.hasNext() ){
- Map.Entry<?,?> propEntry = (Map.Entry<?,?>)it.next();
- String propName = (propEntry.getKey()).toString();
- if( ! dbMaps.NodeProps.containsValue(propName) ){
- throw new AAIException("AAI_6116", "Unrecognized property name [" + propName + "] passed to getConnectedNodes().");
- }
- // Don't allow search on properties that do not have SINGLE cardinality
- if( !checkPropCardinality(propName, "Set") && !checkPropCardinality(propName, "List") ){
- propertyFilter = true;
- }
- }
- }
- // If filter-properties were passed in, then look for nodes that have those values.
- ArrayList<TitanVertex> returnVertList = new ArrayList<TitanVertex>();
- Iterable<TitanVertex> qResult = null;
- Iterator<TitanVertex> resultI = null;
- try {
- qResult = startNodeVal.query().vertices();
- resultI = qResult.iterator();
- }
- catch( NullPointerException npe ){
- throw new AAIException("AAI_6125", "Titan null pointer exception trying to get nodes connected to vertexId = " +
- startNodeVal.id() + ", aai-node-type = [" + startNodeVal.property("aai-node-type") + "].");
- }
-
- while( resultI != null && resultI.hasNext() ){
- boolean addThisOne = true;
- TitanVertex tmpV = (TitanVertex)resultI.next();
- if( tmpV == null ){
- LOGGER.info("Titan gave a null vertex when looking for nodes connected to vertexId = " +
- startNodeVal.id() + ", aai-node-type = [" + startNodeVal.property("aai-node-type") + "].");
- // Note - we will skip this one, but try to return any others that we find.
- addThisOne = false;
- }
-
- else {
- String tmpVid = tmpV.id().toString();
- if( nodeTypeFilter ){
- Object nto = tmpV.<Object>property("aai-node-type").orElse(null);
- if( nto == null || !nto.toString().equals(nodeType) ){
- //LOGGER.info("Found a connected vertex (vertexId = " +
- // tmpVid + "), but we will not collect it. It had aai-node-type [" +
- // nto + "], we are looking for [" + nodeType + "]. ");
- // Note - we will skip this one, but try to return any others that we find.
- addThisOne = false;
- }
- }
-
- if( excludeVidList.contains(tmpVid) ){
- LOGGER.info("Found a connected vertex (vertexId = " +
- tmpVid + "), but will exclude it since it is on an IN edge and this nodeType " +
- startNodeNT + " can be recursively attached.");
- // Note - we will skip this one, but try to return any others that we find.
- addThisOne = false;
- }
-
- if( propertyFilter ){
- Iterator <?> it = propFilterHash.entrySet().iterator();
- while( it.hasNext() ){
- Map.Entry <?,?>propEntry = (Map.Entry<?,?>)it.next();
- String propName = (propEntry.getKey()).toString();
- if( checkPropCardinality(propName, "Set") || checkPropCardinality(propName, "List") ){
- // Don't allow search on properties that do not have SINGLE cardinality
- continue;
- }
- Object propVal = propEntry.getValue();
- Object foundVal = tmpV.<Object>property(propName).orElse(null);
- if( foundVal != null && propVal != null && !foundVal.toString().equals(propVal.toString()) ){
- addThisOne = false;
- break;
- }
- else if( (foundVal == null && propVal != null) || (foundVal != null && propVal == null) ){
- addThisOne = false;
- break;
- }
- }
- }
- }
- if( addThisOne ){
- // This node passed the tests -- put it on the return List
- returnVertList.add( (TitanVertex)tmpV );
- }
- }
- //aaiLogger.debug(logline, " end ");
- return returnVertList;
-
- }// End of getConnectedNodes()
-
-
- /**
- * Gets the connected nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param startNodeVal the start node val
- * @param apiVersion the api version
- * @return the connected nodes
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static ArrayList<TitanVertex> getConnectedNodes(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, TitanVertex startNodeVal, String apiVersion ) throws AAIException {
- return getConnectedNodes( transId, fromAppId, graph, nodeType,
- propFilterHash, startNodeVal, apiVersion, true );
- }
-
- /**
- * Gets the connected nodes.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param nodeType the node type
- * @param propFilterHash the prop filter hash
- * @param startNodeVal the start node val
- * @return the connected nodes
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static ArrayList<TitanVertex> getConnectedNodes(String transId, String fromAppId, TitanTransaction graph, String nodeType,
- HashMap<String,Object> propFilterHash, TitanVertex startNodeVal ) throws AAIException {
- return getConnectedNodes( transId, fromAppId, graph, nodeType,
- propFilterHash, startNodeVal, null, true );
-
- }
-
- /**
- * Ip address format OK.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param addrVal the addr val
- * @param addrVer the addr ver
- * @param apiVersion the api version
- * @return Boolean
- * @throws AAIException the AAI exception
- */
- public static Boolean ipAddressFormatOK(String transId, String fromAppId, String addrVal, String addrVer, String apiVersion) throws AAIException{
-
- /* NOTE -- the google methods we use do not allow leading zeros in ipV4 addresses.
- * So it will reject, "22.33.44.001"
- */
-
- if( addrVal == null ){
- throw new AAIException("AAI_6120", "Bad data (addrVal = null) passed to ipAddressFormatOK()");
- }
- else if( addrVer == null ){
- throw new AAIException("AAI_6120", "Bad data (addrType = null) passed to ipAddressFormatOK()");
- }
-
- Boolean retVal = false;
- Boolean lookingForV4 = false;
- Boolean lookingForV6 = false;
- InetAddress inetAddr = null;
-
- if( addrVer.equalsIgnoreCase("v4") || addrVer.equals("ipv4") || addrVer.equals("4")){
- lookingForV4 = true;
- }
- else if( addrVer.equalsIgnoreCase("v6") || addrVer.equals("ipv6") || addrVer.equals("6")){
- lookingForV6 = true;
- }
- else {
- throw new AAIException("AAI_6120", " Bad data for addressVersion [" + addrVer + "] passed to ipAddressFormatOK()");
- }
-
- try {
- inetAddr = InetAddresses.forString(addrVal);
- if( inetAddr instanceof Inet4Address ){
- if( lookingForV4 ){
- retVal = true;
- }
- else {
- throw new AAIException("AAI_6120", "Bad data. Address is a V4, but addressType said it should be V6. ["
- + addrVal + "], [" + addrVer + "] passed to ipAddressFormatOK()");
- }
- }
- else if( inetAddr instanceof Inet6Address ){
- if( lookingForV6 ){
- retVal = true;
- }
- else {
- throw new AAIException("AAI_6120", "Bad data. Address is a V6, but addressType said it should be V4. ["
- + addrVal + "], [" + addrVer + "] passed to ipAddressFormatOK().");
- }
- }
- }
- catch (IllegalArgumentException e) {
- throw new AAIException("AAI_6120", "Badly formed ip-address: [" + addrVal + "] passed to ipAddressFormatOK()");
- }
-
- return retVal;
-
- }//end of ipAddressFormatOk()
-
- /**
- * Ip address format OK.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param addrVal the addr val
- * @param addrVer the addr ver
- * @return the boolean
- * @throws AAIException the AAI exception
- */
- public static Boolean ipAddressFormatOK(String transId, String fromAppId, String addrVal, String addrVer) throws AAIException{
- return ipAddressFormatOK( transId, fromAppId, addrVal, addrVer, null);
- }
-
- /**
- * Save aai edge to db.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param edgeLabel the edge label
- * @param outV the out V
- * @param inV the in V
- * @param propHash the prop hash
- * @param apiVersion the api version
- * @return TitanEdge
- * @throws AAIException the AAI exception
- */
- private static TitanEdge saveAaiEdgeToDb(String transId, String fromAppId, TitanTransaction graph, String edgeLabel,
- TitanVertex outV, TitanVertex inV, HashMap <String,Object> propHash, String apiVersion) throws AAIException{
-
- // If this edge doesn't exist yet, then create it.
-
- // NOTE - the Titan javaDoc says that there might not always be an id for a node.
- // This is the internal-titan-unique-id, not any of our data.
- // Not sure how to know when it might be there and when it might not?!
- // So far, it has worked for all my testing, but this might warrant some
- // further investigation.
-
- TitanEdge existingEdge = null;
- String inVId = inV.id().toString();
- Iterator <Edge> eI = outV.edges(Direction.BOTH, edgeLabel);
- while( eI.hasNext() ){
- TitanEdge ed = (TitanEdge) eI.next();
- TitanVertex otherVtx = (TitanVertex) ed.otherVertex(outV);
- if( (otherVtx.id().toString()).equals(inVId) ){
- // NOTE -?- Not sure -- at some point we might want to check the edgeLabels also since we might
- // want to allow two different-type edges between the same two vertexes? (or maybe not.)
- existingEdge = ed;
- break;
- }
- }
-
- if( existingEdge != null ){
- // This is just an UPDATE
- for( Map.Entry<String, Object> entry : propHash.entrySet() ){
- LOGGER.debug("update edge property/val = [" + entry.getKey() + "]/[" + entry.getValue() + "]");
- existingEdge.property( entry.getKey(), entry.getValue() );
- }
-
- return( existingEdge );
- }
- else {
- // This is an ADD
-
- // Uniqueness double-check. This is just to catch the possibility that at the transaction layer,
- // if data came in for two identical nodes that point to the same dependant node (for uniqueness),
- // we would only be able to catch the problem at the time the edge to the second node is added.
- // For example - if they had a VM and then got a request to add two ipAddress nodes, but some
- // bad data was passed and those two ipAddress nodes were identical -- we'd want to catch it.
- String outV_NType = outV.<String>property("aai-node-type").orElse(null);
- String inV_NType = inV.<String>property("aai-node-type").orElse(null);
- if( needsADepNode4Uniqueness(transId, fromAppId, outV_NType, apiVersion)
- && nodeTypeACanDependOnB(transId, fromAppId, outV_NType, inV_NType, apiVersion) ){
- // The out-Vertex has a uniqueness dependency on the in-vertex
- // Make sure we haven't already added an node/edge like this in this transaction
- HashMap <String, Object> nodeKeyPropsHash = getNodeKeyPropHash(transId, fromAppId, graph, outV);
- ArrayList<TitanVertex> resultList = new ArrayList<TitanVertex>();
- resultList = DbMeth.getConnectedNodes("transId", "fromAppId", graph, outV_NType, nodeKeyPropsHash, inV, apiVersion, false);
- if( resultList.size() > 0 ){
- String propInfo = "";
- if( nodeKeyPropsHash != null ){
- propInfo = nodeKeyPropsHash.toString();
- }
- throw new AAIException("AAI_6117", "Failed to add edge. This node (" + inV_NType + ") already has an edge to a " + outV_NType +
- " node with kepProps [" + propInfo + "]");
- }
- }
- else if( needsADepNode4Uniqueness(transId, fromAppId, inV_NType, apiVersion)
- && nodeTypeACanDependOnB(transId, fromAppId, inV_NType, outV_NType, apiVersion) ){
- // The in-Vertex has a uniqueness dependency on the out-vertex
- // Make sure we haven't already added an node/edge like this in this transaction
- HashMap <String, Object> nodeKeyPropsHash = getNodeKeyPropHash(transId, fromAppId, graph, inV);
- ArrayList<TitanVertex> resultList = new ArrayList<TitanVertex>();
- resultList = DbMeth.getConnectedNodes("transId", "fromAppId", graph, inV_NType, nodeKeyPropsHash, outV, apiVersion, false);
- if( resultList.size() > 0 ){
- String propInfo = "";
- if( nodeKeyPropsHash != null ){
- propInfo = nodeKeyPropsHash.toString();
- }
- throw new AAIException("AAI_6117", "Failed to add edge. This node (" + outV_NType + ") already has an edge to a " + inV_NType +
- " node with kepProps [" + propInfo + "]");
- }
- }
-
-
- // We're good to go to add this edge
-
- TitanEdge tEdge = outV.addEdge( edgeLabel, inV );
- // Add the properties to the new Edge
- for( Map.Entry<String, Object> entry : propHash.entrySet() ){
- tEdge.property( entry.getKey(), entry.getValue() );
- }
-
- // For (resource-id updates) we need to "touch" the vertices on each side of the edge so
- // anybody working on one of those vertices will know that something (ADDing this edge) has happened.
- touchVertex( transId, fromAppId, inV );
- touchVertex( transId, fromAppId, outV );
-
- return tEdge;
- }
-
- }// End saveAaiEdgeToDb()
-
-
-
- /**
- * Derive edge rule key for this edge.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param tEdge the t edge
- * @return String - key to look up edgeRule (fromNodeType|toNodeType)
- * @throws AAIException the AAI exception
- */
- public static String deriveEdgeRuleKeyForThisEdge( String transId, String fromAppId, TitanTransaction graph,
- TitanEdge tEdge ) throws AAIException{
-
- TitanVertex fromVtx = tEdge.outVertex();
- TitanVertex toVtx = tEdge.inVertex();
- String startNodeType = fromVtx.<String>property("aai-node-type").orElse(null);
- String targetNodeType = toVtx.<String>property("aai-node-type").orElse(null);
- String key = startNodeType + "|" + targetNodeType;
- if( EdgeRules.getInstance().hasEdgeRule(startNodeType, targetNodeType) ){
- // We can use the node info in the order they were given
- return( key );
- }
- else {
- key = targetNodeType + "|" + startNodeType;
- if( EdgeRules.getInstance().hasEdgeRule(targetNodeType, startNodeType) ){
- return( key );
- }
- else {
- // Couldn't find a rule for this edge
- throw new AAIException("AAI_6120", "No EdgeRule found for passed nodeTypes: " + startNodeType + ", "
- + targetNodeType);
- }
- }
- }// end of deriveEdgeRuleKeyForThisEdge()
-
-
-
- /**
- * Save aai edge to db.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param edgeLabel the edge label
- * @param outV the out V
- * @param inV the in V
- * @param propHash the prop hash
- * @return the titan edge
- * @throws AAIException the AAI exception
- */
- @Deprecated
- private static TitanEdge saveAaiEdgeToDb(String transId, String fromAppId, TitanTransaction graph, String edgeLabel,
- TitanVertex outV, TitanVertex inV, HashMap <String,Object> propHash) throws AAIException{
- return saveAaiEdgeToDb( transId, fromAppId, graph, edgeLabel,
- outV, inV, propHash, null);
- }
-
- /**
- * Persist aai edge.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param startVert the start vert
- * @param targetVert the target vert
- * @param apiVersion the api version
- * @return the titan edge
- * @throws AAIException the AAI exception
- */
- public static TitanEdge persistAaiEdge( String transId, String fromAppId, TitanTransaction graph,
- TitanVertex startVert, TitanVertex targetVert, String apiVersion ) throws AAIException{
- TitanEdge returnEdge = persistAaiEdge(transId, fromAppId, graph, startVert, targetVert, apiVersion, "");
- return returnEdge;
- }
-
- /**
- * Persist aai edge.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param startVert the start vert
- * @param targetVert the target vert
- * @param apiVersion the api version
- * @param edgeType the edge type
- * @return TitanEdge
- * @throws AAIException the AAI exception
- */
- public static TitanEdge persistAaiEdge( String transId, String fromAppId, TitanTransaction graph,
- TitanVertex startVert, TitanVertex targetVert, String apiVersion, String edgeType ) throws AAIException{
-
- TitanVertex fromVtx = null;
- TitanVertex toVtx = null;
- String startNodeType = startVert.<String>property("aai-node-type").orElse(null);
- String targetNodeType = targetVert.<String>property("aai-node-type").orElse(null);
- String fwdRuleKey = startNodeType + "|" + targetNodeType;
- int fwdRuleCount = 0;
- String fwdRule = "";
- String fwdLabel = "";
- String revRuleKey = targetNodeType + "|" + startNodeType;
- int revRuleCount = 0;
- String revRule = "";
- String revLabel = "";
- String edRule = "";
- String edLabel = "";
-
- Boolean checkType = false;
- if( (edgeType != null) && edgeType != "" ){
- checkType = true;
- }
-
- // As of 16-07, it is possible to have more than one kind of edge defined between a given
- // pair of nodeTypes. So we need to check to see if there is only one possibility, or if
- // we need to look at the edgeType to determine which to use.
- // NOTE -- we're only supporting having 2 edges between a given pair of nodeTypes and
- // one and only one of them would have to be a parent-child edge.
-
- if( DbEdgeRules.EdgeRules.containsKey(fwdRuleKey) ){
- Collection <String> edRuleColl = DbEdgeRules.EdgeRules.get(fwdRuleKey);
- Iterator <String> ruleItr = edRuleColl.iterator();
- while( ruleItr.hasNext() ){
- String tmpRule = ruleItr.next();
- String [] rules = tmpRule.split(",");
- String tmpLabel = rules[0];
- String tmpParChild = rules[3];
- if( !checkType
- || (checkType && tmpParChild.equals("true") && edgeType.equals("parentChild"))
- || (checkType && tmpParChild.equals("false") && edgeType.equals("cousin")) ){
- // Either they didn't want us to check the edgeType or it is a match
- fwdRuleCount++;
- if( fwdRuleCount > 1 ){
- // We found more than one with the given info
- throw new AAIException("AAI_6120", "Multiple EdgeRules found for nodeTypes: [" + startNodeType + "], ["
- + targetNodeType + "], edgeType = [" + edgeType + "].");
- }
- else {
- fwdRule = tmpRule;
- fwdLabel = tmpLabel;
- }
- }
- }
- }
-
- // Try it the other way also (unless this is the case of a nodeType recursively pointing to itself
- // Ie. the edge rule: "model-element|model-element"
- if( !revRuleKey.equals(fwdRuleKey) && DbEdgeRules.EdgeRules.containsKey(revRuleKey) ){
- Collection <String> edRuleColl = DbEdgeRules.EdgeRules.get(revRuleKey);
- Iterator <String> ruleItr = edRuleColl.iterator();
- while( ruleItr.hasNext() ){
- String tmpRule = ruleItr.next();
- String [] rules = tmpRule.split(",");
- String tmpLabel = rules[0];
- String tmpParChild = rules[3];
- if( !checkType
- || (checkType && tmpParChild.equals("true") && edgeType.equals("parentChild"))
- || (checkType && tmpParChild.equals("false") && edgeType.equals("cousin")) ){
- // Either they didn't want us to check the edgeType or it is a match
- revRuleCount++;
- if( revRuleCount > 1 ){
- // We found more than one with the given info
- throw new AAIException("AAI_6120", "Multiple EdgeRules found for nodeTypes: [" + targetNodeType + "], ["
- + startNodeType + "], edgeType = [" + edgeType + "].");
- }
- else {
- revRule = tmpRule;
- revLabel = tmpLabel;
- }
- }
- }
- }
-
- if( (fwdRuleCount == 1) && (revRuleCount == 0) ){
- // We can use the node info in the order they were given
- fromVtx = startVert;
- toVtx = targetVert;
- edRule = fwdRule;
- edLabel = fwdLabel;
- }
- else if( (fwdRuleCount == 0) && (revRuleCount == 1) ){
- // We need to switch the vertex order so the edge-direction is correct
- toVtx = startVert;
- fromVtx = targetVert;
- edRule = revRule;
- edLabel = revLabel;
- }
- else if( (fwdRuleCount == 0) && (revRuleCount == 0) ){
- // No edge rule found for this
- throw new AAIException("AAI_6120", "No EdgeRule found for passed nodeTypes: " + startNodeType + ", " + targetNodeType
- + "], checkLabelType = [" + edgeType + "].");
- }
- else if( (fwdRuleCount > 0) && (revRuleCount > 0) ){
- // We found more than one with the given info
- throw new AAIException("AAI_6120", "Multiple EdgeRules (fwd and rev) found for nodeTypes: [" + startNodeType + "], ["
- + targetNodeType + "], checkLabelType = [" + edgeType + "].");
- }
-
- // If we got to this point, we now have a single edge label and we know to and from Vtx.
-
- HashMap <String,Object> edgeParamHash = getEdgeTagPropPutHash4Rule(transId, fromAppId, edRule);
- // We do "source-of-truth" for all edges
- edgeParamHash.put("source-of-truth", fromAppId );
-
- TitanEdge returnEdge = saveAaiEdgeToDb(transId, fromAppId, graph, edLabel, fromVtx, toVtx, edgeParamHash, apiVersion);
-
- return returnEdge;
-
- }
-
- /**
- * Persist aai edge.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param startVert the start vert
- * @param targetVert the target vert
- * @return the titan edge
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanEdge persistAaiEdge( String transId, String fromAppId, TitanTransaction graph,
- TitanVertex startVert, TitanVertex targetVert ) throws AAIException{
- return persistAaiEdge( transId, fromAppId, graph,
- startVert, targetVert, null);
- }
- // End persistAaiEdge()
-
-
- /**
- * Persist aai edge.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param edgeLabel the edge label
- * @param startVert the start vert
- * @param targetVert the target vert
- * @param propHash the prop hash
- * @param addIfNotFound the add if not found
- * @return the titan edge
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanEdge persistAaiEdge( String transId, String fromAppId, TitanTransaction graph,
- String edgeLabel, TitanVertex startVert, TitanVertex targetVert,
- HashMap <String,Object> propHash, Boolean addIfNotFound ) throws AAIException{
-
- /*----- This method is depricated ------
- * We will ignore the parameters: edgeLabel, propHash and addIfNotFound
- * We will use the remaining params to call the newer version of this method
- */
- TitanEdge returnEdge = persistAaiEdge(transId, fromAppId, graph, startVert, targetVert, null);
-
- return returnEdge;
-
- }// End depricated version of persistAaiEdge()
-
-
- /**
- * Persist aai edge with dep params.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param startVert the start vert
- * @param targetNodeType the target node type
- * @param targetNodeParamHash the target node param hash
- * @param apiVersion the api version
- * @return TitanEdge
- * @throws AAIException the AAI exception
- */
- public static TitanEdge persistAaiEdgeWithDepParams( String transId, String fromAppId, TitanTransaction graph,
- TitanVertex startVert, String targetNodeType, HashMap <String,Object> targetNodeParamHash, String apiVersion) throws AAIException{
-
- TitanVertex targetVert = getUniqueNodeWithDepParams( transId, fromAppId, graph, targetNodeType, targetNodeParamHash, apiVersion );
- TitanEdge returnEdge = persistAaiEdge(transId, fromAppId, graph, startVert, targetVert, apiVersion);
-
- return returnEdge;
-
- }// End persistAaiEdgeWithDepParams()
-
- // Version that lets you pass in an edgeType ("parentChild" or "cousin" since it sometimes cannot be determined
- /**
- * Persist aai edge with dep params.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param startVert the start vert
- * @param targetNodeType the target node type
- * @param targetNodeParamHash the target node param hash
- * @param apiVersion the api version
- * @param edgeType the edge type
- * @return the titan edge
- * @throws AAIException the AAI exception
- */
- // from the two nodeTypes anymore (16-07)
- public static TitanEdge persistAaiEdgeWithDepParams( String transId, String fromAppId, TitanTransaction graph,
- TitanVertex startVert, String targetNodeType, HashMap <String,Object> targetNodeParamHash,
- String apiVersion, String edgeType) throws AAIException{
- TitanVertex targetVert = getUniqueNodeWithDepParams( transId, fromAppId, graph, targetNodeType, targetNodeParamHash, apiVersion );
- TitanEdge returnEdge = persistAaiEdge(transId, fromAppId, graph, startVert, targetVert, apiVersion, edgeType);
-
- return returnEdge;
-
- }// End persistAaiEdgeWithDepParams()
-
- /**
- * Persist aai edge with dep params.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param startVert the start vert
- * @param targetNodeType the target node type
- * @param targetNodeParamHash the target node param hash
- * @return the titan edge
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static TitanEdge persistAaiEdgeWithDepParams( String transId, String fromAppId, TitanTransaction graph,
- TitanVertex startVert, String targetNodeType, HashMap <String,Object> targetNodeParamHash) throws AAIException{
- return persistAaiEdgeWithDepParams( transId, fromAppId, graph,
- startVert, targetNodeType, targetNodeParamHash, null);
- }
-
- /**
- * Gets the node key prop hash.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param vtx the vtx
- * @return nodeKeyPropHash
- * @throws AAIException the AAI exception
- */
- public static HashMap <String, Object> getNodeKeyPropHash( String transId, String fromAppId, TitanTransaction graph, TitanVertex vtx) throws AAIException{
-
- if( vtx == null ){
- throw new AAIException("AAI_6109", "null node object passed to getNodeKeyPropHash().");
- }
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- String nType = vtx.<String>property("aai-node-type").orElse(null);
- if( ! dbMaps.NodeKeyProps.containsKey(nType) ){
- // Problem if no key Properties defined for this nodeType
- String defVer = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- throw new AAIException("AAI_6105", "No node-key-properties defined in dbMaps for nodeType = " + nType + " (ver=" + defVer + ")");
- }
-
- HashMap <String,Object>nodeKeyPropsHash = new HashMap<String,Object>();
- Collection <String> keyProps = dbMaps.NodeKeyProps.get(nType);
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- String propName = keyPropI.next();
- Object value = (Object) vtx.<Object>property(propName).orElse(null);
- nodeKeyPropsHash.put(propName, value);
- }
-
- return nodeKeyPropsHash;
-
- }// End of getNodeKeyPropHash()
-
- /**
- * Gets the node name prop hash.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param vtx the vtx
- * @param apiVersion the api version
- * @return nodeKeyPropHash
- * @throws AAIException the AAI exception
- */
- public static HashMap <String, Object> getNodeNamePropHash( String transId, String fromAppId, TitanTransaction graph, TitanVertex vtx, String apiVersion) throws AAIException{
-
- if( vtx == null ){
- throw new AAIException("AAI_6109", "null node object passed to getNodeNamePropHash()." );
- }
-
- String nType = vtx.<String>property("aai-node-type").orElse(null);
- HashMap <String,Object>nodeNamePropsHash = new HashMap<String,Object>();
- Collection <String> keyProps = DbMeth.getNodeNameProps(transId, fromAppId, nType, apiVersion);
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- String propName = keyPropI.next();
- Object value = (Object) vtx.<Object>property(propName).orElse(null);
- nodeNamePropsHash.put(propName, value);
- }
-
- return nodeNamePropsHash;
-
- }// End of getNodeNamePropHash()
-
-
- /**
- * Removes the aai edge.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param tEdge the t edge
- * @return void
- */
- public static void removeAaiEdge( String transId, String fromAppId, TitanTransaction graph, TitanEdge tEdge){
- // Before removing the edge, touch the vertices on each side so their resource-versions will get updated
- TitanVertex tmpVIn = tEdge.inVertex();
- touchVertex( transId, fromAppId, tmpVIn );
-
- TitanVertex tmpVOut = tEdge.outVertex();
- touchVertex( transId, fromAppId, tmpVOut );
-
- // Remove the passed in edge.
- tEdge.remove();
-
- }// end of removeAaiEdge()
-
-
- /**
- * Removes the aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param thisVtx the this vtx
- * @param scopeParam the scope param
- * @param apiVersion the api version
- * @param resourceVersion the resource version
- * @throws AAIException the AAI exception
- */
- public static void removeAaiNode( String transId, String fromAppId, TitanTransaction graph, TitanVertex thisVtx, String scopeParam,
- String apiVersion, String resourceVersion ) throws AAIException{
- // Note: the resource Version Override flag is only set to true when called by the Model Delete code which
- // has no way to know the resource-versions of nodes at lower-levels of it's model topology.
- Boolean resVersionOverrideFlag = false;
- removeAaiNode( transId, fromAppId, graph, thisVtx, scopeParam, apiVersion, resourceVersion, resVersionOverrideFlag );
- }
-
-
- /**
- * <pre>
- * Possible values for deleteScope can be:
- * USE_DEFAULT - Get the scope from ref data for this node
- * THIS_NODE_ONLY (but should fail if it there are nodes that depend on it for uniqueness)
- * CASCADE_TO_CHILDREN - will look for OUT-Edges that have parentOf/hasDelTarget = true and follow those down
- * ERROR_4_IN_EDGES_OR_CASCADE - combo of error-if-any-IN-edges + CascadeToChildren
- * ERROR_IF_ANY_IN_EDGES - Fail if this node has any existing IN edges
- * ERROR_IF_ANY_EDGES - Fail if this node has any existing edges at all!
- * </pre>.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param thisVtx the this vtx
- * @param scopeParam the scope param
- * @param apiVersion the api version
- * @param resourceVersion the resource version
- * @param resVerOverride the res ver override
- * @return void
- * @throws AAIException the AAI exception
- */
- public static void removeAaiNode( String transId, String fromAppId, TitanTransaction graph, TitanVertex thisVtx, String scopeParam,
- String apiVersion, String resourceVersion, Boolean resVerOverride ) throws AAIException{
- String nodeType2Del = thisVtx.<String>property("aai-node-type").orElse(null);
- String deleteScope = scopeParam;
- if( scopeParam.equals("USE_DEFAULT") ){
- deleteScope = getDefaultDeleteScope(transId, fromAppId, nodeType2Del, apiVersion);
- }
-
- if( !resVerOverride && needToDoResourceVerCheck(apiVersion, false) ){
- // Need to check that they knew what they were deleting
- String existingResVer = thisVtx.<String>property("resource-version").orElse(null);
- if( resourceVersion == null || resourceVersion.equals("") ){
- throw new AAIException("AAI_6130", "Resource-version not passed for delete of = " + nodeType2Del);
- }
- else if( (existingResVer != null) && !resourceVersion.equals(existingResVer) ){
- throw new AAIException("AAI_6131", "Resource-version MISMATCH for delete of = " + nodeType2Del);
- }
- }
-
- if( !deleteScope.equals("THIS_NODE_ONLY")
- && !deleteScope.equals("CASCADE_TO_CHILDREN")
- && !deleteScope.equals("ERROR_4_IN_EDGES_OR_CASCADE")
- && !deleteScope.equals("ERROR_IF_ANY_EDGES")
- && !deleteScope.equals("ERROR_IF_ANY_IN_EDGES") ){
- throw new AAIException("AAI_6120", "Unrecognized value in deleteScope: [" + deleteScope + "].");
- }
-
- if( deleteScope.equals("ERROR_IF_ANY_EDGES") ){
- if ( thisVtx.edges(Direction.BOTH).hasNext() ) {
- throw new AAIException("AAI_6110", "Node cannot be deleted because it still has Edges and the ERROR_IF_ANY_EDGES scope was used.");
- }
- }
- else if( deleteScope.equals("ERROR_IF_ANY_IN_EDGES") || deleteScope.equals("ERROR_4_IN_EDGES_OR_CASCADE") ){
- Iterator <Edge> eI = thisVtx.edges(Direction.IN);
- boolean onlyHasParent = false;
- Edge temp = null;
- if( eI != null && eI.hasNext() ){
- temp = eI.next();
- Boolean isParent = temp.<Boolean>property("isParent").orElse(null);
- if (isParent != null && isParent && !eI.hasNext()) {
- onlyHasParent = true;
- }
-
- if (!onlyHasParent) {
- throw new AAIException("AAI_6110", "Node cannot be deleted because it still has Edges and the " + deleteScope + " scope was used.");
- }
- }
- }
- else if( deleteScope.equals("THIS_NODE_ONLY")){
- // Make sure nobody depends on this node.
- Iterator<Edge> eI = thisVtx.edges(Direction.BOTH);
- while( eI.hasNext() ){
- TitanEdge ed = (TitanEdge) eI.next();
- TitanVertex otherVtx = (TitanVertex) ed.otherVertex(thisVtx);
- String nodeTypeA = otherVtx.<String>property("aai-node-type").orElse(null);
- if( nodeTypeACanDependOnB(transId, fromAppId, nodeTypeA, nodeType2Del, apiVersion)){
- // We're only supposed to delete this node - but another node is dependant on it,
- // so we shouldn't delete this one.
- throw new AAIException("AAI_6110", "Node cannot be deleted using scope = " + deleteScope +
- " another node (type = " + nodeTypeA + ") depends on it for uniqueness.");
- }
- }
- }
-
- // We've passed our checks - so do some deleting of edges and maybe pass
- // the delete request down to children or delete-targets.
-
- // First we deal with the "IN"-Edges which can't have children/delete-targets which
- // by definition (of "IN") on the other end
- Iterator <Edge> eI_In = thisVtx.edges(Direction.IN);
- while( eI_In.hasNext() ){
- TitanEdge ed = (TitanEdge) eI_In.next();
-
- //- "touch" vertex on other side of this edge so it gets a fresh resource-version
- TitanVertex tmpVOther = ed.otherVertex(thisVtx);
- touchVertex( transId, fromAppId, tmpVOther );
-
- ed.remove();
- }
-
- // Now look at the "OUT"-edges which might include children or delete-targets
- String cascadeMsg = "This nt = " + nodeType2Del + ", Cascading del to: ";
- Iterator <Edge> eI_Out = thisVtx.edges(Direction.OUT);
- if( !eI_Out.hasNext() ){
- cascadeMsg = cascadeMsg + "[no children for this node]";
- }
- while( eI_Out.hasNext() ){
- TitanEdge ed = (TitanEdge) eI_Out.next();
-
- // "touch" vertex on other side of this edge so it gets a fresh resource-version
- TitanVertex tmpVOther = ed.otherVertex(thisVtx);
- touchVertex( transId, fromAppId, tmpVOther );
-
- Boolean otherVtxAChild = ed.<Boolean>property("isParent").orElse(null);
- if( otherVtxAChild == null ){
- otherVtxAChild = false;
- }
-
- Boolean otherVtxADeleteTarget = ed.<Boolean>property("hasDelTarget").orElse(null);
- if( otherVtxADeleteTarget == null ){
- otherVtxADeleteTarget = false;
- }
-
- if( (otherVtxAChild || otherVtxADeleteTarget) &&
- (deleteScope.equals("CASCADE_TO_CHILDREN") || deleteScope.equals("ERROR_4_IN_EDGES_OR_CASCADE")) ){
- // Delete the edge to the child and Pass the delete down to it.
- ed.remove();
- TitanVertex otherVtx = (TitanVertex) ed.otherVertex(thisVtx);
- String vid = otherVtx.id().toString();
- String nty = otherVtx.<String>property("aai-node-type").orElse(null);
- String resVers = otherVtx.<String>property("resource-version").orElse(null);
- cascadeMsg = cascadeMsg + "[" + nty + ":" + vid + "]";
- removeAaiNode(transId, fromAppId, graph, otherVtx, "CASCADE_TO_CHILDREN", apiVersion, resVers);
- }
- else {
- // The other node is not a child or deleteTarget. Delete the edge to it if it is not
- // dependent (Should never be dependent since it's not a child/delTarget... but
- // someone could create a node that was dependent for Uniqueness without
- // being a child/target.
-
- // DEBUG -- eventually add the check for dependancy that isn't on a parent-type or delTarget-type edge
- ed.remove();
- }
- }
-
- LOGGER.info(cascadeMsg);
-
- Iterator<Edge> eI = thisVtx.edges(Direction.BOTH);
- if( ! eI.hasNext() ){
- // By this point, either there were no edges to deal with, or we have dealt with them.
- thisVtx.remove();
- }
- else {
- // Something went wrong and we couldn't delete all the edges for this guy.
- throw new AAIException("AAI_6110", "Node could be deleted because it unexpectedly still has Edges.\n");
- }
- }
-
-
- /**
- * Removes the aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param thisVtx the this vtx
- * @param scopeParam the scope param
- * @return void
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static void removeAaiNode( String transId, String fromAppId, TitanTransaction graph, TitanVertex thisVtx, String scopeParam) throws AAIException{
- removeAaiNode(transId, fromAppId, graph, thisVtx, scopeParam, null, null);
- }
-
- /**
- * Removes the aai node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param thisVtx the this vtx
- * @param scopeParam the scope param
- * @param apiVersion the api version
- * @throws AAIException the AAI exception
- */
- @Deprecated
- public static void removeAaiNode( String transId, String fromAppId, TitanTransaction graph, TitanVertex thisVtx, String scopeParam,
- String apiVersion ) throws AAIException{
- removeAaiNode(transId, fromAppId, graph, thisVtx, scopeParam, apiVersion, null);
- }
- // end of removeAaiNode()
-
-
- /**
- * Delete all graph data.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @return void
- */
- public static void deleteAllGraphData( String transId, String fromAppId, TitanGraph graph ){
- /** ======================================================================
- * WARNING -- this removes ALL the data that is currently in the graph.
- * ======================================================================
- **/
- LOGGER.warn("deleteAllGraphData called! Run for the hills!");
- Iterator<Edge> edges = graph.edges(Direction.BOTH);
- graph.tx().commit();
- Edge edge = null;
- while (edges.hasNext()) {
- edge = edges.next();
- edges.remove();
- }
- graph.tx().commit();
- Iterator<Vertex> vertices = graph.vertices();
- graph.tx().commit();
- Vertex vertex = null;
- while (vertices.hasNext()) {
- vertex = vertices.next();
- vertex.remove();
- }
- graph.tx().commit();
- }
-
-
- /**
- * Show all edges for node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param tVert the t vert
- * @return the array list
- */
- public static ArrayList <String> showAllEdgesForNode( String transId, String fromAppId, TitanVertex tVert ){
-
- ArrayList <String> retArr = new ArrayList <String> ();
- Iterator <Edge> eI = tVert.edges(Direction.IN);
- if( ! eI.hasNext() ){
- retArr.add("No IN edges were found for this vertex. ");
- }
- while( eI.hasNext() ){
- TitanEdge ed = (TitanEdge) eI.next();
- String lab = ed.label();
- TitanVertex vtx = (TitanVertex) ed.otherVertex(tVert);
- if( vtx == null ){
- retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< ");
- }
- else {
- String nType = vtx.<String>property("aai-node-type").orElse(null);
- String vid = vtx.id().toString();
- retArr.add("Found an IN edge (" + lab + ") to this vertex from a [" + nType + "] node with VtxId = " + vid );
- //DEBUG ---
- //showPropertiesForEdge( transId, fromAppId, ed );
- }
- }
-
- eI = tVert.edges(Direction.OUT);
- if( ! eI.hasNext() ){
- retArr.add("No OUT edges were found for this vertex. ");
- }
- while( eI.hasNext() ){
- TitanEdge ed = (TitanEdge) eI.next();
- String lab = ed.label();
- TitanVertex vtx = (TitanVertex) ed.otherVertex(tVert);
- if( vtx == null ){
- retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< ");
- }
- else {
- String nType = vtx.<String>property("aai-node-type").orElse(null);
- String vid = vtx.id().toString();
- retArr.add("Found an OUT edge (" + lab + ") from this vertex to a [" + nType + "] node with VtxId = " + vid );
- //DEBUG ---
- //showPropertiesForEdge( transId, fromAppId, ed );
- }
- }
- return retArr;
- }
-
-
- /**
- * Show properties for node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param tVert the t vert
- * @return the array list
- */
- public static ArrayList <String> showPropertiesForNode( String transId, String fromAppId, TitanVertex tVert ){
-
- ArrayList <String> retArr = new ArrayList <String> ();
- if( tVert == null ){
- retArr.add("null Node object passed to showPropertiesForNode()\n");
- }
- else {
- String nodeType = "";
- //String datType = "";
- Object ob = tVert.<Object>property("aai-node-type").orElse(null);
- if( ob == null ){
- nodeType = "null";
- }
- else{
- nodeType = ob.toString();
- //datType = ob.getClass().getSimpleName();
- }
-
- retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]");
- retArr.add(" Property Detail: ");
- Iterator<VertexProperty<Object>> pI = tVert.properties();
- while( pI.hasNext() ){
- VertexProperty<Object> tp = pI.next();
- Object val = tp.value();
- //retArr.add("Prop: [" + tp.getPropertyKey() + "], val = [" + val + "], dataType = " + val.getClass() );
- retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] ");
- }
- }
- return retArr;
- }
-
-
- /**
- * Gets the node name props.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the node type
- * @param apiVersion the api version
- * @return HashMap of keyProperties
- * @throws AAIException the AAI exception
- */
- public static Collection <String> getNodeNameProps( String transId, String fromAppId, String nodeType, String apiVersion ) throws AAIException{
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- Collection <String> nameProps = new ArrayList <String>();
- if( dbMaps.NodeNameProps.containsKey(nodeType) ){
- nameProps = dbMaps.NodeNameProps.get(nodeType);
- }
- else if( DbEdgeRules.NodeTypeCategory.containsKey(nodeType) ){
- // The passed-in nodeType was really a nodeCategory, theoretically, all the guys in the same
- // category should have the same name property -- so if they just give us the category, we will
- // just give the name info from the first nodeType we encounter of that category.
- Collection <String> nTypeCatCol = DbEdgeRules.NodeTypeCategory.get(nodeType);
- Iterator <String> catItr = nTypeCatCol.iterator();
- String catInfo = "";
- if( catItr.hasNext() ){
- // For now, we only look for one.
- catInfo = catItr.next();
- }
- else {
- throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + nodeType);
- }
-
- String [] flds = catInfo.split(",");
- if( flds.length != 4 ){
- throw new AAIException("AAI_6121", "Bad EdgeRule.NodeTypeCategory data (itemCount=" + flds.length + ") for nodeType = [" + nodeType + "].");
- }
-
- String nodeTypesString = flds[0];
- String [] nodeTypeNames = nodeTypesString.split("\\|");
- if( nodeTypeNames != null && nodeTypeNames.length > 0 ){
- // We'll just use the first one
- String nt = nodeTypeNames[0];
- nameProps = dbMaps.NodeNameProps.get(nt);
- }
- }
-
-
- // Note - it's ok if there was no defined name property for this nodeType.
-
- return nameProps;
-
- }// end of getNodeKeyPropNames
-
-
- /**
- * Gets the edge tag prop put hash 4 rule.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param edRule the ed rule
- * @return the edge tag prop put hash 4 rule
- * @throws AAIException the AAI exception
- */
- public static HashMap <String,Object> getEdgeTagPropPutHash4Rule( String transId, String fromAppId, String edRule )
- throws AAIException{
- // For a given edgeRule - already pulled out of DbEdgeRules.EdgeRules -- parse out the "tags" that
- // need to be set for this kind of edge.
- // These are the Boolean properties like, "isParent", "usesResource" etc.
- HashMap <String,Object> retEdgePropPutMap = new HashMap <String,Object>();
-
- if( (edRule == null) || edRule.equals("") ){
- // No edge rule found for this
- throw new AAIException("AAI_6120", "blank edRule passed to getEdgeTagPropPutHash4Rule()");
- }
-
- int tagCount = DbEdgeRules.EdgeInfoMap.size();
- String [] rules = edRule.split(",");
- if( rules.length != tagCount ){
- throw new AAIException("AAI_6121", "Bad EdgeRule data (itemCount =" + rules.length + ") for rule = [" + edRule + "].");
- }
-
- // In DbEdgeRules.EdgeRules -- What we have as "edRule" is a comma-delimited set of strings.
- // The first item is the edgeLabel.
- // The second in the list is always "direction" which is always OUT for the way we've implemented it.
- // Items starting at "firstTagIndex" and up are all assumed to be booleans that map according to
- // tags as defined in EdgeInfoMap.
- // Note - if they are tagged as 'reverse', that means they get the tag name with "-REV" on it
- for( int i = DbEdgeRules.firstTagIndex; i < tagCount; i++ ){
- String booleanStr = rules[i];
- Integer mapKey = new Integer(i);
- String propName = DbEdgeRules.EdgeInfoMap.get(mapKey);
- String revPropName = propName + "-REV";
-
- if( booleanStr.equals("true") ){
- retEdgePropPutMap.put(propName, true);
- retEdgePropPutMap.put(revPropName,false);
- }
- else if( booleanStr.equals("false") ){
- retEdgePropPutMap.put(propName, false);
- retEdgePropPutMap.put(revPropName,false);
- }
- else if( booleanStr.equals("reverse") ){
- retEdgePropPutMap.put(propName, false);
- retEdgePropPutMap.put(revPropName,true);
- }
- else {
- throw new AAIException("AAI_6121", "Bad EdgeRule data for rule = [" + edRule + "], val = [" + booleanStr + "].");
- }
-
- }
-
- return retEdgePropPutMap;
-
- } // End of getEdgeTagPropPutHash()
-
-
-
- /**
- * Gets the edge tag prop put hash.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param edgeRuleKey the edge rule key
- * @return the edge tag prop put hash
- * @throws AAIException the AAI exception
- */
- public static Map<String, EdgeRule> getEdgeTagPropPutHash( String transId, String fromAppId, String edgeRuleKey )
- throws AAIException{
- // For a given edgeRuleKey (nodeTypeA|nodeTypeB), look up the rule that goes with it in
- // DbEdgeRules.EdgeRules and parse out the "tags" that need to be set on each edge.
- // These are the Boolean properties like, "isParent", "usesResource" etc.
- // Note - this code is also used by the updateEdgeTags.java code
-
- String[] edgeRuleKeys = edgeRuleKey.split("\\|");
-
- if (edgeRuleKeys.length < 2 || ! EdgeRules.getInstance().hasEdgeRule(edgeRuleKeys[0], edgeRuleKeys[1])) {
- throw new AAIException("AAI_6120", "Could not find an DbEdgeRule entry for passed edgeRuleKey (nodeTypeA|nodeTypeB): " + edgeRuleKey + ".");
- }
-
- Map<String, EdgeRule> edgeRules = EdgeRules.getInstance().getEdgeRules(edgeRuleKeys[0], edgeRuleKeys[1]);
-
- return edgeRules;
-
- } // End of getEdgeTagPropPutHash()
-
-
- /**
- * This property was put by newer version of code.
- *
- * @param apiVersionStr the api version str
- * @param nodeType the node type
- * @param propName the prop name
- * @return true, if successful
- * @throws AAIException the AAI exception
- */
- private static boolean thisPropertyWasPutByNewerVersionOfCode( String apiVersionStr,
- String nodeType, String propName) throws AAIException{
- // We want to return True if the nodeType + property-name combo was introduced AFTER the apiVersion passed.
-
- int apiVerInt = 0;
- int propIntroVerInt = 0;
-
- if( apiVersionStr == null || apiVersionStr.equals("") ){
- apiVersionStr = org.openecomp.aai.util.AAIApiVersion.get();
- }
- apiVerInt = getVerNumFromVerString(apiVersionStr);
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
- String propIntroKey = nodeType + "|" + propName;
- if( propName.equals("prov-status") ){
- // This is a special case -- The dbMaps from v2 has it in there, but it was introduced half way through. So
- // it needs to be catogorized as v3.
- propIntroVerInt = 3;
- }
- else if( ! dbMaps.PropertyVersionInfoMap.containsKey(propIntroKey) ){
- String detail = propIntroKey + " [" + propIntroKey + "] not found in dbMaps.PropertyVersionInfoMap.";
- throw new AAIException("AAI_6121", detail);
- }
- else {
- String propIntroVerString = dbMaps.PropertyVersionInfoMap.get(propIntroKey);
- propIntroVerInt = getVerNumFromVerString( propIntroVerString );
- }
-
- if( propIntroVerInt > apiVerInt ){
- return true;
- }
- else {
- return false;
- }
-
- } // End of thisPropertyWasPutByNewerVersionOfCode()
-
-
- /**
- * Touch vertex.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param v the v
- * @return void
- */
- public static void touchVertex( String transId, String fromAppId, TitanVertex v ){
- // We want to "touch" the vertex -- Ie. update it's last-mod-date, last-mod- resource-version to the current date/time
- if( v != null ){
- long unixTimeNow = System.currentTimeMillis() / 1000L;
- String timeNowInSec = "" + unixTimeNow;
- v.property( "aai-last-mod-ts", timeNowInSec );
- v.property( "resource-version", timeNowInSec );
- v.property( "last-mod-source-of-truth", fromAppId );
- }
- } // End of touchVertex()
-
-
- /**
- * Check prop cardinality.
- *
- * @param propName the prop name
- * @param cardinalityType the cardinality type
- * @return boolean
- * @throws AAIException the AAI exception
- */
- public static boolean checkPropCardinality( String propName, String cardinalityType ) throws AAIException {
-
- // Return true if the named property is tagged in our dbMaps PropetyDataTypeMap as
- // having the passed in cardinality type.
- // NOTE: supported cardinality types in dbMaps = "Set" or "List"
- // In Titan (and ex5.json), those go in as "SET" and "LIST"
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- if( dbMaps.PropertyDataTypeMap.containsKey(propName) ){
- String propDataType = dbMaps.PropertyDataTypeMap.get(propName);
- if( propDataType != null && propDataType.startsWith(cardinalityType) ){
- return true;
- }
- }
- return false;
-
- } // End of checkPropCardinality()
-
- /**
- * Convert type if needed.
- *
- * @param propName the prop name
- * @param val the val
- * @return convertedValue (if it was a String but needed to be a Boolean)
- * @throws AAIException the AAI exception
- */
- public static Object convertTypeIfNeeded( String propName, Object val )
- throws AAIException {
- // Make sure the dataType of the passed-in Object matches what the DB expects
-
- // NOTE: since this is a fix very late in our dev cycle, we'll just fix the scenarios that
- // we're having trouble with which is Strings getting into the db which should be going in as
- // Booleans or Integers.
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- if( dbMaps.PropertyDataTypeMap.containsKey(propName) ){
- String dbExpectedDataType = dbMaps.PropertyDataTypeMap.get(propName);
- if( dbExpectedDataType != null
- && dbExpectedDataType.equals("Boolean")
- && val != null
- && !(val instanceof Boolean) ){
- String valStr = val.toString().trim();
- if( valStr.equals("true") || valStr.equals("True") || valStr.equals("TRUE") ){
- return Boolean.valueOf("true");
- }
- else if( valStr.equals("false") || valStr.equals("False") || valStr.equals("FALSE") ){
- return Boolean.valueOf("false");
- }
- else {
- String emsg = "Error trying to convert value: [" + valStr + "] to a Boolean for property + " + propName + "\n";
- throw new AAIException("AAI_6120", emsg);
- }
- }
- else if( dbExpectedDataType != null
- && dbExpectedDataType.equals("Integer")
- && val != null
- && !(val.toString().trim().equals(""))
- && !(val instanceof Integer) ){
- String valStr = val.toString().trim();
- Integer newInt;
- try {
- newInt = Integer.valueOf(valStr);
- return newInt;
- }
- catch( Exception e ){
- String emsg = "Error trying to convert value: [" + valStr + "] to an Integer for property + " + propName + "\n";
- throw new AAIException("AAI_6120", emsg);
- }
- }
- }
-
- // If it didn't need to be converted, just return it.
- return val;
-
- } // End of convertTypeIfNeeded()
-
-
-
- /**
- * This vertex not reachable.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param v the v
- * @param version the version
- * @return boolean
- */
- public static boolean thisVertexNotReachable( String transId, String fromAppId, TitanTransaction graph, TitanVertex v, String version){
- if( v == null ){
- return true;
- }
- else {
- try {
- v.id().toString();
- }
- catch( Exception ex ){
- // Could not get this -- sometimes we're holding a vertex object that has gotten deleted, so
- // when we try to get stuff from it, we get an "Element Has Been Removed" error from Titan
- return true;
- }
- }
-
- return false;
-
- } // End of thisVertexNotReachable()
-
- /**
- * This vertex has bad edges.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param v the v
- * @param version the version
- * @return boolean
- */
- public static boolean thisVertexHasBadEdges( String transId, String fromAppId, TitanTransaction graph, TitanVertex v, String version){
-
- Iterator <Edge> eItor = v.edges(Direction.BOTH);
- while( eItor.hasNext() ){
- Edge e = null;
- e = eItor.next();
- if( e == null ){
- return true;
- }
- Vertex vIn = e.inVertex();
- if( (vIn == null) || (vIn.<String>property("aai-node-type").orElse(null) == null) ){
- // this is a bad edge because it points to a vertex that isn't there anymore
- return true;
- }
-
- Vertex vOut = e.outVertex();
- if( (vOut == null) || (vOut.<String>property("aai-node-type").orElse(null) == null) ){
- // this is a bad edge because it points to a vertex that isn't there anymore
- return true;
- }
- }
-
- // If we made it to here, the vertex's edges must be ok.
- return false;
-
- } // End of thisVertexHasBadEdges()
-
-
- /**
- * This vertex is A phantom.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param v the v
- * @param version the version
- * @return boolean
- * @throws AAIException the AAI exception
- */
- public static boolean thisVertexIsAPhantom( String transId, String fromAppId, TitanTransaction graph, TitanVertex v, String version )
- throws AAIException {
-
-
- // The kind of Phantom we're looking for is the kind that we sometimes get when we do a select without
- // using key properties. They can be in the database as a vertex, but the indexes that should point to
- // them are not working -- so they cannot be used by normal interfaces (like the REST API) which means
- // that if we return it, it can mess up a caller who tries to use it.
- if( v == null ){
- return true;
- }
- String thisVid = v.id().toString();
-
- DbMaps dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP));
-
- Object propOb = v.<Object>property("aai-node-type").orElse(null);
- if( propOb == null ){
- // This vertex does not have an aai-node-type ---> it is messed up
- return true;
- }
- String nType = propOb.toString();
- if( ! dbMaps.NodeKeyProps.containsKey(nType) ){
- // This node Type does not have keys defined
- // This could just be bad reference data, so we will not flag this guy, but we
- // can't really do our test...
- return false;
- }
-
- HashMap <String,Object> propHashWithKeys = new HashMap<String, Object>();
- Collection <String> keyProps = null;
- try {
- keyProps = getNodeKeyPropNames(transId, fromAppId, nType, version);
- }
- catch (AAIException ex) {
- // something wrong with getting this guy's key property names - we'll abandon this test...
- return false;
- }
-
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- String propName = keyPropI.next();
- String propVal = "";
- Object ob = v.<Object>property(propName).orElse(null);
- if( ob != null ){
- propVal = ob.toString();
- }
- propHashWithKeys.put(propName, propVal);
- }
- try {
- // Note - We can get more than one back since some nodes need a dep. node for uniqueness.
- // We don't care about that -- we just want to make sure we can get this vertex back when
- // we're searching with it's indexed fields.
- // NOTE - we're passing the skipGroomCheck to getNodes so we don't wind up in an infinite loop
- ArrayList <TitanVertex> vertList2 = getNodes( transId, fromAppId, graph, nType, propHashWithKeys, false, version, true );
- Iterator<TitanVertex> iter2 = vertList2.iterator();
- while( iter2.hasNext() ){
- TitanVertex tvx2 = iter2.next();
- String foundId = tvx2.id().toString();
- if( foundId.equals( thisVid ) ){
- // We could get back the vertex by looking it up using key properties... That's good.
- return false;
- }
- }
- }
- catch (Exception e2) {
- //String msg = " Error encountered for this vertex id: [" + thisVid +
- // "]. Caught this exception: " + e2.toString();
- // Something messed up - but that doesn't prove that this is a phantom.
- return false;
- }
-
- // If we dropped down to here, we have looked but could not pull the vertex out of the
- // db using it's key fields, so it gets flagged as a Phantom.
- return true;
-
- } // End of thisVertexIsAPhantom()
-
-
- /**
- * Gets the node by unique key.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param graph the graph
- * @param aaiUniquekey the aai uniquekey
- * @return the node by unique key
- */
- public TitanVertex getNodeByUniqueKey(String transId, String fromAppId, TitanTransaction graph, String aaiUniquekey) {
-
- TitanVertex vert = null;
-
- Iterator<?> vertI = graph.query().has("aai-unique-key", aaiUniquekey).vertices().iterator();
-
- if( vertI != null && vertI.hasNext()) {
- // We found a vertex that meets the input criteria.
- vert = (TitanVertex) vertI.next();
- }
-
- return vert;
- }
-
-
-
-}
-
diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResource.java b/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResource.java
deleted file mode 100644
index 2a2cef9d..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResource.java
+++ /dev/null
@@ -1,675 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.domain.model;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-import com.google.common.collect.Multimap;
-
-
-public class AAIResource {
- private AAIResource parent;
- private AAIResources children;
-
- private AAIResourceKeys aaiResourceKeys;
-
- private String namespace; // /Network/Vces/Vce/PortGroups/PortGroup/CvlanTags/CvlanTag -> "Network"
-
- private String resourceType; // node or container
- private String resourceClassName;
- private String simpleName; // Vce
- private String fullName; // /Network/Vces/Vce/PortGroups/PortGroup/CvlanTags/CvlanTag
- private String uri; // /network/vces/vce/{vnf-id}/port-groups/port-group/{interface-name}/cvlan-tags/cvlan-tag/{cvlan-tag}
- private String apiVersion;
- private String relationshipListClass;
- private String relationshipUtils;
-
- private Map<String, String> PropertyDataTypeMap;
- private Multimap<String, String> NodeMapIndexedProps;
- private Multimap<String, String> NodeAltKey1Props;
- private Multimap<String, String> NodeDependencies;
- private Multimap<String, String> NodeKeyProps;
- private Multimap<String, String> NodeReqProps;
- private Multimap<String, String> NodeNameProps;
- private Multimap<String, String> NodeUniqueProps;
-
- // if new dataTypes are added - make sure to update getAllFields() method below
- private ArrayList<String> stringFields;
- private ArrayList<String> stringListFields;
- private ArrayList<String> longFields;
- private ArrayList<String> intFields;
- private ArrayList<String> shortFields;
- private ArrayList<String> booleanFields;
-
- private ArrayList<String> requiredFields;
- private ArrayList<String> orderedFields;
- private AAIResource recurseToResource;
- private boolean allowDirectWrite;
- private boolean allowDirectRead;
- private ArrayList<String> autoGenUuidFields;
-
- /**
- * Gets the parent.
- *
- * @return the parent
- */
- public AAIResource getParent() {
- return parent;
- }
-
- /**
- * Sets the parent.
- *
- * @param parent the new parent
- */
- public void setParent(AAIResource parent) {
- this.parent = parent;
- }
-
- /**
- * Gets the children.
- *
- * @return the children
- */
- public AAIResources getChildren() {
- if (this.children == null) {
- this.children = new AAIResources();
- }
- return this.children;
- }
-
- /**
- * Gets the aai resource keys.
- *
- * @return the aai resource keys
- */
- public AAIResourceKeys getAaiResourceKeys() {
- if (aaiResourceKeys == null) {
- aaiResourceKeys = new AAIResourceKeys();
- }
- return aaiResourceKeys;
- }
-
- /**
- * Gets the namespace.
- *
- * @return the namespace
- */
- public String getNamespace() {
- return namespace;
- }
-
- /**
- * Sets the namespace.
- *
- * @param namespace the new namespace
- */
- public void setNamespace(String namespace) {
- this.namespace = namespace;
- }
-
- /**
- * Gets the resource type.
- *
- * @return the resource type
- */
- public String getResourceType() {
- return resourceType;
- }
-
- /**
- * Sets the resource type.
- *
- * @param resourceType the new resource type
- */
- public void setResourceType(String resourceType) {
- this.resourceType = resourceType;
- }
-
- /**
- * Gets the simple name.
- *
- * @return the simple name
- */
- public String getSimpleName() {
- return simpleName;
- }
-
- /**
- * Sets the simple name.
- *
- * @param simpleName the new simple name
- */
- public void setSimpleName(String simpleName) {
- this.simpleName = simpleName;
- }
-
- /**
- * Gets the full name.
- *
- * @return the full name
- */
- public String getFullName() {
- return fullName;
- }
-
- /**
- * Sets the full name.
- *
- * @param fullName the new full name
- */
- public void setFullName(String fullName) {
- this.fullName = fullName;
- }
-
- /**
- * Gets the uri.
- *
- * @return the uri
- */
- public String getUri() {
- return uri;
- }
-
- /**
- * Sets the uri.
- *
- * @param uri the new uri
- */
- public void setUri(String uri) {
- this.uri = uri;
- }
-
- /**
- * Gets the resource class name.
- *
- * @return the resource class name
- */
- public String getResourceClassName() {
- return resourceClassName;
- }
-
- /**
- * Sets the resource class name.
- *
- * @param resourceClassName the new resource class name
- */
- public void setResourceClassName(String resourceClassName) {
- this.resourceClassName = resourceClassName;
- }
-
- /**
- * Gets the property data type map.
- *
- * @return the property data type map
- */
- public Map<String, String> getPropertyDataTypeMap() {
- return PropertyDataTypeMap;
- }
-
- /**
- * Sets the property data type map.
- *
- * @param propertyDataTypeMap the property data type map
- */
- public void setPropertyDataTypeMap(Map<String, String> propertyDataTypeMap) {
- PropertyDataTypeMap = propertyDataTypeMap;
- }
-
- /**
- * Gets the node map indexed props.
- *
- * @return the node map indexed props
- */
- public Multimap<String, String> getNodeMapIndexedProps() {
- return NodeMapIndexedProps;
- }
-
- /**
- * Sets the node map indexed props.
- *
- * @param nodeMapIndexedProps the node map indexed props
- */
- public void setNodeMapIndexedProps(Multimap<String, String> nodeMapIndexedProps) {
- NodeMapIndexedProps = nodeMapIndexedProps;
- }
-
- /**
- * Gets the node key props.
- *
- * @return the node key props
- */
- public Multimap<String, String> getNodeKeyProps() {
- return NodeKeyProps;
- }
-
- /**
- * Sets the node key props.
- *
- * @param nodeKeyProps the node key props
- */
- public void setNodeKeyProps(Multimap<String, String> nodeKeyProps) {
- this.NodeKeyProps = nodeKeyProps;
- }
-
- /**
- * Gets the node name props.
- *
- * @return the node name props
- */
- public Multimap<String, String> getNodeNameProps() {
- return NodeNameProps;
- }
-
- /**
- * Sets the node name props.
- *
- * @param nodeNameProps the node name props
- */
- public void setNodeNameProps(Multimap<String, String> nodeNameProps) {
-
- NodeNameProps = nodeNameProps;
- }
-
- /**
- * Gets the node unique props.
- *
- * @return the node unique props
- */
- public Multimap<String, String> getNodeUniqueProps() {
- return NodeUniqueProps;
- }
-
- /**
- * Sets the node unique props.
- *
- * @param nodeUniqueProps the node unique props
- */
- public void setNodeUniqueProps(Multimap<String, String> nodeUniqueProps) {
- NodeUniqueProps = nodeUniqueProps;
- }
-
- /**
- * Gets the node req props.
- *
- * @return the node req props
- */
- public Multimap<String, String> getNodeReqProps() {
- return NodeReqProps;
- }
-
- /**
- * Sets the node req props.
- *
- * @param nodeReqProps the node req props
- */
- public void setNodeReqProps(Multimap<String, String> nodeReqProps) {
- NodeReqProps = nodeReqProps;
- }
-
- /**
- * Gets the api version.
- *
- * @return the api version
- */
- public String getApiVersion() {
- return apiVersion;
- }
-
- /**
- * Sets the api version.
- *
- * @param apiVersion the new api version
- */
- public void setApiVersion(String apiVersion) {
- this.apiVersion = apiVersion;
- }
-
- /**
- * Gets the relationship list class.
- *
- * @return the relationship list class
- */
- public String getRelationshipListClass() {
- return relationshipListClass;
- }
-
- /**
- * Sets the relationship list class.
- *
- * @param relationshipListClass the new relationship list class
- */
- public void setRelationshipListClass(String relationshipListClass) {
- this.relationshipListClass = relationshipListClass;
- }
-
- /**
- * Gets the relationship utils.
- *
- * @return the relationship utils
- */
- public String getRelationshipUtils() {
- return relationshipUtils;
- }
-
- /**
- * Sets the relationship utils.
- *
- * @param relationshipUtils the new relationship utils
- */
- public void setRelationshipUtils(String relationshipUtils) {
- this.relationshipUtils = relationshipUtils;
- }
-
- /**
- * Gets the string fields.
- *
- * @return the string fields
- */
- public ArrayList<String> getStringFields() {
- if (this.stringFields == null) {
- this.stringFields = new ArrayList<String>();
- }
- return this.stringFields;
- }
-
- /**
- * Sets the string fields.
- *
- * @param stringFields the new string fields
- */
- public void setStringFields(ArrayList<String> stringFields) {
- this.stringFields = stringFields;
- }
-
- /**
- * Gets the string list fields.
- *
- * @return the string list fields
- */
- public ArrayList<String> getStringListFields() {
- if (this.stringListFields == null) {
- this.stringListFields = new ArrayList<String>();
- }
- return this.stringListFields;
- }
-
- /**
- * Sets the string list fields.
- *
- * @param stringListFields the new string list fields
- */
- public void setStringListFields(ArrayList<String> stringListFields) {
- this.stringListFields = stringListFields;
- }
-
- /**
- * Gets the long fields.
- *
- * @return the long fields
- */
- public ArrayList<String> getLongFields() {
- if (this.longFields == null) {
- this.longFields = new ArrayList<String>();
- }
- return longFields;
- }
-
- /**
- * Sets the long fields.
- *
- * @param longFields the new long fields
- */
- public void setLongFields(ArrayList<String> longFields) {
- this.longFields = longFields;
- }
-
- /**
- * Gets the int fields.
- *
- * @return the int fields
- */
- public ArrayList<String> getIntFields() {
- if (this.intFields == null) {
- this.intFields = new ArrayList<String>();
- }
- return intFields;
- }
-
- /**
- * Sets the int fields.
- *
- * @param intFields the new int fields
- */
- public void setIntFields(ArrayList<String> intFields) {
- this.intFields = intFields;
- }
-
- /**
- * Gets the short fields.
- *
- * @return the short fields
- */
- public ArrayList<String> getShortFields() {
- if (this.shortFields == null) {
- this.shortFields = new ArrayList<String>();
- }
- return shortFields;
- }
-
- /**
- * Sets the short fields.
- *
- * @param shortFields the new short fields
- */
- public void setShortFields(ArrayList<String> shortFields) {
- this.shortFields = shortFields;
- }
-
- /**
- * Gets the boolean fields.
- *
- * @return the boolean fields
- */
- public ArrayList<String> getBooleanFields() {
- if (this.booleanFields == null) {
- this.booleanFields = new ArrayList<String>();
- }
- return booleanFields;
- }
-
- /**
- * Sets the boolean fields.
- *
- * @param booleanFields the new boolean fields
- */
- public void setBooleanFields(ArrayList<String> booleanFields) {
- this.booleanFields = booleanFields;
- }
-
- /**
- * Gets the required fields.
- *
- * @return the required fields
- */
- public ArrayList<String> getRequiredFields() {
- if (this.requiredFields == null) {
- this.requiredFields = new ArrayList<String>();
- }
- return requiredFields;
- }
-
- /**
- * Sets the required fields.
- *
- * @param requiredFields the new required fields
- */
- public void setRequiredFields(ArrayList<String> requiredFields) {
- this.requiredFields = requiredFields;
- }
-
- /**
- * Gets the ordered fields.
- *
- * @return the ordered fields
- */
- public ArrayList<String> getOrderedFields() {
- if (this.orderedFields == null) {
- this.orderedFields = new ArrayList<String>();
- }
- return this.orderedFields;
- }
-
- /**
- * Gets the all fields.
- *
- * @return the all fields
- */
- public ArrayList<String> getAllFields() {
-
- ArrayList<String> allFields = new ArrayList<String>();
- allFields.addAll(getBooleanFields());
- allFields.addAll(getStringListFields());
- allFields.addAll(getStringFields());
- allFields.addAll(getIntFields());
- allFields.addAll(getLongFields());
- allFields.addAll(getShortFields());
-
- return allFields;
- }
-
- /**
- * Gets the plural name.
- *
- * @return the plural name
- */
- public String getPluralName() {
-
- if (simpleName.contains("List") || simpleName.contains("-list") )
- return "";
- String[] fullNameList = getFullName().split("/");
- return fullNameList[fullNameList.length - 2];
- }
-
- /**
- * Sets the node alt key 1 props.
- *
- * @param _dbRulesNodeAltKey1Props the db rules node alt key 1 props
- */
- public void setNodeAltKey1Props(Multimap<String, String> _dbRulesNodeAltKey1Props) {
- this.NodeAltKey1Props = _dbRulesNodeAltKey1Props;
- }
-
- /**
- * Gets the node alt key 1 props.
- *
- * @return the node alt key 1 props
- */
- public Multimap<String,String> getNodeAltKey1Props() {
- return this.NodeAltKey1Props;
- }
-
- /**
- * Sets the node dependencies.
- *
- * @param _dbRulesNodeDependencies the db rules node dependencies
- */
- public void setNodeDependencies(Multimap<String, String> _dbRulesNodeDependencies) {
- this.NodeDependencies = _dbRulesNodeDependencies;
- }
-
- /**
- * Gets the node dependencies.
- *
- * @return the node dependencies
- */
- public Multimap<String,String> getNodeDependencies() {
- return this.NodeDependencies;
- }
-
- /**
- * Gets the recurse to resource.
- *
- * @return the recurse to resource
- */
- public AAIResource getRecurseToResource() {
- return this.recurseToResource;
- }
-
- /**
- * Sets the recurse to resource.
- *
- * @param ancestor the new recurse to resource
- */
- public void setRecurseToResource(AAIResource ancestor) {
- this.recurseToResource = ancestor;
-
- }
-
- /**
- * Sets the allow direct write.
- *
- * @param allowDirectWrite the new allow direct write
- */
- public void setAllowDirectWrite(boolean allowDirectWrite) {
- this.allowDirectWrite = allowDirectWrite;
- }
-
- /**
- * Checks if is allow direct write.
- *
- * @return true, if is allow direct write
- */
- public boolean isAllowDirectWrite() {
- return this.allowDirectWrite;
- }
-
- /**
- * Sets the allow direct read.
- *
- * @param allowDirectRead the new allow direct read
- */
- public void setAllowDirectRead(boolean allowDirectRead) {
- this.allowDirectRead = allowDirectRead;
- }
-
- /**
- * Checks if is allow direct read.
- *
- * @return true, if is allow direct read
- */
- public boolean isAllowDirectRead() {
- return this.allowDirectRead;
- }
-
- /**
- * Gets the auto gen uuid fields.
- *
- * @return the auto gen uuid fields
- */
- public ArrayList<String> getAutoGenUuidFields() {
- if (this.autoGenUuidFields == null) {
- this.autoGenUuidFields = new ArrayList<String>();
- }
- return this.autoGenUuidFields;
- }
-}
diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResourceKey.java b/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResourceKey.java
deleted file mode 100644
index aa3c1e50..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResourceKey.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.domain.model;
-
-import com.google.common.base.CaseFormat;
-
-public class AAIResourceKey {
- private String keyName;
- private String keyType;
- private String pathParamName;
- private String dnCamKeyName;
-
- /**
- * Gets the key name.
- *
- * @return the key name
- */
- public String getKeyName() {
- return keyName;
- }
-
- /**
- * Sets the key name.
- *
- * @param keyName the new key name
- */
- public void setKeyName(String keyName) {
- this.keyName = keyName;
- }
-
- /**
- * Gets the key type.
- *
- * @return the key type
- */
- public String getKeyType() {
- return keyType;
- }
-
- /**
- * Sets the key type.
- *
- * @param t the new key type
- */
- public void setKeyType(String t) {
- this.keyType = t;
- }
-
- /**
- * Gets the path param name.
- *
- * @return the path param name
- */
- public String getPathParamName() {
- return pathParamName;
- }
-
- /**
- * Sets the path param name.
- *
- * @param pathParamName the new path param name
- */
- public void setPathParamName(String pathParamName) {
- this.pathParamName = pathParamName;
- }
-
- /**
- * Gets the dn cam key name.
- *
- * @return the dn cam key name
- */
- public String getDnCamKeyName() {
- return dnCamKeyName;
- }
-
- /**
- * Sets the dn cam key name.
- *
- * @param dnCamKeyName the new dn cam key name
- */
- public void setDnCamKeyName(String dnCamKeyName) {
- this.dnCamKeyName = dnCamKeyName;
- }
-
-}
diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResources.java b/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResources.java
deleted file mode 100644
index 0a91ca6a..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResources.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.domain.model;
-
-import java.util.HashMap;
-
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-
-public class AAIResources {
-
- private DynamicJAXBContext jaxbContext;
-
- private HashMap<String, AAIResource> aaiResources;
- private HashMap<String, AAIResource> resourceLookup;
-
-
- /**
- * Gets the aai resources.
- *
- * @return the aai resources
- */
- public HashMap<String, AAIResource> getAaiResources() {
- if (aaiResources == null) {
- aaiResources = new HashMap<String, AAIResource>();
- }
- return aaiResources;
- }
-
- /**
- * Gets the jaxb context.
- *
- * @return the jaxb context
- */
- public DynamicJAXBContext getJaxbContext() {
- return jaxbContext;
- }
-
- /**
- * Sets the jaxb context.
- *
- * @param jaxbContext the new jaxb context
- */
- public void setJaxbContext(DynamicJAXBContext jaxbContext) {
- this.jaxbContext = jaxbContext;
- }
-
- /**
- * Gets the resource lookup.
- *
- * @return the resource lookup
- */
- public HashMap<String, AAIResource> getResourceLookup() {
- if (resourceLookup == null) {
- resourceLookup = new HashMap<String, AAIResource>();
- }
- return resourceLookup;
- }
-
- /**
- * Sets the resource lookup.
- *
- * @param resourceLookup the resource lookup
- */
- public void setResourceLookup(HashMap<String, AAIResource> resourceLookup) {
- this.resourceLookup = resourceLookup;
- }
-
-}
diff --git a/aai-core/src/main/java/org/openecomp/aai/ingestModel/ConvertXmlToJsonMoxyOxm.java b/aai-core/src/main/java/org/openecomp/aai/ingestModel/ConvertXmlToJsonMoxyOxm.java
deleted file mode 100644
index 5861f38a..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/ingestModel/ConvertXmlToJsonMoxyOxm.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.ingestModel;
-
-import java.io.File;
-import java.io.StringWriter;
-import java.util.ArrayList;
-
-import javax.xml.transform.stream.StreamSource;
-
-import org.eclipse.persistence.dynamic.DynamicEntity;
-import org.eclipse.persistence.jaxb.JAXBMarshaller;
-import org.eclipse.persistence.jaxb.JAXBUnmarshaller;
-import org.eclipse.persistence.jaxb.MarshallerProperties;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-
-import org.openecomp.aai.util.AAIConfig;
-import org.openecomp.aai.util.AAIConstants;
-
-/**
- * The Class ConvertXmlToJsonMoxyOxm.
- */
-public class ConvertXmlToJsonMoxyOxm
-{
- /**
- * The main method.
- *
- * @param args the arguments
- * @throws Exception the exception
- */
- public static void main(String[] args) throws Exception {
-
- String _apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- String fileName = null;
- String dynamicType = null;
- if (args.length > 0) {
- if (args[0] != null) {
- _apiVersion = args[0];
- }
- if (args[1] != null) {
- fileName = args[1];
- }
- if (args[2] != null) {
- dynamicType = args[2];
- }
- }
-
- if (fileName == null) {
- System.err.println("You must specify a fileName");
- System.exit(0);
- }
- if (dynamicType == null) {
- System.err.println("You must specify a dynamic Type");
- System.exit(0);
- }
-
- ArrayList<String> apiVersions = new ArrayList<String>();
- apiVersions.add(_apiVersion);
- final IngestModelMoxyOxm m = new IngestModelMoxyOxm();
- m.init(apiVersions, false);
-
- DynamicJAXBContext jaxbContext = IngestModelMoxyOxm.aaiResourceContainer.get(_apiVersion).getJaxbContext();
-
- JAXBUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();
-
- Class<? extends DynamicEntity> resultClass = jaxbContext.newDynamicEntity(dynamicType).getClass();
-
- DynamicEntity meObject = (DynamicEntity) unmarshaller.unmarshal(new StreamSource(new File(fileName)), resultClass).getValue();
-
- // put it out as JSON
-
- JAXBMarshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, true);
-
- marshaller.setProperty("eclipselink.media-type", "application/json");
- marshaller.setProperty("eclipselink.json.include-root", false);
- marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE) ;
-
- StringWriter writer = new StringWriter();
- marshaller.marshal(meObject, writer);
-
- System.out.println(writer.toString());
-
- System.exit(0);
- }
-
-}
diff --git a/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java b/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java
index 18006295..885f2854 100644
--- a/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java
+++ b/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java
@@ -22,24 +22,20 @@ package org.openecomp.aai.ingestModel;
import java.io.File;
import java.io.PrintWriter;
-import java.io.StringWriter;
import java.util.ArrayList;
-import java.util.Map;
+import java.util.List;
+import java.util.Map.Entry;
import java.util.UUID;
import javax.xml.transform.stream.StreamSource;
-import org.eclipse.persistence.dynamic.DynamicEntity;
-import org.eclipse.persistence.jaxb.JAXBMarshaller;
-import org.eclipse.persistence.jaxb.JAXBUnmarshaller;
-import org.eclipse.persistence.jaxb.MarshallerProperties;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-
-import org.openecomp.aai.domain.model.AAIResource;
-import org.openecomp.aai.domain.model.AAIResources;
+import org.openecomp.aai.introspection.Introspector;
+import org.openecomp.aai.introspection.Loader;
+import org.openecomp.aai.introspection.LoaderFactory;
+import org.openecomp.aai.introspection.ModelType;
+import org.openecomp.aai.introspection.Version;
import org.openecomp.aai.util.AAIConfig;
import org.openecomp.aai.util.AAIConstants;
-import com.google.common.base.CaseFormat;
/**
* The Class CreateWidgetModels.
@@ -78,33 +74,27 @@ public class CreateWidgetModels
System.exit(0);
}
- ArrayList<String> apiVersions = new ArrayList<String>();
- apiVersions.add(_apiVersion);
- final IngestModelMoxyOxm m = new IngestModelMoxyOxm();
- m.init(apiVersions, false);
-
- AAIResources aaiResources = IngestModelMoxyOxm.aaiResourceContainer.get(_apiVersion);
- DynamicJAXBContext jaxbContext = aaiResources.getJaxbContext();
+ Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.valueOf(_apiVersion));
// iterate the collection of resources
ArrayList<String> processedWidgets = new ArrayList<String>();
- for (Map.Entry<String, AAIResource> aaiResEnt : aaiResources.getAaiResources().entrySet()) {
- DynamicEntity meObject = jaxbContext.newDynamicEntity("inventory.aai.openecomp.org." + _apiVersion + ".Model");
+ for (Entry<String, Introspector> aaiResEnt : loader.getAllObjects().entrySet()) {
+ Introspector meObject = loader.introspectorFromName("model");
// no need for a ModelVers DynamicEntity
- AAIResource aaiRes = aaiResEnt.getValue();
+ Introspector aaiRes = aaiResEnt.getValue();
- if (aaiRes.getResourceType().equals("node")) {
- String resource = aaiRes.getSimpleName();
+ if (!(aaiRes.isContainer() || aaiRes.getName().equals("aai-internal"))) {
+ String resource = aaiRes.getName();
if (processedWidgets.contains(resource)) {
continue;
}
processedWidgets.add(resource);
- String widgetName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, resource);
+ String widgetName = resource;
String filePathString = widgetJsonDir + "/" + widgetName + "-" + modelVersion + ".json";
File f = new File(filePathString);
@@ -116,46 +106,32 @@ public class CreateWidgetModels
if (f2.exists()) {
System.out.println("Using old file for " + resource + ".");
- JAXBUnmarshaller unmarshaller = jaxbContext.createUnmarshaller();
- unmarshaller.setProperty("eclipselink.media-type", "application/json");
- unmarshaller.setProperty("eclipselink.json.include-root", false);
- Class<? extends DynamicEntity> resultClass = meObject.getClass();
- meObject = (DynamicEntity) unmarshaller.unmarshal(new StreamSource(f2), resultClass).getValue();
+ meObject = loader.unmarshal("model", new StreamSource(f2).getReader().toString());
// override, some of them are wrong
- meObject.set("modelVersion", modelVersion);
- } else {
-
+ meObject.setValue("model-version", modelVersion);
+ } else {
System.out.println("Making new file for " + resource + ".");
- meObject.set("modelInvariantId", UUID.randomUUID().toString());
- meObject.set("modelType", "widget");
- DynamicEntity mevObject = jaxbContext.newDynamicEntity("inventory.aai.openecomp.org." + _apiVersion + ".ModelVer");
- DynamicEntity mevsObject = jaxbContext.newDynamicEntity("inventory.aai.openecomp.org." + _apiVersion + ".ModelVers");
- mevObject.set("modelVersionId", UUID.randomUUID().toString());
- mevObject.set("modelVersion", modelVersion);
- mevObject.set("modelName", widgetName);
+ meObject.setValue("model-invariant-id", UUID.randomUUID().toString());
+ meObject.setValue("model-type", "widget");
+ Introspector mevObject = loader.introspectorFromName("model-ver");
+ Introspector mevsObject = loader.introspectorFromName("model-vers");
+ mevObject.setValue("model-version-id", UUID.randomUUID().toString());
+ mevObject.setValue("model-version", modelVersion);
+ mevObject.setValue("model-Name", widgetName);
// make a list of dynamic Entities
- ArrayList<DynamicEntity> mevsList = new ArrayList<DynamicEntity>();
+ List<Object> mevsList = new ArrayList<>();
// add this one, it will be the only one in the list in this case
- mevsList.add(mevObject);
- mevsObject.set("modelVer", mevsList);
+ mevsList.add(mevObject.getUnderlyingObject());
+ mevsObject.setValue("model-ver", mevsList);
// Have to figure out how to add my mev object to the mevsObject,
// the modelVers is a list of dynamic entities so we can just attach the array here
- meObject.set("modelVers",mevsObject);
+ meObject.setValue("model-vers",mevsObject.getUnderlyingObject());
}
// put it out as JSON
- JAXBMarshaller marshaller = jaxbContext.createMarshaller();
- marshaller.setProperty(JAXBMarshaller.JAXB_FORMATTED_OUTPUT, true);
-
- marshaller.setProperty("eclipselink.media-type", "application/json");
- marshaller.setProperty("eclipselink.json.include-root", false);
- marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE) ;
-
- StringWriter writer = new StringWriter();
- marshaller.marshal(meObject, writer);
PrintWriter out = new PrintWriter(f);
- out.println(writer.toString());
+ out.println(meObject.marshal(true));
out.close();
} else {
diff --git a/aai-core/src/main/java/org/openecomp/aai/ingestModel/DbMaps.java b/aai-core/src/main/java/org/openecomp/aai/ingestModel/DbMaps.java
deleted file mode 100644
index c872f384..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/ingestModel/DbMaps.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.ingestModel;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-
-/**
- * The Class DbMaps.
- */
-public class DbMaps {
-
- // from oxm file
- public Multimap<String, String> NodeAltKey1Props = ArrayListMultimap.create();
-
- public Multimap<String, String> NodeDependencies = ArrayListMultimap.create();
-
- public Multimap<String, String> NodeNameProps = ArrayListMultimap.create();
-
- public Multimap<String, String> NodeMapIndexedProps = ArrayListMultimap.create();
-
- public Multimap<String, String> NodeMapUniqueProps = ArrayListMultimap.create();
-
- public Map<Integer, String> EdgeInfoMap = new LinkedHashMap<Integer, String>();
-
- public Map<String, String> ReservedPropNames = new HashMap<String, String>();
-
- // from AAIResources
- public Multimap<String, String> NodeProps = ArrayListMultimap.create();
-
- public Multimap<String, String> NodeKeyProps = ArrayListMultimap.create();
-
- public Map<String, String> NodePlural = new HashMap<String, String>();
-
- public Map<String, String> NodeNamespace = new HashMap<String, String>();
-
- public Map<String, String> PropertyVersionInfoMap = new HashMap<String, String>();
-
- public Map<String, String> NodeVersionInfoMap = new HashMap<String, String>();
-
- public Map<String, String> PropertyDataTypeMap = new HashMap<String, String>();
-
- }
diff --git a/aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelListener.java b/aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelListener.java
deleted file mode 100644
index 6adcceea..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelListener.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.ingestModel;
-
-import java.util.ArrayList;
-
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-
-import org.openecomp.aai.exceptions.AAIException;
-import org.openecomp.aai.logging.ErrorLogHelper;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-
-/**
- * The listener interface for receiving ingestModel events.
- * The class that is interested in processing a ingestModel
- * event implements this interface, and the object created
- * with that class is registered with a component using the
- * component's <code>addIngestModelListener<code> method. When
- * the ingestModel event occurs, that object's appropriate
- * method is invoked.
- *
- * @see IngestModelEvent
- */
-public class IngestModelListener implements ServletContextListener {
-
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IngestModelListener.class);
-
-/**
- * Destroys context.
- *
- * @param arg0 the ServletContextEvent
- */
-//@Override
- public void contextDestroyed(ServletContextEvent arg0) {
- IngestModelMoxyOxm m = new IngestModelMoxyOxm();
- m.cleanup();
- LOGGER.info("AAI Auth Listener contextDestroyed() complete.");
- }
-
-//Run this before web application is started
- /**
- * Initializaes the context.
- *
- * @param arg0 the ServletContextEvent
- */
-//@Override
- public void contextInitialized(ServletContextEvent arg0) {
-
- LOGGER.info("IngestModel starts initialization...");
- try {
- ArrayList<String> apiVersions = new ArrayList<String>();
- apiVersions.add("v10");
- apiVersions.add("v9");
- apiVersions.add("v8");
- apiVersions.add("v7");
- apiVersions.add("v2");
- IngestModelMoxyOxm m = new IngestModelMoxyOxm();
- m.init(apiVersions);
- } catch (AAIException e) {
- ErrorLogHelper.logException(e);
- }
- }
-}
diff --git a/aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelMoxyOxm.java b/aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelMoxyOxm.java
deleted file mode 100644
index 30ffb88c..00000000
--- a/aai-core/src/main/java/org/openecomp/aai/ingestModel/IngestModelMoxyOxm.java
+++ /dev/null
@@ -1,862 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * org.openecomp.aai
- * ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
- * ================================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=========================================================
- */
-
-package org.openecomp.aai.ingestModel;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.Vector;
-
-import org.eclipse.persistence.descriptors.ClassDescriptor;
-import org.eclipse.persistence.dynamic.DynamicType;
-import org.eclipse.persistence.internal.dynamic.DynamicTypeImpl;
-import org.eclipse.persistence.internal.helper.DatabaseField;
-import org.eclipse.persistence.jaxb.JAXBContextProperties;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory;
-import org.eclipse.persistence.mappings.DatabaseMapping;
-import org.eclipse.persistence.oxm.XMLField;
-import org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping;
-import org.eclipse.persistence.oxm.mappings.XMLCompositeDirectCollectionMapping;
-
-import org.openecomp.aai.domain.model.AAIResource;
-import org.openecomp.aai.domain.model.AAIResourceKey;
-import org.openecomp.aai.domain.model.AAIResourceKeys;
-import org.openecomp.aai.domain.model.AAIResources;
-import org.openecomp.aai.exceptions.AAIException;
-import org.openecomp.aai.logging.ErrorLogHelper;
-import org.openecomp.aai.util.AAIConfig;
-import org.openecomp.aai.util.AAIConstants;
-import org.openecomp.aai.util.FileWatcher;
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.google.common.base.CaseFormat;
-import com.google.common.base.Splitter;
-import com.google.common.collect.Multimap;
-
-/**
- * The Class IngestModelMoxyOxm.
- */
-public class IngestModelMoxyOxm
-{
-
- private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IngestModelMoxyOxm.class);
-
- public static HashMap<String, AAIResources> aaiResourceContainer;
- public static HashMap<String, DbMaps> dbMapsContainer;
-
- private static HashMap<String, Timer> timers = new HashMap<String,Timer>();
-
- /**
- * The main method.
- *
- * @param args the arguments
- * @throws Exception the exception
- */
- public static void main(String[] args) throws Exception {
-
- String _apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
-
- if (args.length > 0) {
- if (args[0] != null) {
- _apiVersion = args[0];
- }
- }
- ArrayList<String> apiVersions = new ArrayList<String>();
- apiVersions.add(_apiVersion);
- final IngestModelMoxyOxm m = new IngestModelMoxyOxm();
- m.init(apiVersions, false);
-
- ArrayList<String> endpoints = new ArrayList<String>();
-
- for (Map.Entry<String, AAIResources> ent: aaiResourceContainer.entrySet()) {
-
- AAIResources aaiResources = ent.getValue();
- DynamicJAXBContext jaxbContext = aaiResources.getJaxbContext();
- for (Map.Entry<String, AAIResource> aaiResEnt : aaiResources.getAaiResources().entrySet()) {
- AAIResource aaiRes = aaiResEnt.getValue();
-
- String uri = aaiRes.getUri();
- if (uri != null) {
- endpoints.add(uri);
- DynamicType dt = jaxbContext.getDynamicType(aaiRes.getResourceClassName());
- if (dt.containsProperty("relationshipList")) {
- endpoints.add(uri + "/relationship-list/relationship");
- }
- }
- }
- Collections.sort(endpoints);
- for (String endpoint : endpoints) {
- if (!endpoint.contains("/aai-internal/")) {
- System.out.println(endpoint);
- }
- }
- }
-
- System.exit(0);
- }
-
- /**
- * Inits the.
- *
- * @param apiVersions the api versions
- * @throws Exception the exception
- */
- public synchronized void init(ArrayList<String> apiVersions) throws AAIException {
- final IngestModelMoxyOxm m = new IngestModelMoxyOxm();
- m.init(apiVersions, true);
- }
-
- /**
- * Inits the.
- *
- * @param apiVersions the api versions
- * @param setTimer the set timer
- * @throws AAIException If AAIConfig is missing necessary properties
- * @throws Exception the exception
- */
- public synchronized void init(ArrayList<String> apiVersions, Boolean setTimer) throws AAIException {
-
- aaiResourceContainer = new HashMap<String, AAIResources>();
- dbMapsContainer = new HashMap<String, DbMaps>();
-
- final IngestModelMoxyOxm m = new IngestModelMoxyOxm();
-
- for (String apiVersion : apiVersions) {
-
- String relationshipUtils = "org.openecomp.aai.dbmap.RelationshipUtils";
- final String thisRelationshipUtils = relationshipUtils;
-
- final String thisApiVersion = apiVersion;
- final String schemaFile = AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + apiVersion + ".xml";
-
- m.loadSchema(apiVersion, schemaFile, relationshipUtils);
-
- if (!setTimer) continue;
-
- TimerTask task = null;
- task = new FileWatcher ( new File(schemaFile)) {
- protected void onChange( File file ) {
- m.loadSchema(thisApiVersion, schemaFile, thisRelationshipUtils);
- }
- };
-
- if (!timers.containsKey(apiVersion)) {
- Timer timer = new Timer();
- timer.schedule( task , new Date(), 10000 );
- timers.put(apiVersion, timer);
-
- }
- }
- if (apiVersions.contains(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP))) {
- m.createPropertyAndNodeVersionInfoMapFromDbMaps();
-
- for (Map.Entry<String, AAIResources> ent: aaiResourceContainer.entrySet()) {
- String apiVersion = ent.getKey();
- AAIResources aaiResources = ent.getValue();
-
- DbMaps dbMap = dbMapsContainer.get(apiVersion);
-
- for (Map.Entry<String, AAIResource> aaiResEnt : aaiResources.getAaiResources().entrySet()) {
- AAIResource aaiRes = aaiResEnt.getValue();
- aaiRes.setPropertyDataTypeMap(dbMap.PropertyDataTypeMap);
- aaiRes.setNodeKeyProps(dbMap.NodeKeyProps);
- aaiRes.setNodeNameProps(dbMap.NodeNameProps);
- aaiRes.setNodeMapIndexedProps(dbMap.NodeMapIndexedProps);
- }
- }
- }
- }
-
- /**
- * Load schema.
- *
- * @param apiVersion the api version
- * @param schemaFile the schema file
- * @param relationshipUtils the relationship utils
- * @return the dynamic JAXB context
- */
- private DynamicJAXBContext loadSchema(String apiVersion,
- String schemaFile,
- String relationshipUtils) {
-
- AAIResources aaiResources = new AAIResources();
- DbMaps dbMaps = new DbMaps();
- DynamicJAXBContext jaxbContext = null;
-
- try {
-
- InputStream iStream = new FileInputStream(new File(schemaFile));
-
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream);
-
- jaxbContext =
- DynamicJAXBContextFactory.createContextFromOXM(IngestModelMoxyOxm.class.getClassLoader(), properties);
-
- aaiResources.setJaxbContext(jaxbContext);
- String rootClassName = "inventory.aai.openecomp.org." + apiVersion + ".Inventory";
-
- if ("v2".equals(apiVersion)) {
- rootClassName = "inventory.aai.openecomp.org.Inventory";
- }
-
- DynamicTypeImpl t = (DynamicTypeImpl)jaxbContext.getDynamicType(rootClassName);
-
- lookAtDynamicResource("Inventory",
- "inventory.aai.openecomp.org." + apiVersion,
- jaxbContext,
- t,
- 1, "", "", apiVersion, "/" + apiVersion, false, aaiResources, dbMaps, relationshipUtils);
-
- } catch (Exception e) {
- ErrorLogHelper.logException(new AAIException("AAI_3000", e));
- }
-
- LOGGER.info("---> Loading " + apiVersion + " in aaiResourceContainer");
- aaiResourceContainer.put(apiVersion, aaiResources);
-
- createDbMapsfromAAIResources(aaiResources, dbMaps);
-
- LOGGER.info("---> Loading " + apiVersion + " in dbMapsContainer");
- dbMapsContainer.put(apiVersion, dbMaps);
-
- return jaxbContext;
- }
-
- /**
- * Cleanup.
- */
- public void cleanup() {
- aaiResourceContainer.clear();
- dbMapsContainer.clear();
- }
-
- /**
- * Look at dynamic resource.
- *
- * @param resource the resource
- * @param pojoBase the pojo base
- * @param jaxbContext the jaxb context
- * @param t the t
- * @param depth the depth
- * @param parent the parent
- * @param namespace the namespace
- * @param apiVersion the api version
- * @param url the url
- * @param container the container
- * @param aaiResources the aai resources
- * @param dbMaps the db maps
- * @param relationshipUtils the relationship utils
- * @throws ClassNotFoundException the class not found exception
- * @throws NoSuchFieldException the no such field exception
- * @throws SecurityException the security exception
- * @throws IOException Signals that an I/O exception has occurred.
- */
- private void lookAtDynamicResource(String resource,
- String pojoBase,
- DynamicJAXBContext jaxbContext,
- DynamicTypeImpl t,
- int depth,
- String parent,
- String namespace,
- String apiVersion,
- String url,
- boolean container,
- AAIResources aaiResources,
- DbMaps dbMaps,
- String relationshipUtils
- )
- throws ClassNotFoundException, NoSuchFieldException, SecurityException, IOException {
-
- String className = pojoBase + "." + CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL, resource);
-
- AAIResource parentResource = aaiResources.getAaiResources().get(parent);
-
- AAIResources siblings = null;
-
- if (parentResource == null) {
- String fullName = "/" + resource;
- AAIResource aaiRes = new AAIResource();
- aaiRes.setFullName(fullName);
- aaiRes.setSimpleName(resource);
- aaiRes.setResourceType("container");
- aaiRes.setResourceClassName(className);
- aaiRes.setApiVersion(apiVersion);
-
- aaiResources.getAaiResources().put(fullName, aaiRes);
- parentResource = aaiRes;
- }
-
- if (depth >= 50) return;
-
- siblings = parentResource.getChildren();
-
- if (depth == 2) {
- namespace = resource;
- }
- if (depth >= 50) {
- return;
- }
-
- /* if ("Actions".equals(namespace) || "Search".equals(namespace)) {
- return;
- }*/
-
- ClassDescriptor cd = t.getDescriptor();
-
- createDbMapsfromOXM(cd.getProperties(), resource, dbMaps);
-
-
-
- Vector<DatabaseMapping> dm = cd.getMappings();
-
- for (DatabaseMapping dmInst : dm) {
- String dmName = dmInst.getAttributeName();
-
- ClassDescriptor cd2 = dmInst.getReferenceDescriptor();
- if (cd2 != null) {
-
- String newClassName = cd2.getJavaClassName();
- //
- if (newClassName.contains("RelationshipList")) {
- continue;
- }
-
- DynamicTypeImpl newDt = (DynamicTypeImpl)jaxbContext.getDynamicType(newClassName);
-
- if (dmInst instanceof XMLCompositeCollectionMapping) {
- String simpleName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, dmName);
- // System.out.println(spaces + "+ List of A&AI Object named " + simpleName);
-
- String hypName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, simpleName);
-
- String fullName = parent + "/" + simpleName;
-
- //Class<?> newClazz = Class.forName(newClassName);
- AAIResource aaiRes = new AAIResource();
-
- if ("cvlan-tag-entry".equals(hypName)) {
- }
-
- ClassDescriptor cd3 = newDt.getDescriptor();
-
- boolean allowDirectWrite = true;
- if (cd3.getProperties().containsKey("allowDirectWrite")) {
- if (cd3.getProperties().get("allowDirectWrite").equals("false")) {
- allowDirectWrite = false;
- }
- }
-
-
- boolean allowDirectRead = true;
- if (cd3.getProperties().containsKey("allowDirectRead")) {
- if (cd3.getProperties().get("allowDirectRead").equals("false")) {
- allowDirectRead = false;
- }
- }
-
- List<DatabaseField> dbfList = cd3.getPrimaryKeyFields();
- ArrayList<String> keyFields = new ArrayList<String>();
-
- if (dbfList != null) {
- for (DatabaseField dbf : dbfList) {
- String name = dbf.getName();
- name = name.substring(0, name.indexOf('/'));
- keyFields.add(name);
- }
- }
- Vector<DatabaseMapping> dm2 = cd3.getMappings();
- for (DatabaseMapping dmInst2 : dm2) {
- String dmName2= CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmInst2.getAttributeName());
- DatabaseField xf2 = dmInst2.getField();
- if (dmInst2.getProperties().containsKey("autoGenerateUuid")) {
- if (dmInst2.getProperties().get("autoGenerateUuid").equals("true")) {
- aaiRes.getAutoGenUuidFields().add(dmName2);
- }
- }
- if (xf2 instanceof XMLField) {
- XMLField x = (XMLField)xf2;
- if (x != null) {
- if (x.isRequired()) {
- aaiRes.getRequiredFields().add(dmName2);
- }
- }
-
- }
- try {
- Class<?> xf2Clazz = xf2.getType();
- if (xf2Clazz.getSimpleName().equals("String")) {
- if (dmInst2 instanceof XMLCompositeDirectCollectionMapping) {
- aaiRes.getStringListFields().add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmName2));
- } else {
- aaiRes.getStringFields().add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmName2));
- }
- } else if (xf2Clazz.getSimpleName().toLowerCase().contains("long")) {
- aaiRes.getLongFields().add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmName2));
- } else if (xf2Clazz.getSimpleName().toLowerCase().contains("int")) {
- aaiRes.getIntFields().add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmName2));
- } else if (xf2Clazz.getSimpleName().toLowerCase().contains("short")) {
- aaiRes.getShortFields().add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmName2));
- } else if (xf2Clazz.getSimpleName().toLowerCase().contains("boolean")) {
- aaiRes.getBooleanFields().add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmName2));
- }
- } catch (Exception e) { // this xf2.getType() throws null pointer when I try to get the type and it doesn't have one
- ;
- }
- }
-
- // get the key(s) from DbRules
- String uriKey = "";
- LinkedHashMap<String, ArrayList<String>> itemKeyList = new LinkedHashMap<String, ArrayList<String>>();
-
- aaiRes.setApiVersion(apiVersion);
- itemKeyList.put(hypName, new ArrayList<String>());
- for (String thisKey : keyFields) {
- String pathParamName = hypName + "-" + thisKey;
-
- AAIResourceKey aaiResKey = new AAIResourceKey();
- aaiResKey.setKeyName(thisKey);
- aaiResKey.setDnCamKeyName(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, pathParamName));
- aaiResKey.setPathParamName(pathParamName);
-
- for (DatabaseMapping dmInst2 : dm2) {
- String dmName2= CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,dmInst2.getAttributeName());
- if (dmName2.equals(thisKey)){
- DatabaseField xf2 = dmInst2.getField();
- aaiResKey.setKeyType(xf2.getType().getSimpleName());
- break;
- }
- }
-
- aaiRes.getAaiResourceKeys().getAaiResourceKey().add(aaiResKey);
-
- if (siblings != null) {
- siblings.getAaiResources().put(fullName, aaiRes);
- }
-
- uriKey += "/{" + pathParamName + "}";
- }
-
- String newUri = url + "/" + hypName + uriKey;
-
-
- if ("v2".equals(apiVersion)) {
- aaiRes.setResourceClassName("inventory.aai.openecomp.org." + simpleName);
- } else {
- aaiRes.setResourceClassName("inventory.aai.openecomp.org." + apiVersion + "." + simpleName);
- }
-
- aaiRes.setAllowDirectWrite(allowDirectWrite);
- aaiRes.setAllowDirectRead(allowDirectRead);
- aaiRes.setNamespace(namespace);
- aaiRes.setSimpleName(simpleName);
-
- if (!aaiResources.getResourceLookup().containsKey(simpleName)) {
- aaiResources.getResourceLookup().put(simpleName, aaiRes);
- }
-
- aaiRes.setFullName(fullName);
- aaiRes.setUri(newUri);
- aaiRes.setResourceType("node");
- if ("v2".equals(apiVersion)) {
- aaiRes.setRelationshipListClass("inventory.aai.openecomp.org.RelationshipList");
- } else {
- aaiRes.setRelationshipListClass("inventory.aai.openecomp.org." + apiVersion + ".RelationshipList");
- }
- aaiRes.setRelationshipUtils(relationshipUtils);
-
- if (parentResource != null) {
- aaiRes.setParent(parentResource);
- } else {
- aaiRes.setParent(aaiRes);
- }
-
- aaiResources.getAaiResources().put(fullName, aaiRes);
-
- if (siblings != null) {
- siblings.getAaiResources().put(fullName, aaiRes);
- }
-// AAIResource ancestor = parentResource;
-//
-// boolean recursiveEntity = false;
-// while (ancestor != null) {
-//
-// if (ancestor.getSimpleName().equals(aaiRes.getSimpleName())) {
-// recursiveEntity = true;
-// // attach it to the container that contains the resource above this one with the same name
-// if (ancestor.getParent() != null && ancestor.getParent().getResourceType().equals("container")) {
-// AAIResource recurseHere = ancestor.getParent();
-// aaiRes.setRecurseToResource(recurseHere);
-// }
-// break;
-// }
-// ancestor = ancestor.getParent();
-//
-// }
-// if (recursiveEntity == false) {
- lookAtDynamicResource(cd2.getJavaClass().getSimpleName(),
- pojoBase,
- jaxbContext,
- newDt,
- (depth + 1), fullName, namespace, apiVersion, newUri, false, aaiResources, dbMaps,
- relationshipUtils);
-// }
- } else {
- String simpleName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, dmName);
- String fullName = parent + "/" + simpleName;
- // System.out.println(spaces + "+ Container of A&AI Object named " + simpleName);
-
- AAIResource aaiRes = new AAIResource();
- if (parentResource != null) {
- aaiRes.setParent(parentResource);
- } else {
- aaiRes.setParent(aaiRes);
- }
- aaiRes.setAllowDirectWrite(true);
- aaiRes.setAllowDirectRead(true);
- aaiRes.setFullName(fullName);
- aaiRes.setSimpleName(simpleName);
- if (!aaiResources.getResourceLookup().containsKey(simpleName)) {
- aaiResources.getResourceLookup().put(simpleName, aaiRes);
- }
- aaiRes.setResourceType("container");
-
- if ("v2".equals(apiVersion)) {
- aaiRes.setResourceClassName("inventory.aai.openecomp.org." + simpleName);
- aaiRes.setRelationshipListClass("inventory.aai.openecomp.org.RelationshipList");
- } else {
- aaiRes.setResourceClassName("inventory.aai.openecomp.org." + apiVersion + "." + simpleName);
- aaiRes.setRelationshipListClass("inventory.aai.openecomp.org." + apiVersion + ".RelationshipList");
- }
- aaiRes.setApiVersion(apiVersion);
-
- aaiResources.getAaiResources().put(fullName, aaiRes);
- aaiRes.setRelationshipUtils(relationshipUtils);
-
- String hypName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, simpleName);
-
- if (siblings != null) {
- siblings.getAaiResources().put(fullName, aaiRes);
- }
-
- lookAtDynamicResource(cd2.getJavaClass().getSimpleName(),
- pojoBase,
- jaxbContext,
- (DynamicTypeImpl)jaxbContext.getDynamicType(newClassName),
- (depth + 1), fullName, namespace, apiVersion, url + "/" + hypName, false, aaiResources, dbMaps,
- relationshipUtils);
-
-
- }
- }
- }
- }
-
- /**
- * Creates the db mapsfrom OXM.
- *
- * @param propMap the prop map
- * @param resource the resource
- * @param dbMaps the db maps
- */
- private void createDbMapsfromOXM(Map<?, ?> propMap, String resource, DbMaps dbMaps) {
- String nodeType = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, resource);
- if ("cvlan-tag-entry".equals(nodeType)) {
- nodeType = "cvlan-tag";
- }
-
- // if we have nodes dependent on multiple nodes we might revisit the node again - skip then
- if (propMap.size() > 1 && !dbMaps.NodeMapIndexedProps.containsKey(nodeType)) {
-
- if (propMap.containsKey("nameProps"))
- dbMaps.NodeNameProps.putAll(nodeType,
- (Iterable<String>) fromCommaSeparatedString(propMap.get("nameProps").toString()));
-
- if (propMap.containsKey("indexedProps"))
- dbMaps.NodeMapIndexedProps.putAll(nodeType,
- (Iterable<String>) fromCommaSeparatedString(propMap.get("indexedProps").toString()));
-
- if (propMap.containsKey("dependentOn"))
- dbMaps.NodeDependencies.putAll(nodeType,
- (Iterable<String>) fromCommaSeparatedString(propMap.get("dependentOn").toString()));
-
- if (propMap.containsKey("alternateKeys1"))
- dbMaps.NodeAltKey1Props.putAll(nodeType,
- (Iterable<String>) fromCommaSeparatedString(propMap.get("alternateKeys1").toString()));
-
- if (propMap.containsKey("uniqueProps"))
- dbMaps.NodeMapUniqueProps.putAll(nodeType,
- (Iterable<String>) fromCommaSeparatedString(propMap.get("uniqueProps").toString()));
-
- // build EdgeInfoMap
- if (propMap.containsKey("edgeInfo")) {
- int i = 0;
- Iterable<String> edgeInfoIterable = (Iterable<String>) fromCommaSeparatedString(propMap.get("edgeInfo").toString());
- Iterator<String> edgeInfoIterator = edgeInfoIterable.iterator();
- while(edgeInfoIterator.hasNext()) {
- String propName = edgeInfoIterator.next();
- dbMaps.EdgeInfoMap.put(i++, propName);
- }
- }
- }
- }
-
- /**
- * Creates the db mapsfrom AAI resources.
- *
- * @param aaiResources the aai resources
- * @param dbMaps the db maps
- */
- private void createDbMapsfromAAIResources(AAIResources aaiResources, DbMaps dbMaps) {
-
- for (String resource: aaiResources.getAaiResources().keySet()) {
-
- AAIResource aaiResource = aaiResources.getAaiResources().get(resource);
- String nodeType = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,aaiResource.getSimpleName());
-
- if (nodeType.equals("cvlan-tag-entry"))
- nodeType = "cvlan-tag";
-
- // Build NodeNamespace
- if (aaiResource.getNamespace() != null && !aaiResource.getNamespace().equalsIgnoreCase("search"))
- // oamNetworks is also defined under the search namespace - do not want that namespace
- dbMaps.NodeNamespace.put(nodeType, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, aaiResource.getNamespace()));
-
- // only process one nodetype once
- if (dbMaps.NodeProps.containsKey(nodeType))
- continue;
-
- // Build NodePlural
- if (aaiResource.getPluralName() != null && !aaiResource.getPluralName().equals(aaiResource.getNamespace()))
- // dont want resources which are namespaces themselves in map
- dbMaps.NodePlural.put(nodeType, CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, aaiResource.getPluralName()));
-
- // Build NodeProps
- dbMaps.NodeProps.putAll(nodeType, aaiResource.getAllFields());
-
- // build ReservedNames
- if (nodeType.equalsIgnoreCase("reserved-prop-names")) {
- for (String propName: aaiResource.getAllFields()) {
- dbMaps.ReservedPropNames.put(propName, "");
- }
- }
-
- // Build NodekeyProps
- AAIResourceKeys aaiResKeys = aaiResource.getAaiResourceKeys();
- List<String> keyList = new ArrayList<String>();
- for (AAIResourceKey rk : aaiResKeys.getAaiResourceKey()) {
- String keyProp = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN,rk.getKeyName());
- if (!keyList.contains(keyProp))
- keyList.add(keyProp);
- }
- dbMaps.NodeKeyProps.putAll(nodeType, (Iterable<String>)keyList);
-
- // Build PropertyDataTypeMap
- for (String propName: aaiResource.getBooleanFields()) {
- if (nodeType.equalsIgnoreCase("edge-prop-names")) // these properties are in mixed format in DB
- propName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, propName);
- if (propName.equals("sVCINFRA")) propName = "SVC-INFRA";
- if (propName.equals("sVCINFRAREV")) propName = "SVC-INFRA-REV";
- if (!dbMaps.PropertyDataTypeMap.containsKey(propName))
- dbMaps.PropertyDataTypeMap.put(propName, "Boolean");
- else if (!dbMaps.PropertyDataTypeMap.get(propName).equals("Boolean"))
- System.out.println(propName + "defined with mis-matched types in oxm file");
- }
- for (String propName: aaiResource.getShortFields()) {
- if (nodeType.equalsIgnoreCase("edge-prop-names")) // these properties are in mixed format in DB
- propName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, propName);
- if (propName.equals("sVCINFRA")) propName = "SVC-INFRA";
- if (propName.equals("sVCINFRAREV")) propName = "SVC-INFRA-REV";
- if (!dbMaps.PropertyDataTypeMap.containsKey(propName))
- dbMaps.PropertyDataTypeMap.put(propName, "Integer");
- else if (!dbMaps.PropertyDataTypeMap.get(propName).equals("Integer"))
- System.out.println(propName + "defined with mis-matched types in oxm file");
- }
- for (String propName: aaiResource.getLongFields()) {
- if (nodeType.equalsIgnoreCase("edge-prop-names")) // these properties are in mixed format in DB
- propName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, propName);
- if (propName.equals("sVCINFRA")) propName = "SVC-INFRA";
- if (propName.equals("sVCINFRAREV")) propName = "SVC-INFRA-REV";
- if (!dbMaps.PropertyDataTypeMap.containsKey(propName)) {
- if (propName.contains("-ts"))
- dbMaps.PropertyDataTypeMap.put(propName, "Long");
- else
- dbMaps.PropertyDataTypeMap.put(propName, "Integer");
- } else if (!dbMaps.PropertyDataTypeMap.get(propName).equals("Integer"))
- System.out.println(propName + "defined with mis-matched types in oxm file");
- }
- for (String propName: aaiResource.getIntFields()) {
- if (nodeType.equalsIgnoreCase("edge-prop-names")) // these properties are in mixed format in DB
- propName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, propName);
- if (propName.equals("sVCINFRA")) propName = "SVC-INFRA";
- if (propName.equals("sVCINFRAREV")) propName = "SVC-INFRA-REV";
- if (!dbMaps.PropertyDataTypeMap.containsKey(propName))
- dbMaps.PropertyDataTypeMap.put(propName, "Integer");
- else if (!dbMaps.PropertyDataTypeMap.get(propName).equals("Integer"))
- System.out.println(propName + "defined with mis-matched types in oxm file");
- }
- for (String propName: aaiResource.getStringFields()) {
- if (nodeType.equalsIgnoreCase("edge-prop-names")) // these properties are in mixed format in DB
- propName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, propName);
- if (propName.equals("sVCINFRA")) propName = "SVC-INFRA";
- if (propName.equals("sVCINFRAREV")) propName = "SVC-INFRA-REV";
- if (!dbMaps.PropertyDataTypeMap.containsKey(propName))
- dbMaps.PropertyDataTypeMap.put(propName, "String");
- else if (!dbMaps.PropertyDataTypeMap.get(propName).equals("String"))
- System.out.println(propName + "defined with mis-matched types in oxm file");
- }
- for (String propName: aaiResource.getStringListFields()) {
- if (nodeType.equalsIgnoreCase("edge-prop-names")) // these properties are in mixed format in DB
- propName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, propName);
- if (propName.equals("sVCINFRA")) propName = "SVC-INFRA";
- if (propName.equals("sVCINFRAREV")) propName = "SVC-INFRA-REV";
- if (!dbMaps.PropertyDataTypeMap.containsKey(propName))
- dbMaps.PropertyDataTypeMap.put(propName, "Set<String>");
- else if (!dbMaps.PropertyDataTypeMap.get(propName).equals("Set<String>"))
- System.out.println(propName + "defined with mis-matched types in oxm file");
- }
- }
-
- }
-
-
- /**
- * Creates the property and node version info map from db maps.
- */
- private void createPropertyAndNodeVersionInfoMapFromDbMaps() {
- DbMaps dbMaps = null;
- String previousApiVersion = null;
- List<Integer> apiIntegerKeySet = new ArrayList<Integer>();
- for ( String vers : dbMapsContainer.keySet()) {
- apiIntegerKeySet.add(Integer.valueOf(vers.substring(1)));
- }
- ArrayList<Integer> apiIntegerVersionsList = (ArrayList<Integer>) asSortedList(apiIntegerKeySet);
- String apiVersion;
- for ( Integer apiIntegerVersion : apiIntegerVersionsList) {
- apiVersion = "v" + apiIntegerVersion;
- System.out.println("apiVersion=" + apiVersion);
- dbMaps = dbMapsContainer.get(apiVersion);
-
- if (previousApiVersion != null) { // when running more than one version
- dbMaps.PropertyVersionInfoMap.putAll(dbMapsContainer.get(previousApiVersion).PropertyVersionInfoMap);
- dbMaps.NodeVersionInfoMap.putAll(dbMapsContainer.get(previousApiVersion).NodeVersionInfoMap);
- }
-
- Iterator<String> nodeTypeIterator = dbMaps.NodeProps.keySet().iterator();
- while( nodeTypeIterator.hasNext() ){
- String nType = nodeTypeIterator.next();
- if (!dbMaps.NodeVersionInfoMap.containsKey(nType)) {
- dbMaps.NodeVersionInfoMap.put(nType, apiVersion);
- }
- Collection <String> nodePropsForType = dbMaps.NodeProps.get(nType);
- Iterator <String> propIter = nodePropsForType.iterator();
- while( propIter.hasNext() ){
- String propName = propIter.next();
- String infoKey = nType + "|" + propName;
- if( ! dbMaps.PropertyVersionInfoMap.containsKey(infoKey) ){
- // We haven't seen this one yet -- add it in.
- dbMaps.PropertyVersionInfoMap.put(infoKey, apiVersion);
- }
- }
- }
- dbMapsContainer.put(apiVersion, dbMaps);
- previousApiVersion = apiVersion;
- }
- }
-
- /**
- * As sorted list.
- *
- * @param <T> the generic type
- * @param c the c
- * @return the list
- */
- private <T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
- List<T> list = new ArrayList<T>(c);
- java.util.Collections.sort(list);
- return list;
- }
-
- /**
- * From comma separated string.
- *
- * @param string the string
- * @return the iterable
- */
- public Iterable<String> fromCommaSeparatedString( String string ) {
- Iterable<String> split = Splitter.on( "," ).omitEmptyStrings().trimResults().split( string );
- return split;
- }
-
- /**
- * Pretty print map.
- *
- * @param map the map
- * @return the string
- */
- public String prettyPrintMap(Multimap<String, String> map) {
- StringBuilder sb = new StringBuilder();
- sb.append('\n');
- for (String key:map.keySet()) {
- sb.append('\t');
- sb.append(key);
- sb.append('=').append('"');
- sb.append(map.get(key));
- sb.append('"');
- sb.append('\n');
- }
- return sb.toString();
- }
-
- /**
- * Pretty print map.
- *
- * @param map the map
- * @return the string
- */
- public String prettyPrintMap(Map<?, String> map) {
- StringBuilder sb = new StringBuilder();
- sb.append('\n');
- for (Object key:map.keySet()) {
- sb.append('\t');
- sb.append(key);
- sb.append('=').append('"');
- sb.append(map.get(key));
- sb.append('"');
- sb.append('\n');
- }
- return sb.toString();
- }
-
-}
diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java
index ff0ae173..b5a80033 100644
--- a/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java
+++ b/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java
@@ -23,6 +23,7 @@ package org.openecomp.aai.introspection;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
@@ -32,13 +33,13 @@ import java.util.Set;
import org.apache.commons.lang.ClassUtils;
import org.eclipse.persistence.exceptions.DynamicException;
-
import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException;
import org.openecomp.aai.logging.ErrorLogHelper;
import org.openecomp.aai.restcore.MediaType;
import org.openecomp.aai.schema.enums.ObjectMetadata;
import org.openecomp.aai.schema.enums.PropertyMetadata;
import org.openecomp.aai.workarounds.NamingExceptions;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.CaseFormat;
@@ -297,6 +298,14 @@ public abstract class Introspector implements Cloneable {
result = this.uniqueProperties;
return result;
}
+
+ public Set<String> getDependentOn() {
+ String dependentOn = this.getMetadata(ObjectMetadata.DEPENDENT_ON);
+ if (dependentOn == null) {
+ dependentOn = "";
+ }
+ return new LinkedHashSet<>(Arrays.asList(dependentOn.split(",")));
+ }
/**
*
* @param name
diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java
index b28e435e..9163f297 100644
--- a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java
+++ b/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java
@@ -37,16 +37,16 @@ import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
-import org.w3c.dom.Document;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
import org.openecomp.aai.exceptions.AAIException;
import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException;
import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException;
import org.openecomp.aai.logging.ErrorLogHelper;
import org.openecomp.aai.restcore.MediaType;
import org.openecomp.aai.workarounds.NamingExceptions;
+import org.w3c.dom.Document;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.CaseFormat;
@@ -85,6 +85,9 @@ public class MoxyLoader extends Loader {
@Override
public Object objectFromName(String name) throws AAIUnknownObjectException {
+ if (name == null) {
+ throw new AAIUnknownObjectException("null name passed in");
+ }
final String sanitizedName = NamingExceptions.getInstance().getObjectName(name);
final String upperCamel;
@@ -186,5 +189,9 @@ public class MoxyLoader extends Loader {
result.remove("EdgePropNames");
return result;
}
+
+ public DynamicJAXBContext getJAXBContext() {
+ return this.jaxbContext;
+ }
}
diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java
index 0cd07808..dec830a9 100644
--- a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java
+++ b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java
@@ -28,18 +28,18 @@ import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
+import org.eclipse.persistence.jaxb.JAXBContextFactory;
import org.eclipse.persistence.jaxb.UnmarshallerProperties;
-
import org.openecomp.aai.db.props.AAIProperties;
import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException;
import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException;
import org.openecomp.aai.logging.ErrorLogHelper;
import org.openecomp.aai.restcore.MediaType;
import org.openecomp.aai.workarounds.NamingExceptions;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.CaseFormat;
-import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class PojoLoader extends Loader {
@@ -73,6 +73,9 @@ public class PojoLoader extends Loader {
@Override
public Object objectFromName(String name) throws AAIUnknownObjectException {
+ if (name == null) {
+ throw new AAIUnknownObjectException("null name passed in");
+ }
final String sanitizedName = NamingExceptions.getInstance().getObjectName(name);
final String upperCamel;
diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java
index 37a10748..43af40ae 100644
--- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java
+++ b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java
@@ -558,7 +558,13 @@ public class ErrorLogHelper {
public static void logException(AAIException e) {
final ErrorObject errorObject = e.getErrorObject();
- MDC.put("severity", errorObject.getSeverity()); //TODO Use LoggingContext.severity(int severity)
+// MDC.put("severity", errorObject.getSeverity()); //TODO Use LoggingContext.severity(int severity)
+ String severityCode = errorObject.getSeverityCode(errorObject.getSeverity());
+ int sevCode = Integer.parseInt(severityCode);
+ if (sevCode > 0 && sevCode <= 3 )
+ {
+ LoggingContext.severity(sevCode);
+ }
final String errorMessage = new StringBuilder()
.append(errorObject.getErrorText())
diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java
index 0198c60e..50822f68 100644
--- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java
+++ b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java
@@ -294,6 +294,29 @@ public class ErrorObject {
}
return prefix + disposition + "." + category + "." + errorCode;
}
+
+ /**
+ * Gets the severity Code. This is also the string
+ * configured in Nagios to alert on
+ *
+ * @return the severity
+ */
+ // Get the numerical value of severity
+ public String getSeverityCode(String severity) {
+ String severityCode = "";
+ switch (severity) {
+ case "WARN":
+ severityCode = "1";
+ break;
+ case "ERROR":
+ severityCode = "2";
+ break;
+ case "FATAL":
+ severityCode = "3";
+ break;
+ }
+ return severityCode;
+ }
/**
* {@inheritDoc}
diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java b/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java
index 1a46bb25..9a2d5914 100644
--- a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java
+++ b/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java
@@ -115,6 +115,10 @@ public class LoggingContext {
public static void requestId(String requestId) {
try {
+ if (requestId.contains(":")) {
+ String[] uuidParts = requestId.split(":");
+ requestId = uuidParts[0];
+ }
MDC.put(LoggingField.REQUEST_ID.toString(), UUID.fromString(requestId).toString());
} catch (IllegalArgumentException e) {
final UUID generatedRequestUuid = UUID.randomUUID();
diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResourceKeys.java b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java
index 8082cd71..8911f944 100644
--- a/aai-core/src/main/java/org/openecomp/aai/domain/model/AAIResourceKeys.java
+++ b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java
@@ -18,23 +18,25 @@
* ============LICENSE_END=========================================================
*/
-package org.openecomp.aai.domain.model;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class AAIResourceKeys {
- private List<AAIResourceKey> aaiResourceKey;
-
- /**
- * Gets the aai resource key.
- *
- * @return the aai resource key
- */
- public List<AAIResourceKey> getAaiResourceKey() {
- if (aaiResourceKey == null) {
- aaiResourceKey = new ArrayList<AAIResourceKey>();
- }
- return aaiResourceKey;
+package org.openecomp.aai.parsers.exceptions;
+
+import org.openecomp.aai.exceptions.AAIException;
+
+public class DoesNotStartWithValidNamespaceException extends AAIException {
+
+ private static final long serialVersionUID = -888876613879411865L;
+
+ public DoesNotStartWithValidNamespaceException(String message) {
+ super("AAI_3000", message);
+ }
+
+ public DoesNotStartWithValidNamespaceException(Throwable cause) {
+ super("AAI_3000",cause);
}
+
+ public DoesNotStartWithValidNamespaceException(String message, Throwable cause) {
+ super("AAI_3000", cause, message);
+ }
+
}
+
diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java b/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java
index 8fc2ea2c..bd9280f4 100644
--- a/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java
+++ b/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java
@@ -31,7 +31,6 @@ import java.util.Optional;
import javax.ws.rs.core.UriBuilder;
import org.apache.tinkerpop.gremlin.structure.Direction;
-
import org.openecomp.aai.exceptions.AAIException;
import org.openecomp.aai.introspection.Introspector;
import org.openecomp.aai.introspection.IntrospectorFactory;
@@ -47,6 +46,7 @@ import org.openecomp.aai.serialization.db.EdgeRule;
import org.openecomp.aai.serialization.db.EdgeRules;
import org.openecomp.aai.serialization.db.EdgeType;
import org.openecomp.aai.workarounds.LegacyURITransformer;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
@@ -115,7 +115,9 @@ public class RelationshipToURI {
} else {
throw new AAIIdentityMapParseException("nothing to parse");
}
- } catch (UnsupportedEncodingException | URISyntaxException e) {
+ } catch (AAIException e) {
+ throw e;
+ } catch (Exception e) {
throw new AAIIdentityMapParseException("Could not parse relationship-list object: " + e.getMessage(), e);
}
diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java
index 8f867172..b145717f 100644
--- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java
+++ b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java
@@ -28,18 +28,18 @@ import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
-import org.springframework.web.util.UriUtils;
-
import org.openecomp.aai.exceptions.AAIException;
import org.openecomp.aai.introspection.Introspector;
import org.openecomp.aai.introspection.Loader;
import org.openecomp.aai.introspection.LoaderFactory;
import org.openecomp.aai.introspection.Version;
import org.openecomp.aai.logging.ErrorLogHelper;
+import org.openecomp.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException;
import org.openecomp.aai.rest.RestTokens;
import org.openecomp.aai.schema.enums.ObjectMetadata;
import org.openecomp.aai.serialization.db.EdgeType;
import org.openecomp.aai.util.AAIConfig;
+import org.springframework.web.util.UriUtils;
/**
@@ -48,7 +48,7 @@ import org.openecomp.aai.util.AAIConfig;
public class URIParser {
private URI uri = null;
-
+
protected Loader loader = null;
protected Loader originalLoader = null;
@@ -74,9 +74,9 @@ public class URIParser {
} catch (AAIException e) {
ErrorLogHelper.logException(e);
}
-
+
//Load the latest version because we need it for cloud region
-
+
this.loader = loader;
}
@@ -175,7 +175,7 @@ public class URIParser {
//first time through, make sure it starts from a namespace
//ignore abstract types
if (!isRelative && !abstractType.equals("true") && !validNamespaces.hasChild(introspector)) {
- throw new AAIException("AAI_3000", uri + " not a valid path. It does not start from a valid namespace");
+ throw new DoesNotStartWithValidNamespaceException( uri + " not a valid path. It does not start from a valid namespace");
}
}
@@ -248,7 +248,7 @@ public class URIParser {
protected URI handleCloudRegion(String action, URI uri) {
return uri;
-
+
}
/**
diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java
index cf011bf6..57a1de57 100644
--- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java
+++ b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java
@@ -71,7 +71,7 @@ public class URIToObject implements Parsable {
* @throws AAIException the AAI exception
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
- public URIToObject(Loader loader, URI uri) throws IllegalArgumentException, AAIException, UnsupportedEncodingException {
+ public URIToObject(Loader loader, URI uri) throws AAIException, UnsupportedEncodingException {
URIParser parser = new URIParser(loader, uri);
this.relatedObjects = new HashMap<>();
@@ -80,7 +80,7 @@ public class URIToObject implements Parsable {
this.loader = parser.getLoader();
this.version = loader.getVersion();
}
- public URIToObject(Loader loader, URI uri, HashMap<String, Introspector> relatedObjects) throws IllegalArgumentException, AAIException, UnsupportedEncodingException {
+ public URIToObject(Loader loader, URI uri, HashMap<String, Introspector> relatedObjects) throws AAIException, UnsupportedEncodingException {
URIParser parser = new URIParser(loader, uri);
this.relatedObjects = relatedObjects;
diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java b/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java
index e5ab80e6..f1f53a4d 100644
--- a/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java
+++ b/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java
@@ -20,29 +20,18 @@
package org.openecomp.aai.restcore;
-import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
-import javax.xml.bind.JAXBException;
-import javax.xml.transform.stream.StreamSource;
-
-import org.eclipse.persistence.dynamic.DynamicEntity;
-import org.eclipse.persistence.jaxb.JAXBUnmarshaller;
-import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
import org.openecomp.aai.db.props.AAIProperties;
import org.openecomp.aai.dbmap.DBConnectionType;
-import org.openecomp.aai.domain.model.AAIResource;
import org.openecomp.aai.exceptions.AAIException;
import org.openecomp.aai.introspection.Introspector;
import org.openecomp.aai.introspection.Loader;
@@ -57,6 +46,8 @@ import org.openecomp.aai.logging.LoggingContext;
import org.openecomp.aai.util.AAIConfig;
import org.openecomp.aai.util.AAIConstants;
import org.openecomp.aai.util.AAITxnLog;
+import org.openecomp.aai.util.FormatDate;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.google.common.base.Joiner;
@@ -149,19 +140,9 @@ public class RESTAPI {
* @return the string
*/
protected String genDate() {
- Date date = new Date();
- DateFormat formatter = null;
- try {
- formatter = new SimpleDateFormat(AAIConfig.get(AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT));
- } catch (AAIException ex) {
- ErrorLogHelper.logException(ex);
- } finally {
- if (formatter == null) {
- formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
- }
- }
-
- return formatter.format(date);
+ FormatDate fd = new FormatDate(AAIConfig.get(AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT, "YYMMdd-HH:mm:ss:SSS"));
+
+ return fd.getDateTime();
}
/**
diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAITxnLog.java b/aai-core/src/main/java/org/openecomp/aai/util/AAITxnLog.java
index 0da84840..3a90e8e9 100644
--- a/aai-core/src/main/java/org/openecomp/aai/util/AAITxnLog.java
+++ b/aai-core/src/main/java/org/openecomp/aai/util/AAITxnLog.java
@@ -21,10 +21,7 @@
package org.openecomp.aai.util;
import java.io.IOException;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
import org.apache.hadoop.hbase.HBaseConfiguration;
@@ -40,11 +37,11 @@ import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.RegexStringComparator;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
-
import org.openecomp.aai.domain.notificationEvent.NotificationEvent;
import org.openecomp.aai.domain.translog.TransactionLogEntries;
import org.openecomp.aai.domain.translog.TransactionLogEntry;
import org.openecomp.aai.exceptions.AAIException;
+
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
@@ -74,9 +71,9 @@ public class AAITxnLog {
config.set(AAIConstants.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM, AAIConfig.get(AAIConstants.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM));
config.set(AAIConstants.HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT, AAIConfig.get(AAIConstants.HBASE_CONFIGURATION_ZOOKEEPER_CLIENTPORT));
- Date date = new Date();
- DateFormat formatter = new SimpleDateFormat(AAIConfig.get(AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT));
- tm = formatter.format(date);
+ FormatDate fd = new FormatDate(AAIConfig.get(AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT, "YYMMdd-HH:mm:ss:SSS"));
+
+ tm = fd.getDateTime();
} catch (AAIException e) {
LOGGER.warn("Missing configuration in AAIConfig: " + e.getMessage());
}
@@ -188,14 +185,9 @@ public class AAITxnLog {
) {
if (tid == null || "".equals(tid)) {
- Date date = new Date();
- DateFormat formatter = null;
- try {
- formatter = new SimpleDateFormat(AAIConfig.get(AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT));
- } catch (Exception e) {
- formatter = new SimpleDateFormat("YYYYMMdd-HH:mm:ss:SSS");
- }
- tm = formatter.format(date);
+ FormatDate fd = new FormatDate(AAIConfig.get(AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT, "YYMMdd-HH:mm:ss:SSS"));
+
+ tm = fd.getDateTime();
tid = tm + "-";
}
String htid = tid;
diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIUtils.java b/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java
index 9c1602d7..d1489992 100644
--- a/aai-core/src/main/java/org/openecomp/aai/util/AAIUtils.java
+++ b/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java
@@ -20,35 +20,27 @@
package org.openecomp.aai.util;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Collections;
-import java.util.Date;
-import java.util.TimeZone;
+import java.time.ZoneId;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
-public class AAIUtils {
+public class FormatDate {
- /**
- * Null check.
- *
- * @param <T> the generic type
- * @param iterable the iterable
- * @return the iterable
- */
- public static <T> Iterable<T> nullCheck(Iterable<T> iterable) {
- return iterable == null ? Collections.<T>emptyList() : iterable;
+ private final String timeZone;
+ private final String pattern;
+ public FormatDate(String pattern) {
+ this.pattern = pattern;
+ this.timeZone = "GMT";
+ }
+ public FormatDate(String pattern, String timeZone) {
+ this.pattern = pattern;
+ this.timeZone = timeZone;
}
- /**
- * Gen date.
- *
- * @return the string
- */
- public static String genDate() {
- Date date = new Date();
- DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
- formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
- return formatter.format(date);
- }
-
+ public String getDateTime() {
+
+ final DateTimeFormatter formatter =
+ DateTimeFormatter.ofPattern(pattern);
+ return formatter.format(ZonedDateTime.now(ZoneId.of(timeZone)));
+ }
}
diff --git a/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java b/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java
index 870ddeca..8840f412 100644
--- a/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java
+++ b/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java
@@ -20,6 +20,10 @@
package org.openecomp.aai.util;
+import java.io.IOException;
+
+import org.apache.commons.io.output.ByteArrayOutputStream;
+
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.DeserializationFeature;
@@ -27,64 +31,8 @@ import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
-import com.google.common.base.CaseFormat;
-import com.google.common.collect.Multimap;
-import com.thinkaurelius.titan.core.TitanVertex;
-import org.apache.commons.io.output.ByteArrayOutputStream;
-import org.eclipse.persistence.dynamic.DynamicEntity;
-import org.eclipse.persistence.dynamic.DynamicType;
-import org.eclipse.persistence.jaxb.MarshallerProperties;
-import org.openecomp.aai.domain.model.AAIResource;
-import org.openecomp.aai.exceptions.AAIException;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Marshaller;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.*;
-import java.util.Map.Entry;
public class PojoUtils {
-
- /**
- * Gets the key value list.
- *
- * @param <T> the generic type
- * @param e the e
- * @param clazz the clazz
- * @return the key value list
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- */
- public <T> List<KeyValueList> getKeyValueList(Entity e, T clazz) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
- List<KeyValueList> kvList = e.getKeyValueList();
- Object value = null;
- Method[] methods = clazz.getClass().getDeclaredMethods();
- String propertyName = "";
-
- for (Method method : methods) {
- if (method.getName().startsWith("get")) {
- propertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(3));
- if (!(method.getReturnType().getName().contains("aai")) || method.getReturnType().getName().contains("java.util.List")) {
- value = method.invoke(clazz);
- KeyValueList kv = new KeyValueList();
- kv.setKey(propertyName);
- if (value != null) {
- kv.setValue(value.toString());
- } else {
- kv.setValue("");
- }
- kvList.add(kv);
- }
- }
- }
- return kvList;
- }
-
/**
* Gets the json from object.
*
@@ -131,608 +79,4 @@ public class PojoUtils {
return baos.toString();
}
-
- /**
- * Gets the json from dynamic object.
- *
- * @param ent the ent
- * @param jaxbContext the jaxb context
- * @param includeRoot the include root
- * @return the json from dynamic object
- * @throws JsonGenerationException the json generation exception
- * @throws JsonMappingException the json mapping exception
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws JAXBException the JAXB exception
- */
- public String getJsonFromDynamicObject(DynamicEntity ent, org.eclipse.persistence.jaxb.JAXBContext jaxbContext, boolean includeRoot) throws JsonGenerationException, JsonMappingException, IOException, JAXBException {
- org.eclipse.persistence.jaxb.JAXBMarshaller marshaller = jaxbContext.createMarshaller();
-
- marshaller.setProperty(org.eclipse.persistence.jaxb.JAXBMarshaller.JAXB_FORMATTED_OUTPUT, false);
- marshaller.setProperty(MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, Boolean.FALSE) ;
- marshaller.setProperty("eclipselink.json.include-root", includeRoot);
- marshaller.setProperty("eclipselink.media-type", "application/json");
- StringWriter writer = new StringWriter();
- marshaller.marshal(ent, writer);
-
- return writer.toString();
- }
-
- /**
- * Gets the xml from object.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @return the xml from object
- * @throws JAXBException the JAXB exception
- */
- public <T> String getXmlFromObject(T clazz) throws JAXBException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- JAXBContext jc = JAXBContext.newInstance(clazz.getClass().getPackage().getName());
-
- Marshaller marshaller = jc.createMarshaller();
- marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
- marshaller.marshal(clazz, baos);
-
- return baos.toString();
- }
-
- /**
- * Gets the lookup key.
- *
- * @param baseKey the base key
- * @param lookupHash the lookup hash
- * @param keyProps the key props
- * @return the lookup key
- */
- public String getLookupKey (String baseKey, HashMap<String,Object> lookupHash, Collection<String> keyProps) {
- int baseKeyLen = baseKey.length();
- StringBuffer newKey = new StringBuffer();
- if (baseKeyLen > 0) {
- newKey.append(baseKey);
- }
-
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- String keyProp = keyPropI.next();
- if (baseKeyLen > 0) {
- newKey.append("&");
- }
- newKey.append(keyProp + "=" + lookupHash.get(keyProp));
- }
- return newKey.toString();
- }
-
- /**
- * Gets the lookup keys.
- *
- * @param lookupHashes the lookup hashes
- * @param _dbRulesNodeKeyProps the db rules node key props
- * @return the lookup keys
- */
- public String getLookupKeys (LinkedHashMap<String,HashMap<String,Object>> lookupHashes, Multimap<String, String> _dbRulesNodeKeyProps) {
- Iterator<String> it = lookupHashes.keySet().iterator();
- String lookupKeys = "";
- while (it.hasNext()) {
- String objectType = (String)it.next();
- HashMap<String,Object> lookupHash = lookupHashes.get(objectType);
-
- Collection<String> keyProps = _dbRulesNodeKeyProps.get(objectType);
- Iterator <String> keyPropI = keyProps.iterator();
- while( keyPropI.hasNext() ){
- lookupKeys += lookupHash.get(keyPropI.next());
- }
- }
- return lookupKeys;
- }
-
- /**
- * Gets the example object.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @param singleton the singleton
- * @return the example object
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
- * @throws AAIException the AAI exception
- */
- public <T> void getExampleObject(T clazz, boolean singleton) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, AAIException {
- Method[] methods = clazz.getClass().getDeclaredMethods();
- String dnHypPropertyName = "";
- String upCamPropertyName = "";
- Random rand = new Random();
- int randInt = rand.nextInt(10000000);
-
- for (Method method : methods) {
- boolean go = false;
- if (method.getName().startsWith("get")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(3));
- upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(3));
- go = true;
- } else if (method.getName().startsWith("is")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(2));
- upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(2));
- go = true;
- }
- // don't return resource-version on a singleton
- if (singleton && dnHypPropertyName.equals("resource-version")) {
- go = false;
- }
- if (go) {
- String retType = method.getReturnType().getName();
- if (!retType.contains("aai") && !retType.contains("java.util.List")) {
- // get the setter
- Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
-
- if (retType.contains("String")) {
- String val = "example-" + dnHypPropertyName + "-val-" + randInt;
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("long")) {
- Integer foo = rand.nextInt(100000);
- meth.invoke(clazz, foo.longValue());
- } else if (retType.toLowerCase().contains("int")) {
- meth.invoke(clazz, rand.nextInt(100000));
- } else if (retType.toLowerCase().contains("short")) {
- Integer randShort = rand.nextInt(10000);
- meth.invoke(clazz, randShort.shortValue());
- } else if (retType.toLowerCase().contains("boolean")) {
- meth.invoke(clazz, true);
- }
- }
- }
- }
- }
-
-
- /**
- * Gets the aai object from vertex.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @param vert the vert
- * @param _propertyDataTypeMap the property data type map
- * @return the aai object from vertex
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
- * @throws AAIException the AAI exception
- */
- public <T> void getAaiObjectFromVertex(T clazz, TitanVertex vert, Map<String, String> _propertyDataTypeMap) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, AAIException {
- Method[] methods = clazz.getClass().getDeclaredMethods();
- String dnHypPropertyName = "";
- String upCamPropertyName = "";
- for (Method method : methods) {
- boolean go = false;
- if (method.getName().startsWith("get")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(3));
- upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(3));
- go = true;
- } else if (method.getName().startsWith("is")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(2));
- upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(2));
- go = true;
- }
- if (go) {
- String retType = method.getReturnType().getName();
- if (!retType.contains("aai") && !retType.contains("java.util.List")) {
- // get the setter
- Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
-
- if (retType.contains("String")) {
- String val = (String)vert.<String>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("long")) {
- String titanType = _propertyDataTypeMap.get(dnHypPropertyName);
-
- Long val = null;
- // we have a case where the type in titan is "Integer" but in the POJO it's Long or long
- if (titanType.toLowerCase().contains("int")) {
- Integer intVal = (Integer)vert.<Integer>property(dnHypPropertyName).orElse(null);
- if (intVal != null) {
- val = intVal.longValue();
- }
- } else {
- val = (Long)vert.<Long>property(dnHypPropertyName).orElse(null);
- }
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("int")) {
- Integer val = (Integer)vert.<Integer>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("short")) {
- Short val = (Short)vert.<Short>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("boolean")) {
- Boolean val = (Boolean)vert.<Boolean>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- }
- }
- }
- }
- }
-
- /**
- * Gets the topology object.
- *
- * @param <T> the generic type
- * @param clazz the clazz
- * @param _dbRulesNodeNameProps the db rules node name props
- * @param _dbRulesNodeKeyProps the db rules node key props
- * @param vert the vert
- * @return the topology object
- * @throws IllegalAccessException the illegal access exception
- * @throws IllegalArgumentException the illegal argument exception
- * @throws InvocationTargetException the invocation target exception
- * @throws NoSuchMethodException the no such method exception
- * @throws SecurityException the security exception
- * @throws AAIException the AAI exception
- */
- public <T> void getTopologyObject(T clazz, Multimap<String, String> _dbRulesNodeNameProps, Multimap<String, String> _dbRulesNodeKeyProps, TitanVertex vert) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, AAIException {
- Method[] methods = clazz.getClass().getDeclaredMethods();
- String dnHypPropertyName = "";
-// Object value = null;
- List<String> includeProps = new ArrayList<String>();
-
- if ("false".equals(AAIConfig.get("aai.notification.topology.allAttrs", "false"))) {
- for (Method method : methods) {
- if (method.getName().startsWith("is")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(2));
- String upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(2));
- String retType = method.getReturnType().getName();
- if (retType.equals("java.lang.Boolean")) {
- // get the setter
- Method setterMeth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
- setterMeth.invoke(clazz, (Boolean)null);
- }
- }
- }
- String dnHypClassName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,clazz.getClass().getSimpleName());
- Collection<String> keepProps = _dbRulesNodeNameProps.get(dnHypClassName);
- Iterator <String> keepPropI = keepProps.iterator();
- while( keepPropI.hasNext() ){
- includeProps.add(keepPropI.next());
- }
- Collection<String> keepProps2 = _dbRulesNodeKeyProps.get(dnHypClassName);
- Iterator <String> keepPropI2 = keepProps2.iterator();
- while( keepPropI2.hasNext() ){
- includeProps.add(keepPropI2.next());
- }
- }
-
- for (Method method : methods) {
- if (method.getName().startsWith("get")) {
- dnHypPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,method.getName().substring(3));
- if (includeProps.size() > 0) {
- if (!includeProps.contains(dnHypPropertyName)) {
- continue;
- }
- }
- String upCamPropertyName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_CAMEL,method.getName().substring(3));
- String retType = method.getReturnType().getName();
- if (!retType.contains("aai") && !retType.contains("java.util.List")) {
- // get the setter
- Method meth = clazz.getClass().getMethod("set" + upCamPropertyName, method.getReturnType());
-
- if (retType.contains("String")) {
- String val = (String)vert.<String>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("long")) {
- Long val = (Long)vert.<Long>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("int")) {
- Integer val = (Integer)vert.<Integer>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- } else if (retType.toLowerCase().contains("short")) {
- Short val = (Short)vert.<Short>property(dnHypPropertyName).orElse(null);
- if (val != null) {
- meth.invoke(clazz, val);
- }
- }
- }
- }
- }
- }
-
- /**
- * Gets the dynamic topology object.
- *
- * @param aaiRes the aai res
- * @param meObjectType the me object type
- * @param _dbRulesNodeNameProps the db rules node name props
- * @param _dbRulesNodeKeyProps the db rules node key props
- * @param _propertyDataTypeMap the property data type map
- * @param vert the vert
- * @return the dynamic topology object
- * @throws AAIException the AAI exception
- */
- public DynamicEntity getDynamicTopologyObject(AAIResource aaiRes, DynamicType meObjectType, Multimap<String, String> _dbRulesNodeNameProps,
- Multimap<String, String> _dbRulesNodeKeyProps, Map<String, String> _propertyDataTypeMap, TitanVertex vert) throws AAIException {
-
- DynamicEntity meObject = meObjectType.newDynamicEntity();
-
- List<String> includeProps = new ArrayList<String>();
-
- if ("false".equals(AAIConfig.get("aai.notification.topology.allAttrs", "false"))) {
- String dnHypClassName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,meObjectType.getJavaClass().getSimpleName());
- Collection<String> keepProps = _dbRulesNodeNameProps.get(dnHypClassName);
- Iterator <String> keepPropI = keepProps.iterator();
- while( keepPropI.hasNext() ){
- includeProps.add(keepPropI.next());
- }
- Collection<String> keepProps2 = _dbRulesNodeKeyProps.get(dnHypClassName);
- Iterator <String> keepPropI2 = keepProps2.iterator();
- while( keepPropI2.hasNext() ) {
- includeProps.add(keepPropI2.next());
- }
- }
-
-
-
- for (String attrName : aaiRes.getStringFields()) {
- if (includeProps.contains(attrName)) {
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), vert.<String>property(attrName).orElse(null));
- }
- }
- // the attrName might need to be converted to camel case!!!
- for (String attrName : aaiRes.getLongFields()) {
- if (includeProps.contains(attrName)) {
- String titanType = _propertyDataTypeMap.get(attrName);
-
- Long val = null;
- // we have a case where the type in titan is "Integer" but in the POJO it's Long or long
- if (titanType.toLowerCase().contains("int")) {
- Integer intVal = (Integer)vert.<Integer>property(attrName).orElse(null);
- if (intVal != null) {
- val = intVal.longValue();
- }
- } else {
- val = (Long)vert.<Long>property(attrName).orElse(null);
- }
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
-
- for (String attrName : aaiRes.getIntFields()) {
- if (includeProps.contains(attrName)) {
- Integer val = (Integer)vert.<Integer>property(attrName).orElse(null);
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
-
- for (String attrName : aaiRes.getShortFields()) {
- if (includeProps.contains(attrName)) {
- String titanType = _propertyDataTypeMap.get(attrName);
-
- Short val = null;
- // we have a case where the type in titan is "Integer" but in the POJO it's Long or long
- if (titanType.toLowerCase().contains("int")) {
- Integer intVal = (Integer)vert.<Integer>property(attrName).orElse(null);
- if (intVal != null) {
- val = intVal.shortValue();
- }
- } else {
- val = (Short)vert.<Short>property(attrName).orElse(null);
- }
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
-
- for (String attrName : aaiRes.getBooleanFields()) {
- if (includeProps.contains(attrName)) {
- Boolean val = (Boolean)vert.<Boolean>property(attrName).orElse(null);
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
- return meObject;
- }
-
- /**
- * Gets the aai dynamic object from vertex.
- *
- * @param aaiRes the aai res
- * @param meObject the me object
- * @param vert the vert
- * @param _propertyDataTypeMap the property data type map
- * @return the aai dynamic object from vertex
- */
- public void getAaiDynamicObjectFromVertex(AAIResource aaiRes, DynamicEntity meObject, TitanVertex vert,
- Map<String, String> _propertyDataTypeMap) {
- getAaiDynamicObjectFromVertex(aaiRes, meObject, vert, _propertyDataTypeMap, null);
- }
-
- /**
- * Gets the aai dynamic object from vertex.
- *
- * @param aaiRes the aai res
- * @param meObject the me object
- * @param vert the vert
- * @param _propertyDataTypeMap the property data type map
- * @param propertyOverRideHash the property over ride hash
- * @return the aai dynamic object from vertex
- */
- @SuppressWarnings("unchecked")
- public void getAaiDynamicObjectFromVertex(AAIResource aaiRes, DynamicEntity meObject, TitanVertex vert,
- Map<String, String> _propertyDataTypeMap, HashMap<String, Object> propertyOverRideHash) {
-
- for (String attrName : aaiRes.getStringFields()) {
- if (propertyOverRideHash == null || (propertyOverRideHash != null && propertyOverRideHash.containsKey(attrName))) {
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), vert.<String>property(dbAliasWorkaround(attrName)).orElse(null));
- }
- }
-
- for (String attrName : aaiRes.getStringListFields()) {
- if (propertyOverRideHash == null || (propertyOverRideHash != null && propertyOverRideHash.containsKey(attrName))) {
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), vert.<ArrayList<String>>property(attrName).orElse(null));
- }
- }
-
- // the attrName might need to be converted to camel case!!!
- for (String attrName : aaiRes.getLongFields()) {
- String titanType = _propertyDataTypeMap.get(attrName);
- Long val = null;
- // we have a case where the type in titan is "Integer" but in the POJO it's Long or long
- if (titanType.toLowerCase().contains("int")) {
- Object vertexVal = vert.property(attrName).orElse(null);
- if (vertexVal != null) {
- if (vertexVal instanceof Integer) {
- val = ((Integer)vertexVal).longValue();
-
- } else {
- val = (Long)vert.<Long>property(attrName).orElse(null);
- }
- }
- } else {
- val = (Long)vert.<Long>property(attrName).orElse(null);
- }
- if (val != null) {
- if (propertyOverRideHash == null || (propertyOverRideHash != null && propertyOverRideHash.containsKey(attrName))) {
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
- }
-
- for (String attrName : aaiRes.getIntFields()) {
- Integer val = (Integer)vert.<Integer>property(attrName).orElse(null);
- if (val != null) {
- if (propertyOverRideHash == null || (propertyOverRideHash != null && propertyOverRideHash.containsKey(attrName))) {
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
- }
-
- for (String attrName : aaiRes.getShortFields()) {
- String titanType = _propertyDataTypeMap.get(attrName);
- Short val = null;
- // we have a case where the type in titan is "Integer" but in the POJO it's Long or long
- if (titanType.toLowerCase().contains("int")) {
- Integer intVal = (Integer)vert.<Integer>property(attrName).orElse(null);
- if (intVal != null) {
- val = intVal.shortValue();
- }
- } else {
- val = (Short)vert.<Short>property(attrName).orElse(null);
- }
- if (val != null) {
- if (propertyOverRideHash == null || (propertyOverRideHash != null && propertyOverRideHash.containsKey(attrName))) {
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
- }
-
- for (String attrName : aaiRes.getBooleanFields()) {
- Boolean val = (Boolean)vert.<Boolean>property(attrName).orElse(null);
- // This is not ideal, but moxy isn't marshalling these attributes.
- // TODO: Figure out how to see the default-value from the OXM at startup (or at runtime).
- String dnHypClassName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,aaiRes.getSimpleName());
- if (val == null && AAIConfig.getDefaultBools().containsKey(dnHypClassName)) {
- if (AAIConfig.getDefaultBools().get(dnHypClassName).contains(attrName)) {
- val = false;
- }
- }
- if (val != null) {
- if (propertyOverRideHash == null || (propertyOverRideHash != null && propertyOverRideHash.containsKey(attrName))) {
- meObject.set((CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,attrName)), val);
- }
- }
- }
-
- }
-
- private String dbAliasWorkaround(String propName) {
- final String modelInvariantIdLocal = "model-invariant-id-local";
- final String modelVersionIdLocal = "model-version-id-local";
- final String modelInvariantId = "model-invariant-id";
- final String modelVersionId = "model-version-id";
-
- if (propName.equals(modelInvariantId)) {
- return modelInvariantIdLocal;
- }
- if (propName.equals(modelVersionId)) {
- return modelVersionIdLocal;
- }
-
- return propName;
-
- }
-
- /**
- * Gets the dynamic example object.
- *
- * @param childObject the child object
- * @param aaiRes the aai res
- * @param singleton the singleton
- * @return the dynamic example object
- */
- public void getDynamicExampleObject(DynamicEntity childObject, AAIResource aaiRes, boolean singleton) {
- // TODO Auto-generated method stub
-
- Random rand = new Random();
- Integer randInt = rand.nextInt(100000);
- long range = 100000000L;
- long randLong = (long)(rand.nextDouble()*range);
- Integer randShrt = rand.nextInt(20000);
- short randShort = randShrt.shortValue();
-
- for (String dnHypAttrName : aaiRes.getStringFields()) {
-
- if (singleton && ("resource-version").equals(dnHypAttrName)) {
- continue;
- }
-
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, "example-" + dnHypAttrName + "-val-" + randInt);
-
- }
-
- for (String dnHypAttrName : aaiRes.getStringListFields()) {
- ArrayList<String> exampleList = new ArrayList<String>();
- exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 1);
- exampleList.add("example-" + dnHypAttrName + "-val-" + randInt + "-" + 2);
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, exampleList);
- }
-
- // the attrName might need to be converted to camel case!!!
- for (String dnHypAttrName : aaiRes.getLongFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, randLong);
- }
-
- for (String dnHypAttrName : aaiRes.getIntFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, randInt);
- }
-
- for (String dnHypAttrName : aaiRes.getShortFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, randShort);
- }
-
- for (String dnHypAttrName : aaiRes.getBooleanFields()) {
- String dnCamAttrName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL,dnHypAttrName);
- childObject.set(dnCamAttrName, Boolean.TRUE);
- }
- }
}
diff --git a/aai-core/src/test/resources/bundleconfig-local/etc/auth/aai_policy.json b/aai-core/src/test/resources/bundleconfig-local/etc/auth/aai_policy.json
new file mode 100644
index 00000000..9706ce90
--- /dev/null
+++ b/aai-core/src/test/resources/bundleconfig-local/etc/auth/aai_policy.json
@@ -0,0 +1,37 @@
+{
+ "roles": [{
+ "name": "testRole",
+ "functions": [{
+ "name": "testFunction",
+ "methods": [{
+ "name": "GET"
+ }, {
+ "name": "DELETE"
+ }, {
+ "name": "PUT"
+ }
+ ]
+ }
+ ],
+ "users": [{
+ "username": "testUser"
+ }
+ ]
+ }, {
+ "name": "testBasicAuth",
+ "functions": [{
+ "name": "testBasicAuthFuncyion",
+ "methods": [{
+ "name": "GET"
+ }
+ ]
+ }
+ ],
+ "users": [{
+ "user": "testBasicAuthUser",
+ "pass": "OBF:1ytc1vu91v2p1rxf1mqh1v8s1z0d1msn1san1mqf1z0h1v9u1msl1rvf1v1p1vv11yta"
+ }
+ ]
+ }
+ ]
+} \ No newline at end of file