aboutsummaryrefslogtreecommitdiffstats
path: root/aai-resources/src/main/java/org/onap/aai/dbgen/UpdateEdgeTags.java
blob: 8be40de6b666b31218f06199b7eb3f9eb67f427d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
 * ============LICENSE_START=======================================================
 * org.onap.aai
 * ================================================================================
 * Copyright © 2017-2018 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.onap.aai.dbgen;

import com.google.common.collect.Multimap;
import com.thinkaurelius.titan.core.TitanGraph;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.logging.LoggingContext;
import org.onap.aai.logging.LoggingContext.StatusCode;
import org.onap.aai.serialization.db.EdgeRule;
import org.onap.aai.serialization.db.EdgeRules;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAISystemExitUtil;
import org.onap.aai.util.AAIConstants;

import java.util.*;


public class UpdateEdgeTags {

	private static 	final  String    FROMAPPID = "AAI-DB";
	private static 	final  String    TRANSID   = UUID.randomUUID().toString();
	
	/**
	 * The main method.
	 *
	 * @param args the arguments
	 */
	public static void main(String[] args) {

		System.setProperty("aai.service.name", UpdateEdgeTags.class.getSimpleName());

		if( args == null || args.length != 1 ){
				String msg = "usage:  UpdateEdgeTags edgeRuleKey  (edgeRuleKey can be either, all, or a rule key like 'nodeTypeA|nodeTypeB') \n";
				System.out.println(msg);
				AAISystemExitUtil.systemExitCloseAAIGraph(1);
		}
	  	LoggingContext.init();
		LoggingContext.partnerName(FROMAPPID);
		LoggingContext.serviceName(AAIConstants.AAI_RESOURCES_MS);
		LoggingContext.component("updateEdgeTags");
		LoggingContext.targetEntity(AAIConstants.AAI_RESOURCES_MS);
		LoggingContext.targetServiceName("main");
		LoggingContext.requestId(TRANSID);
		LoggingContext.statusCode(StatusCode.COMPLETE);
		LoggingContext.responseCode("0");

	  	String edgeRuleKeyVal = args[0];

		TitanGraph graph = null;
		EdgeRules edgeRulesInstance = EdgeRules.getInstance();
		Multimap<String, EdgeRule> edgeRuleMultimap = edgeRulesInstance.getAllRules();

		HashMap <String,Object> edgeRuleHash = new HashMap <String,Object>();
		HashMap <String,Object> edgeRulesFullHash = new HashMap <String,Object>();
		HashMap <String,Object> edgeRuleLabelToKeyHash = new HashMap <String,Object>();
		ArrayList <String> labelMapsToMultipleKeys = new <String> ArrayList ();
		
		// Loop through all the edge-rules make sure they look right and
    	//    collect info about which labels support duplicate ruleKeys.
    	Iterator<String> edgeRulesIterator = edgeRuleMultimap.keySet().iterator();

    	while( edgeRulesIterator.hasNext() ){
        	String ruleKey = edgeRulesIterator.next();
        	Collection <EdgeRule> edRuleColl = edgeRuleMultimap.get(ruleKey);
        	Iterator <EdgeRule> ruleItr = edRuleColl.iterator();
    		if( ruleItr.hasNext() ){
    			// For now, we only look for one type of edge between two nodes.
    			EdgeRule edgeRule = ruleItr.next();
    			String edgeRuleString = String.format("%s,%s,%s,%s,%s,%s",
					    edgeRule.getLabel(),
					    edgeRule.getDirection(),
					    edgeRule.getMultiplicityRule(),
					    edgeRule.getContains(),
					    edgeRule.getDeleteOtherV(),
					    edgeRule.getServiceInfrastructure());
    			edgeRulesFullHash.put(ruleKey,edgeRuleString);
  			  	String edgeLabel = edgeRule.getLabel();
  			  	if( edgeRuleLabelToKeyHash.containsKey(edgeLabel) ){
  			  		// This label maps to more than one edge rule - we'll have to figure out
  			  		// which rule applies when we look at each edge that uses this label.
  			  		// So we take it out of mapping hash and add it to the list of ones that
  			  		// we'll need to look up later.
  			  		edgeRuleLabelToKeyHash.remove(edgeLabel);
  			  		labelMapsToMultipleKeys.add(edgeLabel);
  			  	}
  			  	else {
  			  		edgeRuleLabelToKeyHash.put(edgeLabel, ruleKey);
  			  	}
    		}
    	}
    	
		if( ! edgeRuleKeyVal.equals( "all" ) ){
			// If they passed in a (non-"all") argument, that is the single edgeRule that they want to update.
			// Note - the key looks like "nodeA|nodeB" as it appears in DbEdgeRules.EdgeRules
			Collection <EdgeRule> edRuleColl = edgeRuleMultimap.get(edgeRuleKeyVal);
        	Iterator <EdgeRule> ruleItr = edRuleColl.iterator();
    		if( ruleItr.hasNext() ){
    			// For now, we only look for one type of edge between two nodes (Ie. for one key).
    			EdgeRule edRule = ruleItr.next();
    			edgeRuleHash.put(edgeRuleKeyVal, edRule);
    			System.out.println("Adding this rule to list of rules to do: key = " + edgeRuleKeyVal + ", rule = [" + edRule + "]");
    		}
    		else {
    			String msg = " Error - Unrecognized edgeRuleKey: [" + edgeRuleKeyVal + "]. ";
    			System.out.println(msg);
    			AAISystemExitUtil.systemExitCloseAAIGraph(0);
    		}
		}
		else {
			// They didn't pass a target ruleKey in, so we'll work on all types of edges
			edgeRuleHash.putAll(edgeRulesFullHash);
		}
		
    	try {   
    		AAIConfig.init();
    		System.out.println("    ---- NOTE --- about to open graph (takes a little while)--------\n");
    		ErrorLogHelper.loadProperties();

    		graph = AAIGraph.getInstance().getGraph();
    	
    		if( graph == null ){
    			String emsg = "null graph object in updateEdgeTags() \n";
    			System.out.println(emsg);
    	 		AAISystemExitUtil.systemExitCloseAAIGraph(0);
    		}
    	}
	    catch (AAIException e1) {
			String msg =  e1.getErrorObject().toString();
			System.out.println(msg);
			AAISystemExitUtil.systemExitCloseAAIGraph(0);
        }
        catch (Exception e2) {
	 		String msg =  e2.toString();
	 		System.out.println(msg);
	 		e2.printStackTrace();
	 		AAISystemExitUtil.systemExitCloseAAIGraph(0);
        }

    	Graph g = graph.newTransaction();
		try {  
        	 Iterator<Edge> edgeItr = graph.traversal().E();
        	 
     		 // Loop through all edges and update their tags if they are a type we are interested in.
        	 //    Sorry about looping over everything, but for now, I can't find a way to just select one type of edge at a time...!?
			 StringBuffer sb;
			 boolean missingEdge = false;
        	 while( edgeItr != null && edgeItr.hasNext() ){
        		 Edge tmpEd = edgeItr.next();
	        	 String edLab = tmpEd.label().toString(); 
	        	 
	     		 // Since we have edgeLabels that can be used for different pairs of node-types, we have to
	        	 //    look to see what nodeTypes this edge is connecting (if it is a label that could do this).
	        	 String derivedEdgeKey = "";
	        	 if( labelMapsToMultipleKeys.contains(edLab) ){
	        		 // need to figure out which key is right for this edge
	        		 derivedEdgeKey = deriveEdgeRuleKeyForThisEdge( TRANSID, FROMAPPID, g, tmpEd );
	        	 }
	        	 else {
	        		 // This kind of label only maps to one key -- so we can just look it up.
	        		 if ( edgeRuleLabelToKeyHash.get(edLab) == null ) {
	        			 if ( !missingEdge ) {
	        				 System.out.print("DEBUG - missing edge(s) in edgeRuleLabelToKeyHash " + edgeRuleLabelToKeyHash.toString());
	        				 missingEdge = true;
	        			 }
		        		 sb = new StringBuffer();
	        			 Vertex vIn = null;
	        			 Vertex vOut = null;
	        			 Object obj = null;
	        			 vIn = tmpEd.inVertex();
	        			 if ( vIn != null ){
	        				 obj = vIn.<String>property("aai-node-type").orElse(null);
	        				 if ( obj != null ) {
	        					 sb.append("from node-type " + obj.toString());
	        				 
	        					 obj = vIn.id();
	        					 sb.append(" id " + obj.toString());
	        				 } else {
	        					 sb.append(" missing from node-type ");
	        				 }
	        			 } else {
	        				 sb.append(" missing inbound vertex ");
	        			 }
	        			 vOut = tmpEd.outVertex();
	        			 if ( vOut != null ) {
	        				 obj = vOut.<String>property("aai-node-type").orElse(null);
	        				 if ( obj != null ) {
		        				 sb.append(" to node-type " + obj.toString());
		        				 obj = vOut.id();
		        				 sb.append(" id " + obj.toString());
	        				 } else {
	        					 sb.append(" missing to node-type ");
	        				 }
	        			 } else {
	        				 sb.append(" missing to vertex ");
	        			 }
	        			 System.out.println("DEBUG - null entry for [" + edLab + "] between " + sb.toString());
	        			 continue;
	        		 }
	        		 derivedEdgeKey = edgeRuleLabelToKeyHash.get(edLab).toString();
	        	 }
	        	 
	        	 if( edgeRuleHash.containsKey(derivedEdgeKey) ){
	        		 // this is an edge that we want to update
	        		 System.out.print("DEBUG - key = " + derivedEdgeKey + ", label = " + edLab 
	        				 + ", for id = " + tmpEd.id().toString() + ", set: ");
			         Map<String,EdgeRule> edgeRules = getEdgeTagPropPutHash(TRANSID, FROMAPPID, derivedEdgeKey);
			         for (String key : edgeRules.keySet()) {
			        	if (tmpEd.label().equals(key)) {
			        		EdgeRules.getInstance().addProperties(tmpEd, edgeRules.get(key));
			        	}
			         }
			         System.out.print("\n");
	        	 }
			 } // End of looping over all edges
			 graph.tx().commit();
			 System.out.println("DEBUG - committed updates for listed edges " );
		}
		catch (Exception e2) {
			String msg = e2.toString();
			System.out.println(msg);
			e2.printStackTrace();
			if( graph != null ){
				graph.tx().rollback();
			}
			AAISystemExitUtil.systemExitCloseAAIGraph(0);
		}

	    AAISystemExitUtil.systemExitCloseAAIGraph(0);
    
	}// end of main()

	
	/**
	 * Derive edge rule key for this edge.
	 *
	 * @param transId the trans id
	 * @param fromAppId the from app id
	 * @param graph the graph
	 * @param tEdge the t edge
	 * @return String - key to look up edgeRule (fromNodeType|toNodeType)
	 * @throws AAIException the AAI exception
	 */
	public static String deriveEdgeRuleKeyForThisEdge( String transId, String fromAppId, Graph graph,  
			Edge tEdge ) throws AAIException {

		Vertex fromVtx = tEdge.outVertex();
		Vertex toVtx = tEdge.inVertex();
		String startNodeType = fromVtx.<String>property("aai-node-type").orElse(null);
		String targetNodeType = toVtx.<String>property("aai-node-type").orElse(null);
		String key = startNodeType + "|" + targetNodeType;
		if( EdgeRules.getInstance().hasEdgeRule(startNodeType, targetNodeType) ){
			// We can use the node info in the order they were given
			return( key );
		}
		else {
			key = targetNodeType + "|" + startNodeType;
			if( EdgeRules.getInstance().hasEdgeRule(targetNodeType, startNodeType) ){
				return( key );
			}
			else {
				// Couldn't find a rule for this edge
				throw new AAIException("AAI_6120", "No EdgeRule found for passed nodeTypes: " + startNodeType + ", "
						+ targetNodeType); 
			}
		}
	}// end of deriveEdgeRuleKeyForThisEdge()
	

