aboutsummaryrefslogtreecommitdiffstats
path: root/ajsc-aai/src/main/java/org/openecomp/aai/testing/LocateEndPoints.java
blob: 8803df890825366c835c26c06b6ba203116ec125 (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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/*-
 * ============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.testing;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.bind.JAXBException;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.openecomp.aai.audit.ListEndpoints;
import org.openecomp.aai.introspection.Introspector;
import org.openecomp.aai.introspection.IntrospectorFactory;
import org.openecomp.aai.introspection.Loader;
import org.openecomp.aai.introspection.LoaderFactory;
import org.openecomp.aai.introspection.ModelType;
import org.openecomp.aai.introspection.Version;
import org.openecomp.aai.logging.LogLineBuilder;

import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;

public class LocateEndPoints {

	private String restPath = "";
	private String pojoPath = "";
	
	private PopulateObject populator = null;
	private ArrayList<String> parentEndPoints = null;
	private ArrayList<String> childEndPoints = null;
	private final Pattern parentPattern = Pattern.compile("\\/(?:[\\w\\-]+?\\/)+?(?:\\{[\\w\\-]+?\\}\\/?)+");

	private Map<String, List<String>> deprecatedEndpoints = new HashMap<>();
	private Pattern apiVersionPattern =  Pattern.compile("\\/(v\\d+)\\/");
	private Version version = null;
	private ModelType modelType = ModelType.MOXY;
	private Loader loader = null;
	protected final LogLineBuilder llBuilder = new LogLineBuilder();

	/**
	 * Instantiates a new locate end points.
	 *
	 * @param version the version
	 * @throws FileNotFoundException the file not found exception
	 * @throws JSONException the JSON exception
	 */
	public LocateEndPoints (Version version) throws FileNotFoundException, JSONException {

		this.version = version;
		populator = new PopulateObject();
		loader = LoaderFactory.createLoaderForVersion(modelType, version, llBuilder);
		this.parentEndPoints = new ArrayList<>();
		this.childEndPoints = new ArrayList<>();
		String[] versions = {"v2","v3", "v4", "v5"};
		deprecatedEndpoints.put("site-pair-set", Arrays.asList(versions));

		this.process();
		
	}
	
	/**
	 * Instantiates a new locate end points.
	 */
	@SuppressWarnings("unused")
	private LocateEndPoints() {}
	
	/**
	 * Process.
	 */
	private void process(){

		ListEndpoints endpoints = new ListEndpoints(this.version);
		String filterOut = "relationship-list";
		List<String> uris = endpoints.getEndpoints(filterOut);
		
		for (String uri : uris) {
			this.addEndPointName(uri);
		}

	}
	
	/**
	 * Checks if is deprecated.
	 *
	 * @param name the name
	 * @return true, if is deprecated
	 */
	private boolean isDeprecated(String name) {

		Matcher m = apiVersionPattern.matcher(name);
		name = name.substring(name.lastIndexOf('.') + 1, name.length());
		String apiVersion = "";
		
		if (m.find()) {
			apiVersion = m.group(1);
		}
		for (String key : deprecatedEndpoints.keySet()) {
			if (name.contains(key)) {
				List<String> deprecatedVersions = this.deprecatedEndpoints.get(key);
				
				if (deprecatedVersions != null && deprecatedVersions.contains(apiVersion)) {
					return true;
				}
			}
		}
	
		return false;
	}

	/**
	 * Gets the parent paths.
	 *
	 * @return the parent paths
	 */
	public List<String> getParentPaths() {
		
		return (List<String>)this.parentEndPoints.clone();
	}
	
	/**
	 * Gets the child paths.
	 *
	 * @return the child paths
	 */
	public List<String> getChildPaths() {
		
		return (List<String>)this.childEndPoints.clone();
	}
	
	/**
	 * Gets the all paths.
	 *
	 * @return the all paths
	 */
	public List<String> getAllPaths() {
		List<String> returnList = new ArrayList<>();
		returnList.addAll(getParentPaths());
		returnList.addAll(getChildPaths());
		return returnList;
	}
	
	/**
	 * Adds the end point name.
	 *
	 * @param path the path
	 */
	private void addEndPointName(String path) {
		
		if (!this.isDeprecated(path)) {
			if (parentPattern.matcher(path).matches()) {
				parentEndPoints.add(path);		
			} else {
				childEndPoints.add(path);
			}
		}
	}
	
	/**
	 * Child path.
	 *
	 * @param path the path
	 * @return the string
	 */
	public String childPath(String path) {
		
		String childPath = "";
		String[] pathSegments = path.split("/");
		boolean foundNonVariable = false;
		for (int i = pathSegments.length-1; i >= 0; i--) {
			
			if (!foundNonVariable && pathSegments[i].contains("{")) {
				childPath = pathSegments[i] + "/" + childPath;
			} else if (foundNonVariable && pathSegments[i].contains("{")) {
				break;
			} else {
				foundNonVariable = true;
				childPath = pathSegments[i] + "/" + childPath;
			}
			
		}
		
		childPath = childPath.substring(0, childPath.length()-1).replace("//", "/");
		
		return childPath;
		
	}
	
	/**
	 * Creates the child for path.
	 *
	 * @param path the path
	 * @param min the min
	 * @param max the max
	 * @return the introspector
	 * @throws IllegalAccessException the illegal access exception
	 * @throws IllegalArgumentException the illegal argument exception
	 * @throws InvocationTargetException the invocation target exception
	 * @throws InstantiationException the instantiation exception
	 * @throws JSONException the JSON exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws JAXBException the JAXB exception
	 */
	public Introspector createChildForPath(String path, int min, int max) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, JSONException, IOException, JAXBException {
		return createChildForPath(path, min, max, false);
	}
	
	/**
	 * Creates the child for path.
	 *
	 * @param path the path
	 * @param min the min
	 * @param max the max
	 * @param minimized the minimized
	 * @return the introspector
	 * @throws IllegalAccessException the illegal access exception
	 * @throws IllegalArgumentException the illegal argument exception
	 * @throws InvocationTargetException the invocation target exception
	 * @throws InstantiationException the instantiation exception
	 * @throws JSONException the JSON exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws JAXBException the JAXB exception
	 */
	public Introspector createChildForPath(String path, int min, int max, boolean minimized) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, JSONException, IOException, JAXBException {
		Pattern p = Pattern.compile("([\\w\\-]+?)\\/(\\{[\\w\\-]+?\\}\\/?)+$");
		Matcher m = p.matcher(path);
		String objectName = "";
		if (m.find()) {
			objectName = m.group(1);
		}
		if (objectName.equals("cvlan-tag")) {
			objectName = "cvlan-tag-entry";
		}
		
		return createChildFromClassName(objectName, min, max, minimized);
	}
	
	/**
	 * Creates the child from class name.
	 *
	 * @param objectName the object name
	 * @param min the min
	 * @param max the max
	 * @return the introspector
	 * @throws IllegalAccessException the illegal access exception
	 * @throws IllegalArgumentException the illegal argument exception
	 * @throws InvocationTargetException the invocation target exception
	 * @throws InstantiationException the instantiation exception
	 * @throws JSONException the JSON exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws JAXBException the JAXB exception
	 */
	public Introspector createChildFromClassName(String objectName, int min, int max) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, JSONException, IOException, JAXBException {
		return createChildFromClassName(objectName, min, max, false);
	}
	
	/**
	 * Creates the child from class name.
	 *
	 * @param objectName the object name
	 * @param min the min
	 * @param max the max
	 * @param minimized the minimized
	 * @return the introspector
	 * @throws IllegalAccessException the illegal access exception
	 * @throws IllegalArgumentException the illegal argument exception
	 * @throws InvocationTargetException the invocation target exception
	 * @throws InstantiationException the instantiation exception
	 * @throws JSONException the JSON exception
	 * @throws IOException Signals that an I/O exception has occurred.
	 * @throws JAXBException the JAXB exception
	 */
	public Introspector createChildFromClassName(String objectName, int min, int max, boolean minimized) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, JSONException, IOException, JAXBException {
		Introspector returnObject = null;
	
		returnObject = loader.introspectorFromName(objectName);
		populator.populateRecursively(returnObject, min, max, minimized);
		
		
		return returnObject;
	}
	
	/**
	 * Populate relationship.
	 *
	 * @param parent the parent
	 * @param dbName the db name
	 * @param fullPath the full path
	 * @return the introspector
	 */
	public Introspector populateRelationship(Introspector parent, String dbName, String fullPath) {
		
		String formattedClassName = parent.getDbName();
		
		String advancedPath = StringUtils.substringAfter(fullPath, formattedClassName + "/");
		String[] pathTokens = advancedPath.split("/");
		
		// Create and format the relationship
		Introspector relationship = loader.introspectorFromName("relationship");
		relationship.setValue("related-to", dbName);
		populateRelationshipHelper(parent, pathTokens, 0, relationship);
		
		return relationship;
	}
	
	/**
	 * Populate relationship helper.
	 *
	 * @param parent the parent
	 * @param pathTokens the path tokens
	 * @param index the index
	 * @param relationship the relationship
	 */
	// Recursively iterate through each token and add the necessary information to the relationship data array
	private void populateRelationshipHelper(Introspector parent, String[] pathTokens, int index, Introspector relationship) {
		Pattern p = Pattern.compile("\\{(.+?)\\}");
		for(int i = index; i < pathTokens.length; ++i) {
			Matcher m = p.matcher(pathTokens[i]);
			if(m.find()) {
				String pathVariable = m.group(1);
				String trimmedClassName = parent.getDbName();
				pathVariable = pathVariable.replaceFirst(trimmedClassName+ "-", "");
				String key = this.callGetMethod(parent, pathVariable).toString();
				pathTokens[i] = pathTokens[i].replaceAll("\\{.+?\\}", key);
				
				// Add the relationship data object from token information
				Introspector data = relationship.newIntrospectorInstanceOfNestedProperty("relationship-data");
				data.setValue("relationship-key", trimmedClassName + "." + pathVariable);
				data.setValue("relationship-value", key);
				((List)relationship.getValue("relationship-data")).add(data.getUnderlyingObject());
				if (i == pathTokens.length-1) {
					List<Introspector> relatedTos = new ArrayList<>();
					String nameProps = parent.getMetadata("nameProps");
					if (nameProps != null) {
						String[] props = nameProps.split(",");
						for (String prop : props) {
							Introspector relatedTo = this.loader.introspectorFromName("related-to-property");
							relatedTo.setValue("property-key", parent.getDbName() + "." + prop);
							relatedTo.setValue("property-value", parent.getValue(prop));
							relatedTos.add(relatedTo);
						}
						
						if (relatedTos.size() > 0) {
							List list = (List)relationship.getValue("related-to-property");
							for (Introspector obj : relatedTos) {
								list.add(obj.getUnderlyingObject());
							}
						}
					}
				}
			} else {
				String getMethodName;
				if (pathTokens[i].equals("cvlan-tag")) {
					getMethodName = "cvlan-tag-entry";
				} else {
					getMethodName = pathTokens[i];
				}
				Object child = this.callGetMethod(parent, getMethodName);
				if (child != null) {
					if (child.getClass().getName().contains("List")) {
						child = ((List)child).get(0);
					}
					populateRelationshipHelper(IntrospectorFactory.newInstance(parent.getModelType(), child, llBuilder), pathTokens, i+1, relationship);
					break;
				}
			}
		}
	}
	
	/**
	 * Populate path.
	 *
	 * @param parent the parent
	 * @param path the path
	 * @return the list
	 * @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
	 */
	public List<Object> populatePath(Introspector parent, String path) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		
		String formattedClassName = parent.getDbName();

		String prefix = StringUtils.substringBefore(path, "{");
		String advancedPath = StringUtils.substringAfter(path, formattedClassName+"/");
		String[] pathTokens = advancedPath.split("/");
		
		Introspector end = populatePathHelper(parent, pathTokens, 0);
		String parentPath = prefix + Joiner.on("/").join(pathTokens);
		List<Object> result = new ArrayList<>();
		result.add(parentPath);
		result.add(end.clone());
		return result;
	}
	
	/**
	 * Populate child path.
	 *
	 * @param topLevelObj the top level obj
	 * @param obj the obj
	 * @param path the path
	 * @return the string
	 * @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
	 */
	public String populateChildPath(Introspector topLevelObj, Introspector obj, String path) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
		String childPath = "/" + this.childPath(path);
		String parentPath = path.replace(childPath, "");
		String resultPath = (String)this.populatePath(topLevelObj, parentPath).get(0) + (String)this.populatePath(obj, childPath).get(0);
		
		return resultPath;
	}
	
	/**
	 * Populate path helper.
	 *
	 * @param parent the parent
	 * @param pathTokens the path tokens
	 * @param index the index
	 * @return the introspector
	 */
	private Introspector populatePathHelper(Introspector parent, String[] pathTokens, int index) {

		Pattern p = Pattern.compile("\\{(.+?)\\}");
		Matcher m = null;
		String pathVariable = "";
		String key = "";
		Object child = null;
		String getMethodName = "";
		for (int i = index; i < pathTokens.length; i++) {
			m = p.matcher(pathTokens[i]);
			if (m.find()) {
				pathVariable = m.group(1);
				
				pathVariable = pathVariable.replaceFirst(parent.getDbName() + "-", "");
				
				key = this.callGetMethod(parent, pathVariable).toString();
				pathTokens[i] = pathTokens[i].replaceAll("\\{.+?\\}", key);
			} else {
				
				if (pathTokens[i].equals("cvlan-tag")) {
					getMethodName = "cvlan-tag-entry";
				} else {
					getMethodName = pathTokens[i];
				}
				child = this.callGetMethod(parent, getMethodName);
				if (child != null) {
					if (child.getClass().getName().contains("List")) {
						child = ((List)child).get(0);
					}
					return populatePathHelper(IntrospectorFactory.newInstance(parent.getModelType(), child, llBuilder), pathTokens, i+1);
				}
			}
		}
		
		return parent;
	}
	
	/**
	 * Gets the path for object.
	 *
	 * @param parentPath the parent path
	 * @param obj the obj
	 * @return the path for object
	 */
	public String getPathForObject(String parentPath, Object obj) {
		
		String name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, this.trimClassName(obj));
		String result = "";
		Pattern p = Pattern.compile(".*?\\/" + name + "\\/\\{.*?\\}");
		Matcher m = null;
		for (String childPath : this.childEndPoints) {
			
			m = p.matcher(childPath);
			if (m.find()) {
				result = m.group();
				break;
			}
			
		}
		
		return result;
		
	}

	/**
	 * Format path string.
	 *
	 * @param item the item
	 * @return the string
	 */
	private String formatPathString(String item) {
		
		String value = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, item);
		
		return value;
	}
	
	/**
	 * Call get method.
	 *
	 * @param obj the obj
	 * @param variableName the variable name
	 * @return the object
	 */
	private Object callGetMethod(Introspector obj, String variableName) {
		Object key = null;
		
		key = obj.getValue(variableName);
	
		return key;
	}
	
	/**
	 * Make singular.
	 *
	 * @param word the word
	 * @return the string
	 */
	private String makeSingular(String word) {
		
		String result = word;
		result = result.replaceAll("ies$", "y");
		result = result.replaceAll("(?:s|([hox])es)$", "$1");
		
		return result;
	}
	
	/**
	 * Trim class name.
	 *
	 * @param obj the obj
	 * @return the string
	 */
	public String trimClassName (Object obj) {
		String returnValue = "";
		String name = obj.getClass().getName();
		returnValue = name.substring(name.lastIndexOf('.') + 1, name.length());
	
		if (returnValue.equals("CvlanTagEntry")) {
			returnValue = "CvlanTag";
		}
		return returnValue;
	}

	
	
}