diff options
author | Venkata Harish K Kajur <vk250x@att.com> | 2017-06-07 23:53:59 -0400 |
---|---|---|
committer | Venkata Harish K Kajur <vk250x@att.com> | 2017-06-07 23:56:55 -0400 |
commit | 8ed8d2f6cacc55263470af007d7ecec23666bbfc (patch) | |
tree | 99387e19e54acb770ec2c798b75fb0e396354f63 /aai-resources/src | |
parent | 57c589b4026f09daf02cf6d3d73b8ce672de1b0b (diff) |
[AAI-ONAP] Get latest changes from develop sync
Change-Id: I2bf80b4af4e3db84cf61fd98bc0ad6efb5e0551b
Signed-off-by: Venkata Harish K Kajur <vk250x@att.com>
Diffstat (limited to 'aai-resources/src')
25 files changed, 87 insertions, 2636 deletions
diff --git a/aai-resources/src/main/java/org/openecomp/aai/dbgen/AddResourceVersionProp.java b/aai-resources/src/main/java/org/openecomp/aai/dbgen/AddResourceVersionProp.java deleted file mode 100644 index 15c9b1e..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/dbgen/AddResourceVersionProp.java +++ /dev/null @@ -1,126 +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.util.Iterator; -import java.util.Properties; - -import org.openecomp.aai.dbmap.AAIGraph; -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 com.att.eelf.configuration.Configuration; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import org.apache.tinkerpop.gremlin.structure.Vertex; - - -public class AddResourceVersionProp { - - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_SCHEMA_MOD_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - - // NOTE -- This is a one-time migration for adding the new property "resource-version" to ALL of our nodes. - // Also -- since it's a one-time thing, we just re-use AAI_SCHEMA_MOD_LOG4J_PROPS - - TitanGraph graph = null; - - System.out.println(">>> WARNING: this script affects all nodes in the database. <<<< " ); - System.out.println(">>> Processing will begin in 5 seconds (unless interrupted). <<<"); - try { - // Give them a chance to back out of this - Thread.sleep(5000); - } catch ( java.lang.InterruptedException ie) { - System.out.println( " AddResourceVersionProp script has been aborted. "); - System.exit(1); - } - - try { - AAIConfig.init(); - ErrorLogHelper.loadProperties(); - - System.out.println(" ---- NOTE --- about to open graph (takes a little while)\n"); - - graph = AAIGraph.getInstance().getGraph(); - if( graph == null ){ - String emsg = "Not able to get a graph object in AddResourceVersionProp.java\n"; - System.out.println( emsg ); - System.exit(1); - } - - - // For each node in the db -- update the "resource-version" and the last mod timestamp. - Iterable<TitanVertex> verts = null; - verts= graph.query().vertices(); - Iterator<TitanVertex> it = verts.iterator(); - int vtxCount = 0; - long unixTimeNow = System.currentTimeMillis() / 1000L; - String timeNowInSec = "" + unixTimeNow; - - while( it.hasNext() ){ - vtxCount++; - TitanVertex tmpVtx = (TitanVertex)it.next(); - tmpVtx.property( "aai-last-mod-ts", timeNowInSec ); - tmpVtx.property( "resource-version", timeNowInSec ); - } - - System.out.println("Updated data for " + vtxCount + " vertexes. Now call graph.tx().commit(). "); - graph.tx().commit(); - - } - catch (AAIException e) { - System.out.print("Threw a AAIException: \n"); - System.out.println(e.getErrorObject().toString()); - } - catch (Exception ex) { - System.out.print("Threw a regular Exception:\n"); - System.out.println(ex.getMessage()); - } - finally { - if( graph != null ){ - // Any changes that worked correctly should have already done their commits. - graph.tx().rollback(); - graph.close(); - } - - } - - - System.exit(0); - - }// End of main() - - -} - - diff --git a/aai-resources/src/main/java/org/openecomp/aai/dbgen/ChangePropertyCardinality.java b/aai-resources/src/main/java/org/openecomp/aai/dbgen/ChangePropertyCardinality.java deleted file mode 100644 index f92cfbc..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/dbgen/ChangePropertyCardinality.java +++ /dev/null @@ -1,307 +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.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.Properties; -import java.util.TimeZone; - -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.logging.ErrorLogHelper; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import com.att.eelf.configuration.Configuration; -import com.thinkaurelius.titan.core.Cardinality; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import org.apache.tinkerpop.gremlin.structure.Vertex; - - -public class ChangePropertyCardinality { - - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - //public static void ChangePropertyCardinality( String[] args ) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_SCHEMA_MOD_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - - // NOTE -- We're just working with properties that are used for NODES - String propName = ""; - String targetDataType = "String"; - String targetCardinality = "SET"; - String preserveDataFlag = "false"; - boolean preserveData = false; - - - String usageString = "Usage: ChangePropertyCardinality propertyName targetDataType targetCardinality preserveDataFlag \n"; - if( args.length != 4 ){ - String emsg = "Four Parameters are required. \n" + usageString; - System.out.println( emsg ); - System.exit(1); - } - else { - propName = args[0]; - targetDataType = args[1]; - targetCardinality = args[2]; - preserveDataFlag = args[3]; - } - - if( propName.equals("") ){ - String emsg = "Bad parameter - propertyName cannot be empty. \n" + usageString; - System.out.println( emsg ); - System.exit(1); - } - else if( !targetDataType.equals("String") ){ - // && !targetDataType.equals("Integer") - // && !targetDataType.equals("Long") - // && !targetDataType.equals("Boolean") ){ - // String emsg = "Unsupported targetDataType. We only support String, Integer, Long or Boolean for now.\n" + usageString; - String emsg = "Unsupported targetDataType. We only support String for now.\n" + usageString; - System.out.println( emsg ); - System.exit(1); - } - else if( !targetCardinality.equals("SET") ){ - // && !targetCardinality.equals("LIST") - // && !targetCardinality.equals("SINGLE") ){ - String emsg = "Unsupported targetCardinality. We only support SET for now.\n" + usageString; - System.out.println( emsg ); - System.exit(1); - } - else { - if( preserveDataFlag.equals("true") ){ - preserveData = true; - String emsg = "Unsupported preserveDataFlag. For now, we only support: 'false'.\n" + usageString; - System.out.println( emsg ); - System.exit(1); - } - else if (preserveDataFlag.equals("false") ){ - preserveData = false; - } - else { - String emsg = "Unsupported preserveDataFlag. We only support: 'true' or 'false'.\n" + usageString; - System.out.println( emsg ); - System.exit(1); - } - } - - String targetDataTypeStr = ""; - if( targetCardinality.equals("SINGLE") ){ - targetDataTypeStr = targetDataType; - } - else if( targetCardinality.equals("SET") ){ - targetDataTypeStr = "Set<" + targetDataType + ">"; - } - else if( targetCardinality.equals("LIST") ){ - targetDataTypeStr = "List<" + targetDataType + ">"; - } - - Class dType = null; - if(targetDataType.equals("String")){ dType = String.class; } - else if(targetDataType.equals("Integer")){ dType = Integer.class; } - else if(targetDataType.equals("Boolean")){ dType = Boolean.class; } - else if(targetDataType.equals("Character")){ dType = Character.class; } - else if(targetDataType.equals("Long")){ dType = Long.class; } - else if(targetDataType.equals("Float")){ dType = Float.class; } - else if(targetDataType.equals("Double")){ dType = Double.class; } - - System.out.println("\n>> WARNING/NOTE - If the passed cardinality is not in synch with what is in the ex5.json file, "); - System.out.println("\n>> then this will cause problems when new environments are created."); - - // Give a big warning if the DbMaps.PropertyDataTypeMap value does not agree with what we're doing - DbMaps dbMaps = null; - try { - dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)); - } - catch( AAIException ae ){ - String emsg = "Could not instantiate a copy of dbMaps. "; - System.out.println( emsg ); - System.exit(1); - } - - String warningMsg = ""; - if( !dbMaps.PropertyDataTypeMap.containsKey(propName) ){ - String emsg = "Property Name = [" + propName + "] not found in PropertyDataTypeMap. "; - System.out.println( emsg ); - System.exit(1); - } - else { - String currentDataType = dbMaps.PropertyDataTypeMap.get(propName); - if( !currentDataType.equals(targetDataTypeStr) ){ - warningMsg = "TargetDataType [" + targetDataTypeStr + "] does not match what is in DbMaps (" + currentDataType + ")."; - } - } - - if( !warningMsg.equals("") ){ - System.out.println("\n>>> WARNING <<<< " ); - System.out.println(">>> " + warningMsg + " <<<"); - System.out.println(">>> !!! WARNING -- this change may be overwritten in some environments if <<<"); - System.out.println(">>> !!! entries are out of synch with what is done with this script. <<<"); - System.out.println(">>> WARNING <<<< " ); - } - - System.out.println(">>> Processing will begin in 5 seconds (unless interrupted). <<<"); - try { - // Give them a chance to back out of this - Thread.sleep(5000); - } catch ( java.lang.InterruptedException ie) { - System.out.println( " DB Schema Update has been aborted. "); - System.exit(1); - } - - TitanManagement graphMgt = null; - TitanGraph graph = null; - try { - AAIConfig.init(); - ErrorLogHelper.loadProperties(); - - System.out.println(" ---- NOTE --- about to open graph (takes a little while)\n"); - - graph = AAIGraph.getInstance().getGraph(); - if( graph == null ){ - String emsg = "Not able to get a graph object in ChangePropertyCardinality.java\n"; - System.out.println( emsg ); - System.exit(1); - } - - // Make sure this property is in the DB. - graphMgt = graph.openManagement(); - if( graphMgt == null ){ - String emsg = "Not able to get a graph Management object in ChangePropertyCardinality.java\n"; - System.out.println( emsg ); - System.exit(1); - } - - PropertyKey origPropKey = graphMgt.getPropertyKey(propName); - if( origPropKey == null ){ - // The old one wasn't there, so there's nothing to do - String emsg = "The propName = [" + propName + "] is not defined in our graph. "; - System.out.println( emsg ); - System.exit(1); - } - - if( origPropKey.cardinality().equals(Cardinality.valueOf(targetCardinality)) ){ - // The existing one already has cardinality of what they're asking for. - String emsg = "The propName = [" + propName + "] already has Cardinality of [" + targetCardinality + "]. "; - System.out.println( emsg ); - System.exit(0); - } - - // Rename this property to a backup name (old name with "retired_" appended plus a dateStr) - SimpleDateFormat d = new SimpleDateFormat("MMddHHmm"); - d.setTimeZone(TimeZone.getTimeZone("GMT")); - String dteStr = d.format(new Date()).toString(); - String retiredName = propName + "-" + dteStr + "-RETIRED"; - graphMgt.changeName( origPropKey, retiredName ); - - // Create a new property using the original property name and the targetDataType - PropertyKey freshPropKey = graphMgt.makePropertyKey(propName).dataType(dType).cardinality(Cardinality.valueOf(targetCardinality)).make(); - - System.out.println("Committing schema changes with graphMgt.tx().commit()"); - graphMgt.commit(); - graph.tx().commit(); - graph.close(); - - - // Get A new graph object - System.out.println(" ---- NOTE --- about to open a second graph object (takes a little while)\n"); - - graph = AAIGraph.getInstance().getGraph(); - if( graph == null ){ - String emsg = "Not able to get a graph object in SchemaMod.java\n"; - System.out.println( emsg ); - System.exit(1); - } - - // For each node that has this property, update the new from the old and then remove the - // old property from that node - // ---- NOTE ---- We're not preserving data at this point - Iterable<TitanVertex> verts = null; - verts= graph.query().has(retiredName).vertices(); - Iterator<TitanVertex> it = verts.iterator(); - int vtxCount = 0; - while( it.hasNext() ){ - vtxCount++; - TitanVertex tmpVtx = (TitanVertex)it.next(); - String tmpVid = tmpVtx.id().toString(); - - Object origVal = tmpVtx.property(retiredName).orElse(null); - if( preserveData ){ - tmpVtx.property(propName,origVal); - System.out.println("INFO -- just did the add of the freshPropertyKey and updated it with the orig value (" + - origVal.toString() + ")"); - } - else { - // existing nodes just won't have this property anymore - // - } - tmpVtx.property(retiredName).remove(); - System.out.println("INFO -- just did the remove of the " + retiredName + " from this vertex. (vid=" + tmpVid + ")"); - } - - System.out.println("Updated data for " + vtxCount + " vertexes. Now call graph.tx().commit(). "); - graph.tx().commit(); - - } - catch (AAIException e) { - System.out.print("Threw a AAIException: \n"); - System.out.println(e.getErrorObject().toString()); - } - catch (Exception ex) { - System.out.print("Threw a regular Exception:\n"); - System.out.println(ex.getMessage()); - } - finally { - if( graphMgt != null && graphMgt.isOpen() ){ - // Any changes that worked correctly should have already done their commits. - graphMgt.rollback(); - } - if( graph != null ){ - // Any changes that worked correctly should have already done their commits. - graph.tx().rollback(); - graph.close(); - } - - } - - System.exit(0); - - }// End of main() - - -} - - diff --git a/aai-resources/src/main/java/org/openecomp/aai/dbgen/DataSnapshot.java b/aai-resources/src/main/java/org/openecomp/aai/dbgen/DataSnapshot.java index d03a5e3..2f1ef33 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/dbgen/DataSnapshot.java +++ b/aai-resources/src/main/java/org/openecomp/aai/dbgen/DataSnapshot.java @@ -25,20 +25,18 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.Iterator; import java.util.Properties; -import java.util.TimeZone; import org.apache.tinkerpop.gremlin.structure.io.IoCore; import org.apache.tinkerpop.gremlin.structure.io.graphson.LegacyGraphSONReader; - import org.openecomp.aai.dbmap.AAIGraph; 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.FormatDate; + import com.att.eelf.configuration.Configuration; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; @@ -100,9 +98,8 @@ public class DataSnapshot { // ------------------------------------------ // They just want to take a snapshot. // ------------------------------------------ - 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 newSnapshotOutFname = targetDir + AAIConstants.AAI_FILESEP + "dataSnapshot.graphSON." + dteStr; graph.io(IoCore.graphson()).writeGraph(newSnapshotOutFname); diff --git a/aai-resources/src/main/java/org/openecomp/aai/dbgen/SchemaMod.java b/aai-resources/src/main/java/org/openecomp/aai/dbgen/SchemaMod.java deleted file mode 100644 index 9cc6cf3..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/dbgen/SchemaMod.java +++ /dev/null @@ -1,441 +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.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.Properties; -import java.util.TimeZone; -import java.util.UUID; - -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.slf4j.MDC; - -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.logging.ErrorLogHelper; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.util.UniquePropertyCheck; -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.Cardinality; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanEdge; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanVertex; -import com.thinkaurelius.titan.core.schema.TitanManagement; - -public class SchemaMod { - - private static final String FROMAPPID = "AAI-UTILS"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static final String COMPONENT = "SchemaMod"; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - SchemaMod.execute(args); - System.exit(0); - - }// End of main() - - /** - * Execute. - * - * @param args the args - */ - public static void execute(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_SCHEMA_MOD_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - - EELFLogger logger = EELFManager.getInstance().getLogger(UniquePropertyCheck.class.getSimpleName()); - MDC.put("logFilenameAppender", SchemaMod.class.getSimpleName()); - - // NOTE -- We're just working with properties that are used for NODES - // for now. - - TitanGraph graph = null; - TitanManagement graphMgt = null; - - Boolean preserveData = true; - String propName = ""; - String targetDataType = ""; - String targetIndexInfo = ""; - String preserveDataFlag = ""; - - String usageString = "Usage: SchemaMod propertyName targetDataType targetIndexInfo preserveDataFlag \n"; - if (args.length != 4) { - String emsg = "Four Parameters are required. \n" + usageString; - logAndPrint(logger, emsg); - System.exit(1); - } else { - propName = args[0]; - targetDataType = args[1]; - targetIndexInfo = args[2]; - preserveDataFlag = args[3]; - } - - if (propName.equals("")) { - String emsg = "Bad parameter - propertyName cannot be empty. \n" + usageString; - logAndPrint(logger, emsg); - System.exit(1); - } else if (!targetDataType.equals("String") && !targetDataType.equals("Set<String>") - && !targetDataType.equals("Integer") && !targetDataType.equals("Long") - && !targetDataType.equals("Boolean")) { - String emsg = "Unsupported targetDataType. We only support String, Set<String>, Integer, Long or Boolean for now.\n" - + usageString; - logAndPrint(logger, emsg); - System.exit(1); - } else if (!targetIndexInfo.equals("uniqueIndex") && !targetIndexInfo.equals("index") - && !targetIndexInfo.equals("noIndex")) { - String emsg = "Unsupported IndexInfo. We only support: 'uniqueIndex', 'index' or 'noIndex'.\n" - + usageString; - logAndPrint(logger, emsg); - System.exit(1); - } else { - if (preserveDataFlag.equals("true")) { - preserveData = true; - } else if (preserveDataFlag.equals("false")) { - preserveData = false; - } else { - String emsg = "Unsupported preserveDataFlag. We only support: 'true' or 'false'.\n" + usageString; - logAndPrint(logger, emsg); - System.exit(1); - } - } - - try { - AAIConfig.init(); - ErrorLogHelper.loadProperties(); - } catch (Exception ae) { - String emsg = "Problem with either AAIConfig.init() or ErrorLogHelper.LoadProperties(). "; - logAndPrint(logger, emsg + "[" + ae.getMessage() + "]"); - System.exit(1); - } - - DbMaps dbMaps = null; - try { - ArrayList<String> apiVersions = new ArrayList<String>(); - apiVersions.add(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)); - final IngestModelMoxyOxm m = new IngestModelMoxyOxm(); - m.init(apiVersions, false); - dbMaps = m.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)); - } catch (AAIException ae) { - String emsg = "Could not instantiate a copy of DbMaps. "; - logAndPrint(logger, emsg + "[" + ae.getMessage() + "]"); - System.exit(1); - } catch (Exception e) { - String emsg = "exception, Could not instantiate a copy of DbMaps. "; - logAndPrint(logger, emsg + "[" + e.getMessage() + "]"); - System.exit(1); - } - // Give a big warning if the DbMaps.PropertyDataTypeMap value does not - // agree with what we're doing - String warningMsg = ""; - /*if (!dbMaps.PropertyDataTypeMap.containsKey(propName)) { - String emsg = "Property Name = [" + propName + "] not found in PropertyDataTypeMap. "; - logAndPrint(logger, emsg); - System.exit(1); - } else { - String currentDataType = dbMaps.PropertyDataTypeMap.get(propName); - if (!currentDataType.equals(targetDataType)) { - warningMsg = "TargetDataType [" + targetDataType + "] does not match what is in DbRules.java (" - + currentDataType + ")."; - } - }*/ - - if (!warningMsg.equals("")) { - logAndPrint(logger, "\n>>> WARNING <<<< "); - logAndPrint(logger, ">>> " + warningMsg + " <<<"); - } - - logAndPrint(logger, ">>> Processing will begin in 5 seconds (unless interrupted). <<<"); - try { - // Give them a chance to back out of this - Thread.sleep(5000); - } catch (java.lang.InterruptedException ie) { - logAndPrint(logger, " DB Schema Update has been aborted. "); - System.exit(1); - } - - try { - Class dType = null; - if (targetDataType.equals("String")) { - dType = String.class; - } else if (targetDataType.equals("Set<String>")) { - dType = String.class; - } else if (targetDataType.equals("Integer")) { - dType = Integer.class; - } else if (targetDataType.equals("Boolean")) { - dType = Boolean.class; - } else if (targetDataType.equals("Character")) { - dType = Character.class; - } else if (targetDataType.equals("Long")) { - dType = Long.class; - } else if (targetDataType.equals("Float")) { - dType = Float.class; - } else if (targetDataType.equals("Double")) { - dType = Double.class; - } else { - String emsg = "Not able translate the targetDataType [" + targetDataType + "] to a Class variable.\n"; - logAndPrint(logger, emsg); - System.exit(1); - } - String cardinality = "SINGLE"; // Default cardinality to SINGLE - - if (targetDataType.equals("Set<String>")) { - cardinality = "SET"; - } - logAndPrint(logger, " ---- NOTE --- about to open graph (takes a little while)\n"); - - graph = AAIGraph.getInstance().getGraph(); - if (graph == null) { - String emsg = "Not able to get a graph object in SchemaMod.java\n"; - logAndPrint(logger, emsg); - System.exit(1); - } - - // Make sure this property is in the DB. - graphMgt = graph.openManagement(); - if (graphMgt == null) { - String emsg = "Not able to get a graph Management object in SchemaMod.java\n"; - logAndPrint(logger, emsg); - System.exit(1); - } - PropertyKey origPropKey = graphMgt.getPropertyKey(propName); - if (origPropKey == null) { - String emsg = "The propName = [" + propName + "] is not defined in our graph. "; - logAndPrint(logger, emsg); - System.exit(1); - } - - if (targetIndexInfo.equals("uniqueIndex")) { - // Make sure the data in the property being changed can have a - // unique-index put on it. - // Ie. if there are duplicate values, we will not be able to - // migrate the data back into the property. - Boolean foundDupesFlag = UniquePropertyCheck.runTheCheckForUniqueness(TRANSID, FROMAPPID, - graph.newTransaction(), propName, logger); - if (foundDupesFlag) { - logAndPrint(logger, - "\n\n!!!!!! >> Cannot add a uniqueIndex for the property: [" + propName - + "] because duplicate values were found. See the log for details on which" - + " nodes have this value. \nThey will need to be resolved (by updating those values to new" - + " values or deleting unneeded nodes) using the standard REST-API \n"); - System.exit(1); - } - } - - // -------------- If we made it to here - we must be OK with making - // this change ------------ - - // Rename this property to a backup name (old name with "retired_" - // appended plus a dateStr) - - SimpleDateFormat d = new SimpleDateFormat("MMddHHmm"); - d.setTimeZone(TimeZone.getTimeZone("GMT")); - String dteStr = d.format(new Date()).toString(); - String retiredName = propName + "-" + dteStr + "-RETIRED"; - graphMgt.changeName(origPropKey, retiredName); - - // Create a new property using the original property name and the - // targetDataType - PropertyKey freshPropKey = graphMgt.makePropertyKey(propName).dataType(dType) - .cardinality(Cardinality.valueOf(cardinality)).make(); - - // Create the appropriate index (if any) - if (targetIndexInfo.equals("uniqueIndex")) { - String freshIndexName = propName + dteStr; - graphMgt.buildIndex(freshIndexName, Vertex.class).addKey(freshPropKey).unique().buildCompositeIndex(); - } else if (targetIndexInfo.equals("index")) { - String freshIndexName = propName + dteStr; - graphMgt.buildIndex(freshIndexName, Vertex.class).addKey(freshPropKey).buildCompositeIndex(); - } - - logAndPrint(logger, "Committing schema changes with graphMgt.commit()"); - graphMgt.commit(); - graph.tx().commit(); - - // Get A new graph object - logAndPrint(logger, " ---- NOTE --- about to open a second graph object (takes a little while)\n"); - - // For each node that has this property, update the new from the old - // and then remove the - // old property from that node - Iterable<?> verts = null; - verts = graph.query().has(retiredName).vertices(); - Iterator<?> it = verts.iterator(); - int vtxCount = 0; - ArrayList<String> alreadySeenVals = new ArrayList<String>(); - while (it.hasNext()) { - vtxCount++; - TitanVertex tmpVtx = (TitanVertex) it.next(); - String tmpVid = tmpVtx.id().toString(); - - Object origVal = tmpVtx.<Object> property(retiredName).orElse(null); - if (preserveData) { - tmpVtx.property(propName, origVal); - if (targetIndexInfo.equals("uniqueIndex")) { - // We're working on a property that is being used as a - // unique index - String origValStr = ""; - if (origVal != null) { - origValStr = origVal.toString(); - } - if (alreadySeenVals.contains(origValStr)) { - // This property is supposed to be unique, but we've - // already seen this value in this loop - // This should have been caught up in the first part - // of SchemaMod, but since it wasn't, we - // will just log the problem. - logAndPrint(logger, - "\n\n ---------- ERROR - could not migrate the old data [" + origValStr - + "] for propertyName [" + propName - + "] because this property is having a unique index put on it."); - showPropertiesAndEdges(TRANSID, FROMAPPID, tmpVtx, logger); - logAndPrint(logger, "-----------------------------------\n"); - } else { - // Ok to add this prop in as a unique value - tmpVtx.property(propName, origVal); - logAndPrint(logger, - "INFO -- just did the add of the freshPropertyKey and updated it with the orig value (" - + origValStr + ")"); - } - alreadySeenVals.add(origValStr); - } else { - // We are not working with a unique index - tmpVtx.property(propName, origVal); - logAndPrint(logger, - "INFO -- just did the add of the freshPropertyKey and updated it with the orig value (" - + origVal.toString() + ")"); - } - } else { - // existing nodes just won't have that property anymore - // Not sure if we'd ever actually want to do this -- maybe - // we'd do this if the new - // data type was not compatible with the old? - } - tmpVtx.property(retiredName).remove(); - - logAndPrint(logger, "INFO -- just did the remove of the " + retiredName + " from this vertex. (vid=" - + tmpVid + ")"); - } - - logAndPrint(logger, "Updated data for " + vtxCount + " vertexes. Now call graph2.commit(). "); - graph.tx().commit(); - } catch (Exception ex) { - logAndPrint(logger, "Threw a regular Exception: "); - logAndPrint(logger, ex.getMessage()); - } finally { - if (graphMgt != null && graphMgt.isOpen()) { - // Any changes that worked correctly should have already done - // their commits. - graphMgt.rollback(); - } - if (graph != null) { - // Any changes that worked correctly should have already done - // their commits. - graph.tx().rollback(); - graph.close(); - } - } - - } - - /** - * Show properties and edges. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param tVert the t vert - * @param logger the logger - */ - private static void showPropertiesAndEdges(String transId, String fromAppId, TitanVertex tVert, EELFLogger logger) { - - if (tVert == null) { - logAndPrint(logger, "Null node passed to showPropertiesAndEdges."); - } else { - String nodeType = ""; - Object ob = tVert.<String> property("aai-node-type"); - if (ob == null) { - nodeType = "null"; - } else { - nodeType = ob.toString(); - } - - logAndPrint(logger, " AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]"); - logAndPrint(logger, " Property Detail: "); - Iterator<VertexProperty<Object>> pI = tVert.properties(); - while (pI.hasNext()) { - VertexProperty<Object> tp = pI.next(); - Object val = tp.value(); - logAndPrint(logger, "Prop: [" + tp.key() + "], val = [" + val + "] "); - } - - Iterator<Edge> eI = tVert.edges(Direction.BOTH); - if (!eI.hasNext()) { - logAndPrint(logger, "No 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) { - logAndPrint(logger, - " >>> 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(); - logAndPrint(logger, "Found an edge (" + lab + ") from this vertex to a [" + nType - + "] node with VtxId = " + vid); - } - } - } - } // End of showPropertiesAndEdges() - - /** - * Log and print. - * - * @param logger the logger - * @param msg the msg - */ - protected static void logAndPrint(EELFLogger logger, String msg) { - System.out.println(msg); - logger.info(msg); - } - -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSInInterceptor.java b/aai-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSInInterceptor.java index 80127d0..7480c05 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSInInterceptor.java +++ b/aai-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSInInterceptor.java @@ -21,11 +21,8 @@ package org.openecomp.aai.interceptors; import java.io.InputStream; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; -import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; @@ -39,13 +36,14 @@ import org.apache.cxf.helpers.CastUtils; import org.apache.cxf.interceptor.LoggingMessage; import org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor; import org.apache.cxf.message.Message; - import org.openecomp.aai.exceptions.AAIException; import org.openecomp.aai.logging.ErrorLogHelper; import org.openecomp.aai.rest.util.EchoResponse; import org.openecomp.aai.util.AAIConfig; import org.openecomp.aai.util.AAIConstants; +import org.openecomp.aai.util.FormatDate; import org.openecomp.aai.util.HbaseSaltPrefixer; + import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; @@ -265,19 +263,8 @@ public class AAILogJAXRSInInterceptor extends JAXRSInInterceptor { * @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-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSOutInterceptor.java b/aai-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSOutInterceptor.java index 0f5e457..563500e 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSOutInterceptor.java +++ b/aai-resources/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSOutInterceptor.java @@ -21,10 +21,7 @@ package org.openecomp.aai.interceptors; import java.io.OutputStream; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.Collections; -import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -36,11 +33,12 @@ import org.apache.cxf.io.CachedOutputStream; import org.apache.cxf.io.CachedOutputStreamCallback; import org.apache.cxf.jaxrs.interceptor.JAXRSOutInterceptor; import org.apache.cxf.message.Message; - 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.FormatDate; + import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; @@ -269,34 +267,15 @@ public class AAILogJAXRSOutInterceptor extends JAXRSOutInterceptor { } 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(); } public String putTransaction(String tid, String status, String rqstTm, String respTm, String srcId, String rsrcId, String rsrcType, String rqstBuf, String respBuf, String actualResponse) { String tm = null; - String fromAppId = srcId.substring(0, srcId.indexOf(':')); - String transId = srcId.substring(srcId.indexOf(':') + 1); 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); + tm = this.genDate(); tid = tm + "-"; } diff --git a/aai-resources/src/main/java/org/openecomp/aai/rest/LegacyMoxyConsumer.java b/aai-resources/src/main/java/org/openecomp/aai/rest/LegacyMoxyConsumer.java index ca5fc33..27a082e 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/rest/LegacyMoxyConsumer.java +++ b/aai-resources/src/main/java/org/openecomp/aai/rest/LegacyMoxyConsumer.java @@ -48,7 +48,6 @@ import javax.ws.rs.core.UriInfo; import org.apache.cxf.jaxrs.ext.PATCH; import org.javatuples.Pair; - import org.openecomp.aai.dbmap.DBConnectionType; import org.openecomp.aai.exceptions.AAIException; import org.openecomp.aai.introspection.Introspector; @@ -58,12 +57,14 @@ import org.openecomp.aai.introspection.Version; import org.openecomp.aai.parsers.query.QueryParser; import org.openecomp.aai.rest.db.DBRequest; import org.openecomp.aai.rest.db.HttpEntry; +import org.openecomp.aai.rest.exceptions.AAIInvalidXMLNamespace; import org.openecomp.aai.rest.util.ValidateEncoding; import org.openecomp.aai.restcore.HttpMethod; import org.openecomp.aai.restcore.RESTAPI; import org.openecomp.aai.serialization.engines.QueryStyle; import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; import org.openecomp.aai.workarounds.RemoveDME2QueryParams; + import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.google.common.base.Joiner; @@ -100,7 +101,7 @@ public class LegacyMoxyConsumer extends RESTAPI { MediaType mediaType = headers.getMediaType(); - return this.handleWrites(Action.PUT, mediaType, HttpMethod.PUT, content, versionParam, uri, headers, info, req); + return this.handleWrites(mediaType, HttpMethod.PUT, content, versionParam, uri, headers, info); } /** @@ -195,7 +196,7 @@ public class LegacyMoxyConsumer extends RESTAPI { MediaType mediaType = MediaType.APPLICATION_JSON_TYPE; - return this.handleWrites(Action.PUT, mediaType, HttpMethod.MERGE_PATCH, content, versionParam, uri, headers, info, req); + return this.handleWrites(mediaType, HttpMethod.MERGE_PATCH, content, versionParam, uri, headers, info); } @@ -513,7 +514,7 @@ public class LegacyMoxyConsumer extends RESTAPI { * @param req the req * @return the response */ - private Response handleWrites(Action aaiAction, MediaType mediaType, HttpMethod method, String content, String versionParam, String uri, HttpHeaders headers, UriInfo info, HttpServletRequest req) { + private Response handleWrites(MediaType mediaType, HttpMethod method, String content, String versionParam, String uri, HttpHeaders headers, UriInfo info) { Response response = null; TransactionalGraphEngine dbEngine = null; @@ -524,7 +525,7 @@ public class LegacyMoxyConsumer extends RESTAPI { String realTime = headers.getRequestHeaders().getFirst("Real-Time"); TitanTransaction g = null; Boolean success = true; - + try { validateRequest(info); @@ -548,6 +549,10 @@ public class LegacyMoxyConsumer extends RESTAPI { if (obj == null) { throw new AAIException("AAI_3000", "object could not be unmarshalled:" + content); } + + if (mediaType.toString().contains(MediaType.APPLICATION_XML) && !content.equals("<empty/>") && isEmptyObject(obj)) { + throw new AAIInvalidXMLNamespace(content); + } this.validateIntrospector(obj, loader, uriObject, method); @@ -589,6 +594,9 @@ public class LegacyMoxyConsumer extends RESTAPI { private boolean hasRelatedTo(URI uri) { return uri.toString().contains("/" + RestTokens.COUSIN + "/"); - + } + + protected boolean isEmptyObject(Introspector obj) { + return "{}".equals(obj.marshal(false)); } } diff --git a/aai-resources/src/main/java/org/openecomp/aai/rest/exceptions/AAIInvalidXMLNamespace.java b/aai-resources/src/main/java/org/openecomp/aai/rest/exceptions/AAIInvalidXMLNamespace.java new file mode 100644 index 0000000..e71e1f2 --- /dev/null +++ b/aai-resources/src/main/java/org/openecomp/aai/rest/exceptions/AAIInvalidXMLNamespace.java @@ -0,0 +1,40 @@ +/*- + * ============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.rest.exceptions; + +import org.openecomp.aai.exceptions.AAIException; + +public class AAIInvalidXMLNamespace extends AAIException { + + private static final long serialVersionUID = 7487333042291858169L; + + public AAIInvalidXMLNamespace(String message) { + super("AAI_3011", message); + } + + public AAIInvalidXMLNamespace(Throwable cause) { + super("AAI_3011",cause); + } + + public AAIInvalidXMLNamespace(String message, Throwable cause) { + super("AAI_3011", cause, message); + } +} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/DeleteResource.java b/aai-resources/src/main/java/org/openecomp/aai/util/DeleteResource.java deleted file mode 100644 index 5e60c5c..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/DeleteResource.java +++ /dev/null @@ -1,229 +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.util; - -import java.lang.reflect.Field; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Properties; -import java.util.Scanner; -import java.util.UUID; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.ingestModel.DbMaps; -import org.openecomp.aai.ingestModel.IngestModelMoxyOxm; -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; - - -public class DeleteResource { - - private static EELFLogger LOGGER; - private static final String FROMAPPID = "AAI-TOOLS"; - private static final String TRANSID = UUID.randomUUID().toString(); - // the logic below to parse the url is dependent on the node types - // code may need to be adjusted if different nodetypes are added here - private static final String[] nodeTypeList = {"complex", "availability-zone", "oam-network", - "dvs-switch", "vserver", "vpe", "vpls-pe"}; - - private static final String USAGE_STRING = "Usage: deleteTool.sh <resource-path>\n + " - + "for example: resource-path for a particular customer is business/customers/customer/global-customer-id-1 \n"; - - /** - * The main method. - * - * @param <T> the generic type - * @param args the arguments - */ - public static <T> void main(String[] args) { - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_DELTOOL_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(DeleteResource.class); - String url = null; - try { - if ((args.length < 1) || ((args.length > 1) )) { - System.out.println("Insufficient or Invalid arguments"); - System.out.println(USAGE_STRING); - System.exit(1); - } - - Boolean bResVersionEnabled = false; - - try - { - String strEnableResVersion = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG); - if (strEnableResVersion != null && !strEnableResVersion.isEmpty()) - bResVersionEnabled = Boolean.valueOf(strEnableResVersion); - } - catch (Exception e) { - - } - - // Assume the config AAI_SERVER_URL has a last slash so remove if - // resource-path has it as the first char - String path = args[0].replaceFirst("^/", ""); - - Path p = Paths.get(path); - - // if the node type has one key - String resource = p.getName(p.getNameCount() - 2).toString(); - - IngestModelMoxyOxm moxyMod = new IngestModelMoxyOxm(); - DbMaps dbMaps = null; - try { - ArrayList <String> defaultVerLst = new ArrayList <String> (); - defaultVerLst.add( AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP) ); - moxyMod.init( defaultVerLst, false); - // Just make sure we can get DbMaps - don't actually need it until later. - dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)); - } - catch (Exception ex){ - ErrorLogHelper.logError("AAI_7402", " ERROR - Could not get the DbMaps object: " + ex.getMessage()); - System.exit(1); - } - // if the node type has two keys - this assumes max 2 keys - if (!dbMaps.NodeKeyProps.containsKey(resource)) - resource = p.getName(p.getNameCount() - 3).toString(); - String resourceClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, resource); - resourceClass = "org.openecomp.aai.domain.yang." + resourceClass; - - String dMsg = "class=" + resourceClass; - System.out.println(dMsg); - LOGGER.debug(dMsg); - dMsg = "path=" + path; - System.out.println(dMsg); - LOGGER.debug(dMsg); - - if (bResVersionEnabled) - { - RestObject<T> restObj = new RestObject<T>(); - @SuppressWarnings("unchecked") - T t = (T)getInstance(Class.forName(resourceClass)); - restObj.set(t); - - try - { - RestController.<T>Get(t, FROMAPPID, TRANSID, path, restObj, false); - t = restObj.get(); - String infMsg = " GET resoruceversion succeeded\n"; - System.out.println(infMsg); - LOGGER.info(infMsg); - String resourceUpdateVersion = GetResourceVersion(t); - path += "?resource-version=" + resourceUpdateVersion; - } catch (AAIException e) { - if (e.getMessage().contains("with status=404") && resource.equals("named-query")) { - System.out.println("Delete succeeded, the resource doesn't exist in the DB. " + p); - System.exit(0); - } else { - System.out.println("Delete failed. Resource Not found in the DB."); - System.exit(1); - } - } catch (Exception e1){ - System.out.println("Delete failed. Resource Not found in the DB."); - System.exit(1); - } - } - - System.out.print("\nAre you sure you would like to delete the resource \n" + url + "? (y/n): "); - Scanner s = new Scanner(System.in); - s.useDelimiter(""); - String confirm = s.next(); - - if (!confirm.equalsIgnoreCase("y")) { - String infMsg = "User chose to exit before deleting"; - System.out.println(infMsg); - LOGGER.info(infMsg); - System.exit(1); - } - - RestController.Delete(FROMAPPID, TRANSID, path); - - s.close(); - System.exit(0); - - } catch (AAIException e) { - ErrorLogHelper.logException(e); - System.exit(1); - } catch (Exception e) { - ErrorLogHelper.logError("AAI_7402", e.getMessage()); - System.exit(1); - } - - } - - /** - * Gets the single instance of DeleteResource. - * - * @param <T> the generic type - * @param clazz the clazz - * @return single instance of DeleteResource - * @throws IllegalAccessException the illegal access exception - * @throws InstantiationException the instantiation exception - */ - public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException - { - return clazz.newInstance(); - } - - /** - * Gets the resource version. - * - * @param <T> the generic type - * @param resource the resource - * @return the string - */ - public static <T> String GetResourceVersion(T resource) - { - Field[] fields = resource.getClass().getDeclaredFields(); - if (fields != null) - { - for (Field field : fields) - { - try - { - field.setAccessible(true); - if ( field.getName().equalsIgnoreCase("resourceVersion") ) - { - Object obj = field.get(resource); - return (String)obj; - } - - - } - catch (Exception e) - { - - } - - - } - } - return null; - } -} diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/PojoUtils.java b/aai-resources/src/main/java/org/openecomp/aai/util/PojoUtils.java deleted file mode 100644 index 870ddec..0000000 --- a/aai-resources/src/main/java/org/openecomp/aai/util/PojoUtils.java +++ /dev/null @@ -1,738 +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.util; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.DeserializationFeature; -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. - * - * @param <T> the generic type - * @param clazz the clazz - * @return the json from object - * @throws JsonGenerationException the json generation exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public <T> String getJsonFromObject(T clazz) throws JsonGenerationException, JsonMappingException, IOException { - return getJsonFromObject(clazz, false, true); - } - - /** - * Gets the json from object. - * - * @param <T> the generic type - * @param clazz the clazz - * @param wrapRoot the wrap root - * @param indent the indent - * @return the json from object - * @throws JsonGenerationException the json generation exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public <T> String getJsonFromObject(T clazz, boolean wrapRoot, boolean indent) throws JsonGenerationException, JsonMappingException, IOException { - ObjectMapper mapper = new ObjectMapper(); - - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - - mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - mapper.configure(SerializationFeature.INDENT_OUTPUT, indent); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapRoot); - - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapRoot); - - mapper.registerModule(new JaxbAnnotationModule()); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - mapper.writeValue(baos, clazz); - - 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-resources/src/main/java/org/openecomp/aai/util/PutResource.java b/aai-resources/src/main/java/org/openecomp/aai/util/PutResource.java index b4275b7..ced51cd 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/util/PutResource.java +++ b/aai-resources/src/main/java/org/openecomp/aai/util/PutResource.java @@ -24,17 +24,21 @@ import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Field; +import java.net.URI; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyManagementException; -import java.util.ArrayList; import java.util.Properties; import java.util.UUID; +import org.openecomp.aai.db.props.AAIProperties; import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.ingestModel.DbMaps; -import org.openecomp.aai.ingestModel.IngestModelMoxyOxm; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; import org.openecomp.aai.logging.ErrorLogHelper; +import org.openecomp.aai.parsers.uri.URIToObject; + import com.att.eelf.configuration.Configuration; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; @@ -98,31 +102,17 @@ public class PutResource { System.out.println(USAGE_STRING); System.exit(1); } - + + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); // Assume the config AAI_SERVER_URL has a last slash so remove if // resource-path has it as the first char - String path = args[0].replaceFirst("^/", ""); + URI uri = new URI(args[0]); + String path = args[0].replaceFirst("^/", ""); Path p = Paths.get(path); - // if the node type has one key - String resource = p.getName(p.getNameCount() - 2).toString(); - // if the node type has two keys - this assumes max 2 keys - IngestModelMoxyOxm moxyMod = new IngestModelMoxyOxm(); - DbMaps dbMaps = null; - try { - ArrayList <String> defaultVerLst = new ArrayList <String> (); - defaultVerLst.add( AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP) ); - moxyMod.init( defaultVerLst, false); - // Just make sure we can get DbMaps - don't actually need it until later. - dbMaps = IngestModelMoxyOxm.dbMapsContainer.get(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP)); - } - catch (Exception ex){ - ErrorLogHelper.logError("AAI_7402", "ERROR - Could not get the DbMaps object."); - System.exit(1); - } + URIToObject parser = new URIToObject(loader, uri); + String resource = parser.getEntityName(); - if (!dbMaps.NodeKeyProps.containsKey(resource)) - resource = p.getName(p.getNameCount() - 3).toString(); String resourceClass = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, resource); resourceClass = "org.openecomp.aai.domain.yang." + resourceClass; diff --git a/aai-resources/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java b/aai-resources/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java index 181627b..a73c4c8 100644 --- a/aai-resources/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java +++ b/aai-resources/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java @@ -21,9 +21,6 @@ package org.openecomp.aai.util; import java.io.StringWriter; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; import java.util.Iterator; import java.util.UUID; @@ -33,7 +30,6 @@ import org.eclipse.persistence.dynamic.DynamicEntity; import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; import org.json.JSONException; import org.json.JSONObject; - import org.openecomp.aai.dmaap.AAIDmaapEventJMSProducer; import org.openecomp.aai.domain.notificationEvent.NotificationEvent; import org.openecomp.aai.exceptions.AAIException; @@ -297,6 +293,9 @@ public class StoreNotificationEvent { entityJsonObjectUpdated.put("event-header", entityHeader); entityJsonObjectUpdated.put("cambria.partition", cambriaPartition); + String transId = entityHeader.getString("id"); + String fromAppId = entityHeader.getString("source-name"); + Iterator<String> iter = entityJsonObject.keys(); JSONObject entity = new JSONObject(); if (iter.hasNext()) { @@ -320,9 +319,8 @@ public class StoreNotificationEvent { * @return the string */ public static String genDate() { - Date date = new Date(); - DateFormat formatter = new SimpleDateFormat("YYYYMMdd-HH:mm:ss:SSS"); - return formatter.format(date); + FormatDate fd = new FormatDate("YYMMdd-HH:mm:ss:SSS"); + return fd.getDateTime(); } /** @@ -331,9 +329,8 @@ public class StoreNotificationEvent { * @return the string */ public static String genDate2() { - Date date = new Date(); - DateFormat formatter = new SimpleDateFormat("YYYYMMddHHmmss"); - return formatter.format(date); + FormatDate fd = new FormatDate("YYYYMMddHHmmss"); + return fd.getDateTime(); } } diff --git a/aai-resources/src/main/scripts/addResourceVersionProperty.sh b/aai-resources/src/main/scripts/addResourceVersionProperty.sh deleted file mode 100644 index 821275a..0000000 --- a/aai-resources/src/main/scripts/addResourceVersionProperty.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/ksh - -### -# ============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========================================================= -### - -# -# The script invokes the AddResourceVersionProp java class as a one-time (per database instance) migration tool -# which adds the new property "resource-version" to every node in the db. -# - -echo -echo `date` " Starting $0" - -. /etc/profile.d/aai.sh -PROJECT_HOME=/opt/app/aai-resources - -for JAR in `ls $PROJECT_HOME/extJars/*.jar` -do - CLASSPATH=$CLASSPATH:$JAR -done - -for JAR in `ls $PROJECT_HOME/lib/*.jar` -do - CLASSPATH=$CLASSPATH:$JAR -done - -userid=$( id | cut -f2 -d"(" | cut -f1 -d")" ) -if [ "${userid}" != "aaiadmin" ]; then - echo "You must be aaiadmin to run $0. The id used $userid." - exit 1 -fi - - -$JAVA_HOME/bin/java -classpath $CLASSPATH -Dhttps.protocols=TLSv1.1,TLSv1.2 -DAJSC_HOME=$PROJECT_HOME -Daai.home=$PROJECT_HOME \ - org.openecomp.aai.dbgen.AddResourceVersionProp - -echo `date` " Done $0" -exit 0 diff --git a/aai-resources/src/test/java/org/openecomp/aai/dbgen/DbMethTest.java b/aai-resources/src/test/java/org/openecomp/aai/dbgen/DbMethTest.java deleted file mode 100644 index 420daa7..0000000 --- a/aai-resources/src/test/java/org/openecomp/aai/dbgen/DbMethTest.java +++ /dev/null @@ -1,90 +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 static org.junit.Assert.assertEquals; - -import java.util.HashMap; -import java.util.Map; - -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import org.openecomp.aai.exceptions.AAIException; - -public class DbMethTest { - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Test - public void testGetEdgeTagPropPutHash() throws AAIException { - Map<String, String> expectedMap = new HashMap<>(); - expectedMap.put("usesResource", "false"); - expectedMap.put("isParent", "false"); - expectedMap.put("SVC-INFRA", "true"); - expectedMap.put("hasDelTarget", "false"); - - assertEquals(expectedMap, DbMeth.getEdgeTagPropPutHash("", "", "pserver|complex").get("locatedIn").getEdgeProperties()); - } - - @Test - public void testGetEdgeTagPropPutHash2() throws AAIException { - Map<String, String> expectedMap = new HashMap<>(); - expectedMap.put("usesResource", "false"); - expectedMap.put("isParent", "false"); - expectedMap.put("SVC-INFRA", "false"); - expectedMap.put("hasDelTarget", "false"); - - assertEquals(expectedMap, DbMeth.getEdgeTagPropPutHash("", "", "service-instance|allotted-resource").get("uses").getEdgeProperties()); - } - - @Test - public void testGetEdgeTagPropPutHash3() throws AAIException { - Map<String, String> expectedMap = new HashMap<>(); - expectedMap.put("usesResource", "false"); - expectedMap.put("isParent", "true"); - expectedMap.put("SVC-INFRA", "false"); - expectedMap.put("hasDelTarget", "false"); - - assertEquals(expectedMap, DbMeth.getEdgeTagPropPutHash("", "", "service-instance|allotted-resource").get("has").getEdgeProperties()); - } - - @Ignore - @Test - public void getGetEdgeTagPropPutHashThrowsExceptionWhenNoRuleExists() throws Exception { - expectedEx.expect(AAIException.class); - expectedEx.expectMessage("AAI_6120"); - DbMeth.getEdgeTagPropPutHash("", "", "complex|pserver"); - } - - @Ignore - @Test - public void getGetEdgeTagPropPutHashThrowsExceptionWhenNoRuleExists1() throws Exception { - expectedEx.expect(AAIException.class); - expectedEx.expectMessage("AAI_6120"); - DbMeth.getEdgeTagPropPutHash("", "", "complex"); - } - - -} diff --git a/aai-resources/src/test/java/org/openecomp/aai/dbgen/DbRunTest.java b/aai-resources/src/test/java/org/openecomp/aai/dbgen/DbRunTest.java deleted file mode 100644 index cef8019..0000000 --- a/aai-resources/src/test/java/org/openecomp/aai/dbgen/DbRunTest.java +++ /dev/null @@ -1,341 +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.nio.file.attribute.FileTime; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Iterator; - -import org.openecomp.aai.dbmap.AAIGraph; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.DbTestGetFileTime; -import com.thinkaurelius.titan.core.TitanTransaction; -import com.thinkaurelius.titan.core.TitanVertex; - -public class DbRunTest { - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - String testid = "NA"; - TitanTransaction graph = null; - - boolean runIt = false; - try { - AAIConfig.init(); - ErrorLogHelper.loadProperties(); - if (args.length > 0) { - System.out.println( "DbRunTest called with " + args.length + " arguments"); - - - } else { - System.out.print("usage: DbRunTest <testid> <processDelay milliseconds> <processName> <loopcnt>\n"); - return; - } - } catch (AAIException e) { - System.out.print("Threw a AAIException -- \n"); - System.out.println(e.getMessage()); - } catch (Exception ex) { - System.out.print("Threw a regular ole Exception \n"); - System.out.println(ex.getMessage()); - } - - - - //System.out.println("skipping Titan graph for now..."); - //TitanGraph graph = null; - - - String processName = "NA"; - if ( args.length > 1 ) - processName = args[2].trim(); - - try { - System.out.println(processName + " ---- NOTE --- about to open graph (takes a little while)--------\n"); - - graph = AAIGraph.getInstance().getGraph().newTransaction(); - - if( graph == null ){ - System.out.println(processName + "Error creating Titan graph. \n"); - return; - } - } catch( Exception ex ){ - System.out.println( processName + " ERROR: caught this exception: " + ex ); - return; - } - - testid = args[0].trim(); - runIt = true; - Integer processDelay = new Integer(args[1].trim() ); // delay of write - Integer loopCnt = new Integer(args[3].trim() ); // delay of write - - String path = "NA"; - try { - - path = AAIConfig.get("dbruntest.path" ); // uses file create-timestamp - Integer writeDelay = new Integer(AAIConfig.get("dbruntest.delay" )); // delay seconds from create-timestamp - Integer loopDelay = new Integer(AAIConfig.get("dbruntest.loopdelay" )); // delay seconds from create-timestamp for next loop - - DbTestGetFileTime getFileTime = new DbTestGetFileTime(); - FileTime fileTime = getFileTime.createFileReturnTime( path ); - long createMillis = fileTime.toMillis(); - System.out.println(processName + " delays to use " + writeDelay + " processDelay " + processDelay); - System.out.println(processName + " test control file " + path + " creation time :" - + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSS") - .format(fileTime.toMillis())); - - long delayMillis = writeDelay * 60 * 1000; - long loopMillis = loopDelay * 60 * 1000; - - int loops = loopCnt.intValue(); - - long sleepTime; - for ( int i = 0; i < loops; ++i ) { - - if ( i > 0 ) - delayMillis = loopMillis * i; // to find the time the write will be done - delayMillis += processDelay.intValue(); - - System.out.println(processName + " test control file " + path + " write time :" - + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSS") - .format(createMillis + delayMillis)); - - Calendar now = Calendar.getInstance(); - long myMillis = now.getTimeInMillis(); - System.out.println(processName + " test control file " + path + " current time :" - + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSS") - .format(myMillis)); - // total sleep based on current time, time file was created, and any delay per process - - if ( i == 0 ) - sleepTime = createMillis + delayMillis - myMillis; // + processDelay.intValue() - else - sleepTime = createMillis + ( loopMillis * i ) - myMillis; - sleepTime += processDelay.intValue(); - System.out.println(processName + " sleep " + sleepTime + " current time :" - + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSS") - .format(myMillis)); - Thread.sleep(sleepTime); - - System.out.println(processName + " out of sleep for loop count " + i); - - if (runIt) { - // include loop in unique-id string - runMultiLevelTest(graph, testid + i + "-", processName); - } - - } // end loop - - - } catch ( Exception io ) { - System.out.println( processName + " Exception getting creation time " + path + " message " + io.getMessage()); - io.printStackTrace(); - } - - - - - - if( graph != null && graph.isOpen() ){ - System.out.println(processName + "About to call graph.shutdown()"); - graph.tx().close(); - System.out.println(processName + " -- AFTER call graph.shutdown()"); - } - - System.out.println(processName + " -- Boom!"); - System.exit(0); - - }// end of main() - - - - /** - * Run multi level test. - * - * @param graph the graph - * @param testIdentifier the test identifier - * @param processName the process name - */ - private static void runMultiLevelTest(TitanTransaction graph, String testIdentifier, String processName) { - - try { - String useRollback = AAIConfig.get("dbruntest.rollback"); - - // l3-interface-ipv6-address-list -> vlan -> l-interface -> vnic -> vserver -> tenant - - HashMap<String, Object> propHash7 = new HashMap<String, Object>(); - propHash7.put("tenant-name", testIdentifier + "tenantName"); - propHash7.put("tenant-id", testIdentifier + "tenantId"); - TitanVertex tenantVtx = DbMeth.persistAaiNode("junkTransId", - "testApp", graph, "tenant", propHash7, true, null); - - - HashMap<String, Object> propHash8 = new HashMap<String, Object>(); - propHash8.put("vserver-selflink", testIdentifier + "vserverSelfThing"); - propHash8.put("vserver-id", testIdentifier + "vserverID"); - propHash8.put("vserver-name", testIdentifier + "vserverName"); - propHash8.put("vserver-name2", testIdentifier + "vserverName2"); - TitanVertex vserverVtx = DbMeth.persistAaiNode("junkTransId", - "testApp", graph, "vserver", propHash8, true, tenantVtx); - - HashMap<String, Object> propHash10 = new HashMap<String, Object>(); - propHash10.put("interface-name", testIdentifier + "logIntfOnVpe"); - TitanVertex logIntfVtx = DbMeth.persistAaiNode("junkTransId", - "testApp", graph, "l-interface", propHash10, true, vserverVtx); - - HashMap<String, Object> propHash11 = new HashMap<String, Object>(); - propHash11.put("vlan-interface", testIdentifier + "vlanIntf"); - TitanVertex vlanVtx = DbMeth.persistAaiNode("junkTransId", - "testApp", graph, "vlan", propHash11, true, logIntfVtx); - - HashMap<String, Object> propHash12 = new HashMap<String, Object>(); - propHash12.put("l3-interface-ipv6-address", testIdentifier + "v6 pool"); - TitanVertex l3PoolVtx = DbMeth.persistAaiNode("junkTransId", - "testApp", graph, "l3-interface-ipv6-address-list", propHash12, true, vlanVtx); - - System.out.println(processName + " ---- did the persist on all the nodes -- "); - - DbMeth.persistAaiEdge("junkTransId", "junkApp", graph, vserverVtx, tenantVtx); - DbMeth.persistAaiEdge("junkTransId", "junkApp", graph, logIntfVtx, vserverVtx); - DbMeth.persistAaiEdge("junkTransId", "junkApp", graph, vlanVtx, logIntfVtx); - DbMeth.persistAaiEdge("junkTransId", "junkApp", graph, l3PoolVtx, vlanVtx); - - System.out.println(processName + " ---- persisted all the edges -- "); - - if ( useRollback.toUpperCase().equals("Y")) { - System.out.print(processName + " using rollback for unittesting\n"); - if (graph != null) { - graph.tx().rollback(); - } - } else { - graph.tx().commit(); - System.out.println(processName + " ---- Ran graph.commit() -- "); - } - HashMap<String, Object> propHash0 = new HashMap<String, Object>(); - propHash0.put("l3-interface-ipv6-address-list.l3-interface-ipv6-address", testIdentifier + "v6 pool"); - propHash0.put("tenant.tenant-name", testIdentifier + "tenantName"); - propHash0.put("tenant.tenant-id", testIdentifier + "tenantId"); - propHash0.put("vserver.vserver-selflink", testIdentifier + "vserverSelfThing"); - propHash0.put("vserver.vserver-id", testIdentifier + "vserverID"); - propHash0.put("vserver.vserver-name", testIdentifier + "vserverName"); - propHash0.put("vserver.vserver-name2", testIdentifier + "vserverName2"); - propHash0.put("l-interface.interface-name", testIdentifier + "logIntfOnVpe"); - propHash0.put("vlan.vlan-interface", testIdentifier + "vlanIntf"); - - - System.out.println(processName + " ---- First try the getUniqueNodeWithDepParams trail: "); - - TitanVertex poolV = DbMeth.getUniqueNodeWithDepParams("junkTransId", "junkAppId", graph, "l3-interface-ipv6-address-list", propHash0, null); - - ArrayList <String> retArr = DbMeth.showPropertiesForNode("junkTransId", "junkFromAppId", poolV); - for( String info : retArr ){ System.out.println(info); } - -/* - * RelationshipUtils replaced with RelationshipGraph - * System.out.println(processName + " ---- Next try the figureRelData trail: "); - List <RelationshipData> relDatList = RelationshipUtils.figureRelData("junkTransId", "junkAppId", graph, poolV, ""); - System.out.println(processName + " ---- Looks like it worked ----------"); - Iterator<RelationshipData> iterDat = relDatList.iterator(); - while (iterDat.hasNext()) { - RelationshipData relDat = iterDat.next(); - System.out.println(processName + " relData: key = [" - + relDat.getRelationshipKey() + "], val = [" - + relDat.getRelationshipValue() + "]"); - }*/ - - - HashMap<String, Object> propHash = new HashMap<String, Object>(); - ArrayList<TitanVertex> vertList; - - propHash.put("tenant-id", testIdentifier + "tenantId"); - vertList = DbMeth.getNodes("junkTransId", - "testApp", graph, "tenant", propHash, false, null, true); - - Iterator<TitanVertex> iter = vertList.iterator(); - - int vertexCnt = 0; - while( iter.hasNext() ) { - ++vertexCnt; - TitanVertex tvx = iter.next(); - System.out.println(processName + " Found tenant " + vertexCnt ); - DbMeth.showPropertiesForNode( "junkId", "junkApp", tvx ); - } - if ( vertexCnt == 0 ) - System.out.println(processName + " no tenant found" ); - - propHash = new HashMap<String, Object>(); - - propHash.put("vserver-id", testIdentifier + "vserverID"); - vertList = DbMeth.getNodes("junkTransId", - "testApp", graph, "vserver", propHash, false, null, true); - - iter = vertList.iterator(); - - vertexCnt = 0; - while( iter.hasNext() ) { - ++vertexCnt; - TitanVertex tvx = iter.next(); - System.out.println(processName + " Found vserver " + vertexCnt ); - DbMeth.showPropertiesForNode( "junkId", "junkApp", tvx ); - } - if ( vertexCnt == 0 ) - System.out.println(processName + " no vserver found" ); - - if ( useRollback.toUpperCase().equals("Y")) { - System.out.print(processName + " using rollback for unittesting\n"); - if (graph != null) { - graph.tx().rollback(); - } - } - - } - catch (AAIException e) { - System.out.print(processName + " Threw an AAIException -- calling graph.rollback()\n"); - System.out.println("exMsg = [" + e.getMessage() + "]"); - if (graph != null) { - graph.tx().rollback(); - } - } - catch (Exception ex) { - System.out.print(processName + " Threw a regular ole Exception calling graph.rollback()\n"); - System.out.println(ex.getMessage()); - System.out.println(ex.toString()); - if (graph != null) { - graph.tx().rollback(); - } - } - - - - return; - } - - -} diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java deleted file mode 100644 index 0bba892..0000000 --- a/aai-resources/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java +++ /dev/null @@ -1,112 +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.util; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.TimeZone; -import java.util.concurrent.TimeUnit; - -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.powermock.modules.agent.PowerMockAgent; -import org.powermock.modules.junit4.rule.PowerMockRule; - -public class AAIUtilsTest { - - @Rule - public PowerMockRule rule = new PowerMockRule(); - - static { - PowerMockAgent.initializeIfNeeded(); - } - - - AAIUtils testObj; - - /** - * Initialize. - */ - @Before - public void initialize(){ - testObj = new AAIUtils(); - } - - /** - * Test nullCheck with null. - */ - @Test - public void testNullCheck_withNull(){ - List<String> newList = null; - assertNotNull("method nullCheck should not return null", AAIUtils.nullCheck(newList)); - } - - /** - * Test nullCheck with a List. - */ - @Test - public void testNullCheck_withList(){ - List<String> newList = new ArrayList<String>(); - newList.add("testString"); - assertNotNull("method nullCheck failed for a List", AAIUtils.nullCheck(newList)); - } - - /** - * Test genDate using a past and a future date. - */ - @Test - public void testGenDate(){ - - Date d1 = new Date(0); - - DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS"); - formatter.setTimeZone(TimeZone.getTimeZone("GMT")); - formatter.setLenient(false); - - Date d2 = null; - - try { - d2 = formatter.parse(AAIUtils.genDate()); - } catch (ParseException e) { - fail("Date parsing exception"); - e.printStackTrace(); - } - - try { - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e1) {} - - Date d3 = new Date(); - - assertTrue("Generated date is not after a past date", d2.after(d1)); - assertTrue("Generated date is not before a future date", d2.before(d3)); - } - -} diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java deleted file mode 100644 index 1522e80..0000000 --- a/aai-resources/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java +++ /dev/null @@ -1,108 +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.util; - - - -import static org.junit.Assert.assertEquals; - -import static org.junit.Assert.assertFalse; - -import static org.junit.Assert.assertTrue; - -import static org.junit.Assert.fail; - -import org.junit.Test; - - - -import org.openecomp.aai.domain.yang.PhysicalLink; - - - -public class DeleteResourceTest { - - - - /** - * Test getInstance. - */ - - @Test - - public void testGetInstance(){ - - Object obj = null; - - try { - - obj = DeleteResource.getInstance(DeleteResource.class); - - } catch (IllegalAccessException | InstantiationException e) { - - e.printStackTrace(); - - } - - assertTrue("Didn't get right instance", obj instanceof DeleteResource); - - } - - - - /** - * Test GetResourceVersion. - */ - - @Test - - public void testGetResourceVersion(){ - - String version = "aVersion"; - - PhysicalLink plink = new PhysicalLink(); - - plink.setResourceVersion(version); - - assertEquals("Versions didn't match", version, DeleteResource.GetResourceVersion(plink)); - - } - - - - /** - * Test null in GetResourceVersion. - */ - - @Test - - public void testGetResourceVersion_withNull(){ - - PhysicalLink plink = new PhysicalLink(); - - assertEquals("Versions didn't match", null, DeleteResource.GetResourceVersion(plink)); - - } - - - -} - diff --git a/aai-resources/src/test/resources/com/att/aai/introspection/aai_oxm_v10.xml b/aai-resources/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v10.xml index 8479470..8479470 100644 --- a/aai-resources/src/test/resources/com/att/aai/introspection/aai_oxm_v10.xml +++ b/aai-resources/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v10.xml diff --git a/aai-resources/src/test/resources/com/att/aai/introspection/aai_oxm_v8.xml b/aai-resources/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v8.xml index 1eb8f9c..1eb8f9c 100644 --- a/aai-resources/src/test/resources/com/att/aai/introspection/aai_oxm_v8.xml +++ b/aai-resources/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v8.xml diff --git a/aai-resources/src/test/resources/com/att/aai/introspection/aai_oxm_v9.xml b/aai-resources/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v9.xml index a0fc9c8..a0fc9c8 100644 --- a/aai-resources/src/test/resources/com/att/aai/introspection/aai_oxm_v9.xml +++ b/aai-resources/src/test/resources/org/openecomp/aai/introspection/aai_oxm_v9.xml diff --git a/aai-resources/src/test/resources/com/att/aai/introspection/sideeffect/nested-case.json b/aai-resources/src/test/resources/org/openecomp/aai/introspection/sideeffect/nested-case.json index 40a0493..40a0493 100644 --- a/aai-resources/src/test/resources/com/att/aai/introspection/sideeffect/nested-case.json +++ b/aai-resources/src/test/resources/org/openecomp/aai/introspection/sideeffect/nested-case.json diff --git a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/graphson/resource.graphson b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/graphson/resource.graphson index 257916a..257916a 100644 --- a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/graphson/resource.graphson +++ b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/graphson/resource.graphson diff --git a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/resource-format.json b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/resource-format.json index c7e4255..c7e4255 100644 --- a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/resource-format.json +++ b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/resource-format.json diff --git a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/resource_and_url-format.json b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/resource_and_url-format.json index 80d6560..80d6560 100644 --- a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/resource_and_url-format.json +++ b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/resource_and_url-format.json diff --git a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/simple-format.json b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/simple-format.json index dd34261..dd34261 100644 --- a/aai-resources/src/test/resources/com/att/aai/serialization/queryformats/simple-format.json +++ b/aai-resources/src/test/resources/org/openecomp/aai/serialization/queryformats/simple-format.json |