	/**
	 * Gets the edge tag prop put hash.
	 *
	 * @param transId the trans id
	 * @param fromAppId the from app id
	 * @param edgeRuleKey the edge rule key
	 * @return the edge tag prop put hash
	 * @throws AAIException the AAI exception
	 */
	public static Map<String, EdgeRule> getEdgeTagPropPutHash(String transId, String fromAppId, String edgeRuleKey )
			throws AAIException {
		// For a given edgeRuleKey (nodeTypeA|nodeTypeB), look up the rule that goes with it in
		// DbEdgeRules.EdgeRules and parse out the "tags" that need to be set on each edge.  
		// These are the Boolean properties like, "isParent", "usesResource" etc.  
		// Note - this code is also used by the updateEdgeTags.java code

		String[] edgeRuleKeys = edgeRuleKey.split("\\|");
		
		if (edgeRuleKeys.length < 2 || ! EdgeRules.getInstance().hasEdgeRule(edgeRuleKeys[0], edgeRuleKeys[1])) {
			throw new AAIException("AAI_6120", "Could not find an DbEdgeRule entry for passed edgeRuleKey (nodeTypeA|nodeTypeB): " + edgeRuleKey + ".");
		}
		
		Map<String, EdgeRule> edgeRules = EdgeRules.getInstance().getEdgeRules(edgeRuleKeys[0], edgeRuleKeys[1]);
		
		return edgeRules;
		
	} // End of getEdgeTagPropPutHash()

}