diff options
author | 2017-09-28 12:43:08 -0400 | |
---|---|---|
committer | 2017-09-28 13:29:27 -0400 | |
commit | 1767960099ea2983eef5218b8ce44b167ae0774c (patch) | |
tree | 4efe13601c1f9ebebc6026b32ec749778cd96caf /aai-core/src/main/java/org/openecomp | |
parent | a8a05641920545aa094dffdb016b7b5febe9a879 (diff) |
Change openecomp to onap and update license
Issue-ID: AAI-61 AAI-82
Change-Id: Iae98d4bf4c693c0a3203158bff98c3c5e739f453
Signed-off-by: Venkata Harish K Kajur <vk250x@att.com>
Diffstat (limited to 'aai-core/src/main/java/org/openecomp')
221 files changed, 0 insertions, 34525 deletions
diff --git a/aai-core/src/main/java/org/openecomp/aai/audit/ListEndpoints.java b/aai-core/src/main/java/org/openecomp/aai/audit/ListEndpoints.java deleted file mode 100644 index 1e1df8fc..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/audit/ListEndpoints.java +++ /dev/null @@ -1,302 +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.audit; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang.StringUtils; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; - -/** - * The Class ListEndpoints. - */ -public class ListEndpoints { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ListEndpoints.class); - - private final String start = "inventory"; - private final String[] blacklist = { "search", "aai-internal" }; - - private List<String> endpoints = new ArrayList<>(); - private Map<String, String> endpointToLogicalName = new HashMap<String, String>(); - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - ListEndpoints endPoints = new ListEndpoints(AAIProperties.LATEST); - - System.out.println(endPoints.toString("relationship-list")); - - } - - /** - * Instantiates a new list endpoints. - * - * @param version the version - */ - public ListEndpoints(Version version) { - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); - - try { - final Introspector start = loader.introspectorFromName(this.start); - Set<String> startMap = new HashSet<>(); - beginAudit(start, "/aai/" + version, startMap); - } catch (AAIUnknownObjectException e) { - throw new RuntimeException("Failed to find object " + this.start + ", cannot run ListEndpoints audit"); - } - } - - /** - * Begin audit. - * - * @param obj the obj - * @param uri the uri - */ - private void beginAudit(Introspector obj, String uri, Set<String> visited) { - - String currentUri = ""; - - if (!obj.getDbName().equals("inventory")) { - currentUri = uri + obj.getGenericURI(); - } else { - currentUri = uri; - } - if (obj.getName().equals("relationship-data") || obj.getName().equals("related-to-property")) { - return; - } - if (!obj.isContainer()) { - endpoints.add(currentUri); - } - - String dbName = obj.getDbName(); - - populateLogicalName(obj, uri, currentUri); - - Set<String> properties = obj.getProperties(); - Set<String> props = new LinkedHashSet<>(properties); - if (obj.isContainer()) { - for (String key : visited) { - if (props.remove(key)) { - try { - endpoints.add(currentUri + obj.getLoader().introspectorFromName(key).getGenericURI()); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping endpoint for " + key + " (Unknown object)", e); - } - } - } - } - - outer: for (String propName : props) { - - for (String item : blacklist) { - if (propName.equals(item)) { - continue outer; - } - } - if (obj.isListType(propName)) { - if (obj.isComplexGenericType(propName)) { - try { - final Introspector nestedObj = obj.newIntrospectorInstanceOfNestedProperty(propName); - Set<String> newVisited = new HashSet<>(); - newVisited.addAll(visited); - newVisited.add(nestedObj.getDbName()); - beginAudit( - nestedObj, - currentUri, - newVisited - ); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping nested endpoint for " + propName + " (Unknown Object)", e); - } - } - } else if (obj.isComplexType(propName)) { - try { - final Introspector nestedObj = obj.newIntrospectorInstanceOfProperty(propName); - Set<String> newVisited = new HashSet<>(); - newVisited.addAll(visited); - newVisited.add(nestedObj.getDbName()); - beginAudit(nestedObj, - currentUri, - visited - ); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping nested enpoint for " + propName + " (Unknown Object)", e); - } - } - } - - } - - /** - * Populate logical name. - * - * @param obj the obj - * @param uri the uri - * @param currentUri the current uri - */ - private void populateLogicalName(Introspector obj, String uri, String currentUri) { - - if (obj.getDbName().equals("inventory") || currentUri.split("/").length <= 4 || currentUri.endsWith("relationship-list")) { - return; - } - - if (uri.endsWith("/relationship-list")) { - uri = uri.substring(0, uri.lastIndexOf("/")); - } - - String logicalName = ""; - String keys = ""; - - - if (!obj.getAllKeys().isEmpty()) { - - Pattern p = Pattern.compile("/\\{[\\w\\d\\-]+\\}/\\{[\\w\\d\\-]+\\}+$"); - Matcher m = p.matcher(currentUri); - - if (m.find()) { - keys = StringUtils.join(obj.getAllKeys(), "-and-"); - } else { - keys = StringUtils.join(obj.getAllKeys(), "-or-"); - } - keys = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, keys); - if (!keys.isEmpty()) { - keys = "With" + keys; - } - } - - logicalName = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, obj.getDbName()) + keys; - - if (endpointToLogicalName.containsKey(uri) && uri.endsWith("}")) { - logicalName = logicalName + "From" + endpointToLogicalName.get(uri); - } else if (endpointToLogicalName.containsKey(uri.substring(0, uri.lastIndexOf("/")))) { - logicalName = logicalName + "From" + endpointToLogicalName.get(uri.substring(0, uri.lastIndexOf("/"))); - } - - endpointToLogicalName.put(currentUri, logicalName); - - } - - /** - * Gets the logical names. - * - * @return the logical names - */ - public Map<String, String> getLogicalNames() { - - return endpointToLogicalName; - - } - - /** - * Gets the endpoints. - * - * @return the endpoints - */ - public List<String> getEndpoints() { - - return this.getEndpoints(""); - - } - - /** - * Gets the endpoints. - * - * @param filterOut the filter out - * @return the endpoints - */ - public List<String> getEndpoints(String filterOut) { - List<String> result = new ArrayList<>(); - Pattern p = null; - Matcher m = null; - if (!filterOut.equals("")) { - p = Pattern.compile(filterOut); - m = null; - } - for (String s : endpoints) { - if (p != null) { - m = p.matcher(s); - if (m.find()) { - continue; - } - } - - result.add(s); - } - - return result; - - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - for (String s : endpoints) { - sb.append(s + "\n"); - } - return sb.toString(); - - } - - /** - * To string. - * - * @param filterOut the filter out - * @return the string - */ - public String toString(String filterOut) { - StringBuilder sb = new StringBuilder(); - Pattern p = Pattern.compile(filterOut); - Matcher m = null; - for (String s : endpoints) { - m = p.matcher(s); - if (!m.find()) { - sb.append(s + "\n"); - } - } - return sb.toString(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java b/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java deleted file mode 100644 index 5a3d8c6b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/auth/exceptions/AAIUnrecognizedFunctionException.java +++ /dev/null @@ -1,42 +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.auth.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIUnrecognizedFunctionException extends AAIException { - - private static final long serialVersionUID = 3297064867724071290L; - - public AAIUnrecognizedFunctionException() {} - - public AAIUnrecognizedFunctionException(String message) { - super("AAI_3012", message); - } - - public AAIUnrecognizedFunctionException(Throwable cause) { - super("AAI_3012",cause); - } - - public AAIUnrecognizedFunctionException(String message, Throwable cause) { - super("AAI_3012", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/DbMethHelper.java b/aai-core/src/main/java/org/openecomp/aai/db/DbMethHelper.java deleted file mode 100644 index 79172d9b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/DbMethHelper.java +++ /dev/null @@ -1,158 +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.db; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.relationship.RelationshipToURI; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -public class DbMethHelper { - - private final Loader loader; - private final TransactionalGraphEngine engine; - - protected DbMethHelper() { - this.loader = null; - this.engine = null; - } - public DbMethHelper(Loader loader, TransactionalGraphEngine engine) { - this.loader = loader; - this.engine = engine; - } - /** - * - * @param type - * @param map - form [{type}.{propname}:{value}] - * @return - * @throws UnsupportedEncodingException - * @throws AAIException - */ - public Optional<Vertex> searchVertexByIdentityMap(String type, Map<String, Object> map) throws AAIException { - - Introspector relationship = constructRelationship(type, map); - RelationshipToURI parser; - URI uri; - QueryParser queryParser; - try { - parser = new RelationshipToURI(loader, relationship); - uri = parser.getUri(); - queryParser = this.engine.getQueryBuilder().createQueryFromURI(uri); - } catch (UnsupportedEncodingException e) { - throw new AAIException("AAI_3000"); - } - - List<Vertex> results = queryParser.getQueryBuilder().toList(); - - return reduceToSingleVertex(results, map); - } - - /** - * @param type - * @param map - form [{propname}:{value}] - * @return - * @throws AAIException - */ - public Optional<Vertex> locateUniqueVertex(String type, Map<String, Object> map) throws AAIException { - - return reduceToSingleVertex(locateUniqueVertices(type, map), map); - } - - public List<Vertex> locateUniqueVertices(String type, Map<String, Object> map) throws AAIException { - Introspector obj = this.createIntrospectorFromMap(type, map); - QueryBuilder builder = this.engine.getQueryBuilder().exactMatchQuery(obj); - - return builder.toList(); - } - private Introspector constructRelationship(String type, Map<String, Object> map) throws AAIUnknownObjectException { - final Introspector relationship = loader.introspectorFromName("relationship"); - relationship.setValue("related-to", type); - final List<Object> data = relationship.getValue("relationship-data"); - for (Entry<String, Object> entry : map.entrySet()) { - final Introspector dataObj = loader.introspectorFromName("relationship-data"); - dataObj.setValue("relationship-key", entry.getKey()); - dataObj.setValue("relationship-value", entry.getValue()); - data.add(dataObj.getUnderlyingObject()); - } - - return relationship; - } - - private Introspector createIntrospectorFromMap(String targetNodeType, Map<String, Object> propHash) throws AAIUnknownObjectException { - final Introspector result = loader.introspectorFromName(targetNodeType); - for (Entry<String, Object> entry : propHash.entrySet()) { - result.setValue(entry.getKey(), entry.getValue()); - } - return result; - } - - private Optional<Vertex> reduceToSingleVertex(List<Vertex> vertices, Map<String, Object> map) throws AAIException { - if (vertices.isEmpty()){ - return Optional.empty(); - } else if (vertices.size() > 1) { - throw new AAIException("AAI_6112", "More than one Node found by getUniqueNode for params: " + map); - } - - return Optional.of(vertices.get(0)); - } - public List<String> getVertexProperties(Vertex v) { - List<String> retArr = new ArrayList<>(); - if( v == null ){ - retArr.add("null Node object passed to showPropertiesForNode()\n"); - } - else { - String nodeType; - Object ob = v.<Object>property("aai-node-type").orElse(null); - if( ob == null ){ - nodeType = "null"; - } - else{ - nodeType = ob.toString(); - } - - retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + v.id() + "]"); - retArr.add(" Property Detail: "); - Iterator<VertexProperty<Object>> pI = v.properties(); - while( pI.hasNext() ){ - VertexProperty<Object> tp = pI.next(); - Object val = tp.value(); - retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] "); - } - } - return retArr; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java b/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java deleted file mode 100644 index caac6744..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/props/AAIProperties.java +++ /dev/null @@ -1,39 +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.db.props; - -import org.openecomp.aai.introspection.Version; - -public class AAIProperties { - public static final String NODE_TYPE = "aai-node-type"; - public static final String LAST_MOD_SOURCE_OF_TRUTH = "last-mod-source-of-truth"; - public static final String SOURCE_OF_TRUTH = "source-of-truth"; - public static final String LAST_MOD_TS = "aai-last-mod-ts"; - public static final String UNIQUE_KEY = "aai-unique-key"; - public static final String CREATED_TS = "aai-created-ts"; - public static final String RESOURCE_VERSION = "resource-version"; - public static final String AAI_URI = "aai-uri"; - public static final Version LATEST = Version.v11; - public static final Integer MAXIMUM_DEPTH = 10000; - public static final String LINKED = "linked"; - public static final String DB_ALIAS_SUFFIX = "-local"; - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditDoc.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditDoc.java deleted file mode 100644 index 58d3dc0b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditDoc.java +++ /dev/null @@ -1,89 +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.db.schema; - -import java.util.List; - -import org.codehaus.jackson.annotate.JsonProperty; - -public class AuditDoc { - - private List<DBProperty> properties; - private List<DBIndex> indexes; - private List<EdgeProperty> edgeLabels; - - /** - * Gets the properties. - * - * @return the properties - */ - public List<DBProperty> getProperties() { - return properties; - } - - /** - * Sets the properties. - * - * @param properties the new properties - */ - public void setProperties(List<DBProperty> properties) { - this.properties = properties; - } - - /** - * Gets the indexes. - * - * @return the indexes - */ - public List<DBIndex> getIndexes() { - return indexes; - } - - /** - * Sets the indexes. - * - * @param indexes the new indexes - */ - public void setIndexes(List<DBIndex> indexes) { - this.indexes = indexes; - } - - /** - * Gets the edge labels. - * - * @return the edge labels - */ - @JsonProperty("edge-labels") - public List<EdgeProperty> getEdgeLabels() { - return edgeLabels; - } - - /** - * Sets the edge labels. - * - * @param edgeLabels the new edge labels - */ - public void setEdgeLabels(List<EdgeProperty> edgeLabels) { - this.edgeLabels = edgeLabels; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditOXM.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditOXM.java deleted file mode 100644 index b7aab081..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditOXM.java +++ /dev/null @@ -1,249 +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.db.schema; - -import java.io.IOException; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.util.AAIConstants; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.collect.Multimap; -import com.thinkaurelius.titan.core.Cardinality; -import com.thinkaurelius.titan.core.Multiplicity; -import com.thinkaurelius.titan.core.schema.SchemaStatus; - -public class AuditOXM extends Auditor { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AuditOXM.class); - - private Set<Introspector> allObjects; - - /** - * Instantiates a new audit OXM. - * - * @param version the version - */ - public AuditOXM(Version version) { - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); - Set<String> objectNames = getAllObjects(version); - allObjects = new HashSet<>(); - for (String key : objectNames) { - try { - final Introspector temp = loader.introspectorFromName(key); - allObjects.add(temp); - this.createDBProperties(temp); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping audit for object " + key + " (Unknown Object)", e); - } - } - for (Introspector temp : allObjects) { - this.createDBIndexes(temp); - } - createEdgeLabels(); - - } - - /** - * Gets the all objects. - * - * @param version the version - * @return the all objects - */ - private Set<String> getAllObjects(Version version) { - String fileName = AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + version.toString() + ".xml"; - Set<String> result = new HashSet<>(); - DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - try { - docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - Document doc = docBuilder.parse(fileName); - NodeList list = doc.getElementsByTagName("java-type"); - for (int i = 0; i < list.getLength(); i++) { - result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue()); - } - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (SAXException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - result.remove("EdgePropNames"); - return result; - - } - - /** - * Creates the DB properties. - * - * @param temp the temp - */ - private void createDBProperties(Introspector temp) { - Set<String> objectProperties = temp.getProperties(); - - for (String prop : objectProperties) { - if (!properties.containsKey(prop)) { - DBProperty dbProperty = new DBProperty(); - dbProperty.setName(prop); - if (temp.isListType(prop)) { - dbProperty.setCardinality(Cardinality.SET); - if (temp.isSimpleGenericType(prop)) { - Class<?> clazz = null; - try { - clazz = Class.forName(temp.getGenericType(prop)); - } catch (ClassNotFoundException e) { - clazz = Object.class; - } - dbProperty.setTypeClass(clazz); - properties.put(prop, dbProperty); - } - } else { - dbProperty.setCardinality(Cardinality.SINGLE); - if (temp.isSimpleType(prop)) { - Class<?> clazz = null; - try { - clazz = Class.forName(temp.getType(prop)); - } catch (ClassNotFoundException e) { - clazz = Object.class; - } - dbProperty.setTypeClass(clazz); - properties.put(prop, dbProperty); - } - } - } - } - - } - - /** - * Creates the DB indexes. - * - * @param temp the temp - */ - private void createDBIndexes(Introspector temp) { - String uniqueProps = temp.getMetadata(ObjectMetadata.UNIQUE_PROPS); - String namespace = temp.getMetadata(ObjectMetadata.NAMESPACE); - if (uniqueProps == null) { - uniqueProps = ""; - } - if (namespace == null) { - namespace = ""; - } - boolean isTopLevel = namespace != ""; - List<String> unique = Arrays.asList(uniqueProps.split(",")); - Set<String> indexed = temp.getIndexedProperties(); - Set<String> keys = temp.getKeys(); - - for (String prop : indexed) { - DBIndex dbIndex = new DBIndex(); - LinkedHashSet<DBProperty> properties = new LinkedHashSet<>(); - if (!this.indexes.containsKey(prop)) { - dbIndex.setName(prop); - dbIndex.setUnique(unique.contains(prop)); - properties.add(this.properties.get(prop)); - dbIndex.setProperties(properties); - dbIndex.setStatus(SchemaStatus.ENABLED); - this.indexes.put(prop, dbIndex); - } - } - if (keys.size() > 1 || isTopLevel) { - DBIndex dbIndex = new DBIndex(); - LinkedHashSet<DBProperty> properties = new LinkedHashSet<>(); - dbIndex.setName("key-for-" + temp.getDbName()); - if (!this.indexes.containsKey(dbIndex.getName())) { - boolean isUnique = false; - if (isTopLevel) { - properties.add(this.properties.get(AAIProperties.NODE_TYPE)); - } - for (String key : keys) { - properties.add(this.properties.get(key)); - - if (unique.contains(key) && !isUnique) { - isUnique = true; - } - } - dbIndex.setUnique(isUnique); - dbIndex.setProperties(properties); - dbIndex.setStatus(SchemaStatus.ENABLED); - this.indexes.put(dbIndex.getName(), dbIndex); - } - } - - } - - /** - * Creates the edge labels. - */ - private void createEdgeLabels() { - Multimap<String, EdgeRule> edgeRules = EdgeRules.getInstance().getAllRules(); - for (String key : edgeRules.keySet()) { - Collection<EdgeRule> collection = edgeRules.get(key); - EdgeProperty prop = new EdgeProperty(); - //there is only ever one, they used the wrong type for EdgeRules - String label = ""; - for (EdgeRule item : collection) { - label = item.getLabel(); - } - prop.setName(label); - prop.setMultiplicity(Multiplicity.MULTI); - this.edgeLabels.put(label, prop); - } - } - - /** - * Gets the all introspectors. - * - * @return the all introspectors - */ - public Set<Introspector> getAllIntrospectors() { - return this.allObjects; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditTitan.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditTitan.java deleted file mode 100644 index 838a9b60..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditTitan.java +++ /dev/null @@ -1,123 +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.db.schema; - - -import java.util.Iterator; -import java.util.LinkedHashSet; - -import org.apache.tinkerpop.gremlin.structure.Vertex; - -import com.thinkaurelius.titan.core.EdgeLabel; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; - -public class AuditTitan extends Auditor { - - private final TitanGraph graph; - - /** - * Instantiates a new audit titan. - * - * @param g the g - */ - public AuditTitan (TitanGraph g) { - this.graph = g; - buildSchema(); - } - - /** - * Builds the schema. - */ - private void buildSchema() { - populateProperties(); - populateIndexes(); - populateEdgeLabels(); - } - - /** - * Populate properties. - */ - private void populateProperties() { - TitanManagement mgmt = graph.openManagement(); - Iterable<PropertyKey> iterable = mgmt.getRelationTypes(PropertyKey.class); - Iterator<PropertyKey> titanProperties = iterable.iterator(); - PropertyKey propKey; - while (titanProperties.hasNext()) { - propKey = titanProperties.next(); - DBProperty prop = new DBProperty(); - - prop.setName(propKey.name()); - prop.setCardinality(propKey.cardinality()); - prop.setTypeClass(propKey.dataType()); - - this.properties.put(prop.getName(), prop); - } - } - - /** - * Populate indexes. - */ - private void populateIndexes() { - TitanManagement mgmt = graph.openManagement(); - Iterable<TitanGraphIndex> iterable = mgmt.getGraphIndexes(Vertex.class); - Iterator<TitanGraphIndex> titanIndexes = iterable.iterator(); - TitanGraphIndex titanIndex; - while (titanIndexes.hasNext()) { - titanIndex = titanIndexes.next(); - if (titanIndex.isCompositeIndex()) { - DBIndex index = new DBIndex(); - LinkedHashSet<DBProperty> dbProperties = new LinkedHashSet<>(); - index.setName(titanIndex.name()); - index.setUnique(titanIndex.isUnique()); - PropertyKey[] keys = titanIndex.getFieldKeys(); - for (PropertyKey key : keys) { - dbProperties.add(this.properties.get(key.name())); - } - index.setProperties(dbProperties); - index.setStatus(titanIndex.getIndexStatus(keys[0])); - this.indexes.put(index.getName(), index); - } - } - } - - /** - * Populate edge labels. - */ - private void populateEdgeLabels() { - TitanManagement mgmt = graph.openManagement(); - Iterable<EdgeLabel> iterable = mgmt.getRelationTypes(EdgeLabel.class); - Iterator<EdgeLabel> titanEdgeLabels = iterable.iterator(); - EdgeLabel edgeLabel; - while (titanEdgeLabels.hasNext()) { - edgeLabel = titanEdgeLabels.next(); - EdgeProperty edgeProperty = new EdgeProperty(); - - edgeProperty.setName(edgeLabel.name()); - edgeProperty.setMultiplicity(edgeLabel.multiplicity()); - - this.edgeLabels.put(edgeProperty.getName(), edgeProperty); - } - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/Auditor.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/Auditor.java deleted file mode 100644 index cd811041..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/Auditor.java +++ /dev/null @@ -1,54 +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.db.schema; - -import java.util.*; - -public abstract class Auditor { - - protected Map<String, DBProperty> properties = new HashMap<>(); - protected Map<String, DBIndex> indexes = new HashMap<>(); - protected Map<String, EdgeProperty> edgeLabels = new HashMap<>(); - - /** - * Gets the audit doc. - * - * @return the audit doc - */ - public AuditDoc getAuditDoc() { - AuditDoc doc = new AuditDoc(); - List<DBProperty> propertyList = new ArrayList<>(); - List<DBIndex> indexList = new ArrayList<>(); - List<EdgeProperty> edgeLabelList = new ArrayList<>(); - propertyList.addAll(this.properties.values()); - indexList.addAll(this.indexes.values()); - edgeLabelList.addAll(this.edgeLabels.values()); - Collections.sort(propertyList, new CompareByName()); - Collections.sort(indexList, new CompareByName()); - Collections.sort(edgeLabelList, new CompareByName()); - - doc.setProperties(propertyList); - doc.setIndexes(indexList); - doc.setEdgeLabels(edgeLabelList); - - return doc; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditorFactory.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditorFactory.java deleted file mode 100644 index 66e52820..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/AuditorFactory.java +++ /dev/null @@ -1,47 +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.db.schema; - -import org.openecomp.aai.introspection.Version; -import com.thinkaurelius.titan.core.TitanGraph; - -public class AuditorFactory { - - /** - * Gets the OXM auditor. - * - * @param v the v - * @return the OXM auditor - */ - public static Auditor getOXMAuditor (Version v) { - return new AuditOXM(v); - } - - /** - * Gets the graph auditor. - * - * @param g the g - * @return the graph auditor - */ - public static Auditor getGraphAuditor (TitanGraph g) { - return new AuditTitan(g); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/CompareByName.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/CompareByName.java deleted file mode 100644 index ea45fd75..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/CompareByName.java +++ /dev/null @@ -1,36 +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.db.schema; - -import java.util.Comparator; - -public class CompareByName implements Comparator<Named>{ - - /** - * {@inheritDoc} - */ - @Override - public int compare(Named o1, Named o2) { - return o1.getName().compareTo(o2.getName()); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBIndex.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/DBIndex.java deleted file mode 100644 index 9e157a93..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBIndex.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.db.schema; - -import java.util.LinkedHashSet; -import java.util.Set; - -import com.thinkaurelius.titan.core.schema.SchemaStatus; - -public class DBIndex implements Named { - - private String name = null; - private boolean unique = false; - private LinkedHashSet<DBProperty> properties = new LinkedHashSet<>(); - private SchemaStatus status = null; - - /** - * Gets the name - */ - public String getName() { - return name; - } - - /** - * Sets the name. - * - * @param name the new name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Checks if is unique. - * - * @return true, if is unique - */ - public boolean isUnique() { - return unique; - } - - /** - * Sets the unique. - * - * @param unique the new unique - */ - public void setUnique(boolean unique) { - this.unique = unique; - } - - /** - * Gets the properties. - * - * @return the properties - */ - public Set<DBProperty> getProperties() { - return properties; - } - - /** - * Sets the properties. - * - * @param properties the new properties - */ - public void setProperties(LinkedHashSet<DBProperty> properties) { - this.properties = properties; - } - - /** - * Gets the status. - * - * @return the status - */ - public SchemaStatus getStatus() { - return status; - } - - /** - * Sets the status. - * - * @param status the new status - */ - public void setStatus(SchemaStatus status) { - this.status = status; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBProperty.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/DBProperty.java deleted file mode 100644 index d142e15b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/DBProperty.java +++ /dev/null @@ -1,85 +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.db.schema; - -import org.openecomp.aai.introspection.Introspector; -import com.thinkaurelius.titan.core.Cardinality; - -public class DBProperty implements Named { - - - private String name = null; - private Cardinality cardinality = null; - private Class<?> typeClass = null; - - /** - * Gets the name - */ - public String getName() { - return name; - } - - /** - * Sets the name. - * - * @param name the new name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Gets the cardinality. - * - * @return the cardinality - */ - public Cardinality getCardinality() { - return cardinality; - } - - /** - * Sets the cardinality. - * - * @param cardinality the new cardinality - */ - public void setCardinality(Cardinality cardinality) { - this.cardinality = cardinality; - } - - /** - * Gets the type class. - * - * @return the type class - */ - public Class<?> getTypeClass() { - return typeClass; - } - - /** - * Sets the type class. - * - * @param type the new type class - */ - public void setTypeClass(Class<?> type) { - this.typeClass = type; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/EdgeProperty.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/EdgeProperty.java deleted file mode 100644 index 0f9fafd3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/EdgeProperty.java +++ /dev/null @@ -1,69 +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.db.schema; - -import com.thinkaurelius.titan.core.Multiplicity; -import org.codehaus.jackson.annotate.JsonProperty; -import org.codehaus.jackson.annotate.JsonPropertyOrder; - -@JsonPropertyOrder({ "label", "multiplicity" }) -public class EdgeProperty implements Named { - - private String name = null; - private Multiplicity multiplicity = null; - - /** - * Gets the name - */ - @JsonProperty("label") - public String getName() { - return name; - } - - /** - * Sets the name. - * - * @param name the new name - */ - @JsonProperty("label") - public void setName(String name) { - this.name = name; - } - - /** - * Gets the multiplicity. - * - * @return the multiplicity - */ - public Multiplicity getMultiplicity() { - return multiplicity; - } - - /** - * Sets the multiplicity. - * - * @param multiplicity the new multiplicity - */ - public void setMultiplicity(Multiplicity multiplicity) { - this.multiplicity = multiplicity; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java deleted file mode 100644 index a7f835e6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/ManageTitanSchema.java +++ /dev/null @@ -1,329 +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.db.schema; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.structure.Vertex; - -import org.openecomp.aai.introspection.Version; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.SchemaStatus; -import com.thinkaurelius.titan.core.schema.TitanGraphIndex; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import com.thinkaurelius.titan.core.schema.TitanManagement.IndexBuilder; - -public class ManageTitanSchema { - - - private TitanManagement graphMgmt; - private TitanGraph graph; - private List<DBProperty> aaiProperties; - private List<DBIndex> aaiIndexes; - private List<EdgeProperty> aaiEdgeProperties; - private Auditor oxmInfo = null; - private Auditor graphInfo = null; - - /** - * Instantiates a new manage titan schema. - * - * @param graph the graph - */ - public ManageTitanSchema(final TitanGraph graph) { - this.graph = graph; - oxmInfo = AuditorFactory.getOXMAuditor(Version.v8); - graphInfo = AuditorFactory.getGraphAuditor(graph); - } - - - /** - * Builds the schema. - */ - public void buildSchema() { - - this.graphMgmt = graph.openManagement(); - aaiProperties = new ArrayList<>(); - aaiEdgeProperties = new ArrayList<>(); - aaiIndexes = new ArrayList<>(); - aaiProperties.addAll(oxmInfo.getAuditDoc().getProperties()); - aaiIndexes.addAll(oxmInfo.getAuditDoc().getIndexes()); - aaiEdgeProperties.addAll(oxmInfo.getAuditDoc().getEdgeLabels()); - try { - createPropertyKeys(); - createIndexes(); - createEdgeLabels(); - } catch (Exception e) { - e.printStackTrace(); - graphMgmt.rollback(); - } - graphMgmt.commit(); - } - - /** - * Creates the property keys. - */ - private void createPropertyKeys() { - - - for (DBProperty prop : aaiProperties) { - - if (graphMgmt.containsPropertyKey(prop.getName())) { - PropertyKey key = graphMgmt.getPropertyKey(prop.getName()); - boolean isChanged = false; - if (!prop.getCardinality().equals(key.cardinality())) { - isChanged = true; - } - if (!prop.getTypeClass().equals(key.dataType())) { - isChanged = true; - } - if (isChanged) { - //must modify! - this.replaceProperty(prop); - } - } else { - //create a new property key - System.out.println("Key: " + prop.getName() + " not found - adding"); - graphMgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make(); - } - } - - } - - /** - * Creates the indexes. - */ - private void createIndexes() { - - for (DBIndex index : aaiIndexes) { - Set<DBProperty> props = index.getProperties(); - boolean isChanged = false; - boolean isNew = false; - List<PropertyKey> keyList = new ArrayList<>(); - for (DBProperty prop : props) { - keyList.add(graphMgmt.getPropertyKey(prop.getName())); - } - if (graphMgmt.containsGraphIndex(index.getName())) { - TitanGraphIndex titanIndex = graphMgmt.getGraphIndex(index.getName()); - PropertyKey[] dbKeys = titanIndex.getFieldKeys(); - if (dbKeys.length != keyList.size()) { - isChanged = true; - } else { - int i = 0; - for (PropertyKey key : keyList) { - if (!dbKeys[i].equals(key)) { - isChanged = true; - break; - } - i++; - } - } - } else { - isNew = true; - } - if (keyList.size() > 0) { - this.createIndex(graphMgmt, index.getName(), keyList, index.isUnique(), isNew, isChanged); - } - } - } - - // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE: the multiplicty used here is - // always "MULTI". This is not the same as our internal "Many2Many", "One2One", "One2Many" or "Many2One" - // We use the same edge-label for edges between many different types of nodes and our internal - // multiplicty definitions depends on which two types of nodes are being connected. - /** - * Creates the edge labels. - */ - private void createEdgeLabels() { - - - for (EdgeProperty prop : aaiEdgeProperties) { - - if (graphMgmt.containsEdgeLabel(prop.getName())) { - // see what changed - } else { - graphMgmt.makeEdgeLabel(prop.getName()).multiplicity(prop.getMultiplicity()).make(); - } - - } - - - } - - /** - * Creates the property. - * - * @param mgmt the mgmt - * @param prop the prop - */ - private void createProperty(TitanManagement mgmt, DBProperty prop) { - if (mgmt.containsPropertyKey(prop.getName())) { - PropertyKey key = mgmt.getPropertyKey(prop.getName()); - boolean isChanged = false; - if (!prop.getCardinality().equals(key.cardinality())) { - isChanged = true; - } - if (!prop.getTypeClass().equals(key.dataType())) { - isChanged = true; - } - if (isChanged) { - //must modify! - this.replaceProperty(prop); - } - } else { - //create a new property key - System.out.println("Key: " + prop.getName() + " not found - adding"); - mgmt.makePropertyKey(prop.getName()).dataType(prop.getTypeClass()).cardinality(prop.getCardinality()).make(); - } - } - - /** - * Creates the index. - * - * @param mgmt the mgmt - * @param indexName the index name - * @param keys the keys - * @param isUnique the is unique - * @param isNew the is new - * @param isChanged the is changed - */ - private void createIndex(TitanManagement mgmt, String indexName, List<PropertyKey> keys, boolean isUnique, boolean isNew, boolean isChanged) { - - /*if (isChanged) { - System.out.println("Changing index: " + indexName); - TitanGraphIndex oldIndex = mgmt.getGraphIndex(indexName); - mgmt.updateIndex(oldIndex, SchemaAction.DISABLE_INDEX); - mgmt.commit(); - //cannot remove indexes - //graphMgmt.updateIndex(oldIndex, SchemaAction.REMOVE_INDEX); - }*/ - if (isNew || isChanged) { - - if (isNew) { - IndexBuilder builder = mgmt.buildIndex(indexName,Vertex.class); - for (PropertyKey k : keys) { - builder.addKey(k); - } - if (isUnique) { - builder.unique(); - } - builder.buildCompositeIndex(); - System.out.println("Built index for " + indexName + " with keys: " + keys); - - //mgmt.commit(); - } - - //mgmt = graph.asAdmin().getManagementSystem(); - //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REGISTER_INDEX); - //mgmt.commit(); - - try { - //waitForCompletion(indexName); - //TitanIndexRepair.hbaseRepair(AAIConstants.AAI_CONFIG_FILENAME, indexName, ""); - } catch (Exception e) { - // TODO Auto-generated catch block - graph.tx().rollback(); - graph.close(); - e.printStackTrace(); - } - - //mgmt = graph.asAdmin().getManagementSystem(); - //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.REINDEX); - - //mgmt.updateIndex(mgmt.getGraphIndex(indexName), SchemaAction.ENABLE_INDEX); - - //mgmt.commit(); - - } - } - - /** - * Wait for completion. - * - * @param name the name - * @throws InterruptedException the interrupted exception - */ - private void waitForCompletion(String name) throws InterruptedException { - - boolean registered = false; - long before = System.currentTimeMillis(); - while (!registered) { - Thread.sleep(500L); - TitanManagement mgmt = graph.openManagement(); - TitanGraphIndex idx = mgmt.getGraphIndex(name); - registered = true; - for (PropertyKey k : idx.getFieldKeys()) { - SchemaStatus s = idx.getIndexStatus(k); - registered &= s.equals(SchemaStatus.REGISTERED); - } - mgmt.rollback(); - } - System.out.println("Index REGISTERED in " + (System.currentTimeMillis() - before) + " ms"); - } - - /** - * Replace property. - * - * @param key the key - */ - private void replaceProperty(DBProperty key) { - - - - - } - - /** - * Update index. - * - * @param index the index - */ - public void updateIndex(DBIndex index) { - - TitanManagement mgmt = graph.openManagement(); - List<PropertyKey> keys = new ArrayList<>(); - boolean isNew = false; - boolean isChanged = false; - for (DBProperty prop : index.getProperties()) { - createProperty(mgmt, prop); - keys.add(mgmt.getPropertyKey(prop.getName())); - } - if (mgmt.containsGraphIndex(index.getName())) { - System.out.println("index already exists"); - isNew = false; - isChanged = true; - } else { - isNew = true; - isChanged = false; - } - this.createIndex(mgmt, index.getName(), keys, index.isUnique(), isNew, isChanged); - - mgmt.commit(); - - } - - - - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/Named.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/Named.java deleted file mode 100644 index 850af57a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/Named.java +++ /dev/null @@ -1,31 +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.db.schema; - -public interface Named { - - /** - * Gets the name. - * - * @return the name - */ - public String getName(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/db/schema/ScriptDriver.java b/aai-core/src/main/java/org/openecomp/aai/db/schema/ScriptDriver.java deleted file mode 100644 index 9a90ea28..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/db/schema/ScriptDriver.java +++ /dev/null @@ -1,93 +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.db.schema; - -import java.io.IOException; - -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.util.AAIConfig; -import com.beust.jcommander.JCommander; -import com.beust.jcommander.Parameter; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; - -public class ScriptDriver { - - - /** - * The main method. - * - * @param args the arguments - * @throws AAIException the AAI exception - * @throws JsonGenerationException the json generation exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - */ - public static void main (String[] args) throws AAIException, IOException { - CommandLineArgs cArgs = new CommandLineArgs(); - - new JCommander(cArgs, args); - - if (cArgs.help) { - System.out.println("-c [path to graph configuration] -type [what you want to audit - oxm or graph]"); - } - String config = cArgs.config; - AAIConfig.init(); - try (TitanGraph graph = TitanFactory.open(config)) { - if (!("oxm".equals(cArgs.type) || "graph".equals(cArgs.type))) { - System.out.println("type: " + cArgs.type + " not recognized."); - System.exit(1); - } - - AuditDoc doc = null; - if ("oxm".equals(cArgs.type)) { - doc = AuditorFactory.getOXMAuditor(Version.v8).getAuditDoc(); - } else if ("graph".equals(cArgs.type)) { - doc = AuditorFactory.getGraphAuditor(graph).getAuditDoc(); - } - - ObjectMapper mapper = new ObjectMapper(); - - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); - System.out.println(json); - } - } - -} - -class CommandLineArgs { - - @Parameter(names = "--help", description = "Help") - public boolean help = false; - - @Parameter(names = "-c", description = "Configuration", required=true) - public String config; - - @Parameter(names = "-type", description = "Type", required=true) - public String type = "graph"; - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java deleted file mode 100644 index f2d6a4b8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/DataGrooming.java +++ /dev/null @@ -1,2319 +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.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.UUID; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Property; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.AAIGraph; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.serialization.db.AAIDirection; -import org.openecomp.aai.serialization.db.EdgeProperty; -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; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; - - -public class DataGrooming { - - private static EELFLogger LOGGER; - private static final String FROMAPPID = "AAI-DB"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static int dupeGrpsDeleted = 0; - - /** - * 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_DATA_GROOMING_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(DataGrooming.class); - String ver = "version"; // Placeholder - Boolean doAutoFix = false; - Boolean edgesOnlyFlag = false; - Boolean dontFixOrphansFlag = false; - Boolean skipHostCheck = false; - Boolean singleCommits = false; - Boolean dupeCheckOff = false; - Boolean dupeFixOn = false; - Boolean ghost2CheckOff = false; - Boolean ghost2FixOn = false; - Boolean neverUseCache = false; - Boolean skipEdgeCheckFlag = false; - - int timeWindowMinutes = 0; // A value of 0 means that we will not have a time-window -- we will look - // at all nodes of the passed-in nodeType. - long windowStartTime = 0; // Translation of the window into a starting timestamp - - int maxRecordsToFix = AAIConstants.AAI_GROOMING_DEFAULT_MAX_FIX; - int sleepMinutes = AAIConstants.AAI_GROOMING_DEFAULT_SLEEP_MINUTES; - try { - String maxFixStr = AAIConfig.get("aai.grooming.default.max.fix"); - if( maxFixStr != null && !maxFixStr.equals("") ){ - maxRecordsToFix = Integer.parseInt(maxFixStr); - } - String sleepStr = AAIConfig.get("aai.grooming.default.sleep.minutes"); - if( sleepStr != null && !sleepStr.equals("") ){ - sleepMinutes = Integer.parseInt(sleepStr); - } - } - catch ( Exception e ){ - // Don't worry, we'll just use the defaults that we got from AAIConstants - LOGGER.warn("WARNING - could not pick up aai.grooming values from aaiconfig.properties file. "); - } - - String prevFileName = ""; - dupeGrpsDeleted = 0; - FormatDate fd = new FormatDate("yyyyMMddHHmm", "GMT"); - String dteStr = fd.getDateTime(); - String groomOutFileName = "dataGrooming." + dteStr + ".out"; - - String argString = ""; - for( int x = 0; x < args.length; x++ ) { - argString = argString + " " + args[x]; - } - LOGGER.info(" DataGrooming called with these options: [" + argString + "]"); - - if (args.length > 0) { - // They passed some arguments in that will affect processing - - for (int i = 0; i < args.length; i++) { - String thisArg = args[i]; - if (thisArg.equals("-edgesOnly")) { - edgesOnlyFlag = true; - } else if (thisArg.equals("-autoFix")) { - doAutoFix = true; - } else if (thisArg.equals("-skipHostCheck")) { - skipHostCheck = true; - } else if (thisArg.equals("-dontFixOrphans")) { - dontFixOrphansFlag = true; - } else if (thisArg.equals("-singleCommits")) { - singleCommits = true; - } else if (thisArg.equals("-dupeCheckOff")) { - dupeCheckOff = true; - } else if (thisArg.equals("-dupeFixOn")) { - dupeFixOn = true; - } else if (thisArg.equals("-ghost2CheckOff")) { - ghost2CheckOff = true; - } else if (thisArg.equals("-neverUseCache")) { - neverUseCache = true; - } else if (thisArg.equals("-ghost2FixOn")) { - ghost2FixOn = true; - } else if (thisArg.equals("-skipEdgeChecks")) { - skipEdgeCheckFlag = true; - } else if (thisArg.equals("-maxFix")) { - i++; - if (i >= args.length) { - LOGGER.error(" No value passed with -maxFix option. "); - System.exit(0); - } - String nextArg = args[i]; - try { - maxRecordsToFix = Integer.parseInt(nextArg); - } catch (Exception e) { - LOGGER.error("Bad value passed with -maxFix option: [" - + nextArg + "]"); - System.exit(0); - } - } else if (thisArg.equals("-sleepMinutes")) { - i++; - if (i >= args.length) { - LOGGER.error("No value passed with -sleepMinutes option."); - System.exit(0); - } - String nextArg = args[i]; - try { - sleepMinutes = Integer.parseInt(nextArg); - } catch (Exception e) { - LOGGER.error("Bad value passed with -sleepMinutes option: [" - + nextArg + "]"); - System.exit(0); - } - } else if (thisArg.equals("-timeWindowMinutes")) { - i++; - if (i >= args.length) { - LOGGER.error("No value passed with -timeWindowMinutes option."); - System.exit(0); - } - String nextArg = args[i]; - try { - timeWindowMinutes = Integer.parseInt(nextArg); - } catch (Exception e) { - LOGGER.error("Bad value passed with -timeWindowMinutes option: [" - + nextArg + "]"); - System.exit(0); - } - if( timeWindowMinutes > 0 ){ - // Translate the window value (ie. 30 minutes) into a unix timestamp like - // we use in the db - so we can select data created after that time. - windowStartTime = figureWindowStartTime( timeWindowMinutes ); - } - } else if (thisArg.equals("-f")) { - i++; - if (i >= args.length) { - LOGGER.error(" No value passed with -f option. "); - System.exit(0); - } - prevFileName = args[i]; - } else { - LOGGER.error(" Unrecognized argument passed to DataGrooming: [" - + thisArg + "]. "); - LOGGER.error(" Valid values are: -f -autoFix -maxFix -edgesOnly -dupeFixOn -donFixOrphans -sleepMinutes -neverUseCache"); - System.exit(0); - } - } - } - - - try { - LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - - } - catch (Exception ex){ - LOGGER.error("ERROR - Could not create loader", ex); - System.exit(1); - } - - - try { - if (!prevFileName.equals("")) { - // They are trying to fix some data based on a data in a - // previous file. - LOGGER.info(" Call doTheGrooming() with a previous fileName [" - + prevFileName + "] for cleanup. "); - Boolean finalShutdownFlag = true; - Boolean cacheDbOkFlag = false; - doTheGrooming(prevFileName, edgesOnlyFlag, dontFixOrphansFlag, - maxRecordsToFix, groomOutFileName, ver, singleCommits, - dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - } else if (doAutoFix) { - // They want us to run the processing twice -- first to look for - // delete candidates, then after - // napping for a while, run it again and delete any candidates - // that were found by the first run. - // Note: we will produce a separate output file for each of the - // two runs. - LOGGER.info(" Doing an auto-fix call to Grooming. "); - LOGGER.info(" First, Call doTheGrooming() to look at what's out there. "); - Boolean finalShutdownFlag = false; - Boolean cacheDbOkFlag = true; - int fixCandCount = doTheGrooming("", edgesOnlyFlag, - dontFixOrphansFlag, maxRecordsToFix, groomOutFileName, - ver, singleCommits, dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - if (fixCandCount == 0) { - LOGGER.info(" No fix-Candidates were found by the first pass, so no second/fix-pass is needed. "); - } else { - // We'll sleep a little and then run a fix-pass based on the - // first-run's output file. - try { - LOGGER.info("About to sleep for " + sleepMinutes - + " minutes."); - int sleepMsec = sleepMinutes * 60 * 1000; - Thread.sleep(sleepMsec); - } catch (InterruptedException ie) { - LOGGER.info("\n >>> Sleep Thread has been Interrupted <<< "); - System.exit(0); - } - - dteStr = fd.getDateTime(); - String secondGroomOutFileName = "dataGrooming." + dteStr - + ".out"; - LOGGER.info(" Now, call doTheGrooming() a second time and pass in the name of the file " - + "generated by the first pass for fixing: [" - + groomOutFileName + "]"); - finalShutdownFlag = true; - cacheDbOkFlag = false; - doTheGrooming(groomOutFileName, edgesOnlyFlag, - dontFixOrphansFlag, maxRecordsToFix, - secondGroomOutFileName, ver, singleCommits, - dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - } - } else { - // Do the grooming - plain vanilla (no fix-it-file, no - // auto-fixing) - Boolean finalShutdownFlag = true; - LOGGER.info(" Call doTheGrooming() "); - Boolean cacheDbOkFlag = true; - if( neverUseCache ){ - // They have forbidden us from using a cached db connection. - cacheDbOkFlag = false; - } - doTheGrooming("", edgesOnlyFlag, dontFixOrphansFlag, - maxRecordsToFix, groomOutFileName, ver, singleCommits, - dupeCheckOff, dupeFixOn, ghost2CheckOff, ghost2FixOn, - finalShutdownFlag, cacheDbOkFlag, - skipEdgeCheckFlag, windowStartTime); - } - } catch (Exception ex) { - LOGGER.error("Exception while grooming data", ex); - } - - LOGGER.info(" Done! "); - System.exit(0); - - }// End of main() - - /** - * Do the grooming. - * - * @param fileNameForFixing the file name for fixing - * @param edgesOnlyFlag the edges only flag - * @param dontFixOrphansFlag the dont fix orphans flag - * @param maxRecordsToFix the max records to fix - * @param groomOutFileName the groom out file name - * @param version the version - * @param singleCommits the single commits - * @param dupeCheckOff the dupe check off - * @param dupeFixOn the dupe fix on - * @param ghost2CheckOff the ghost 2 check off - * @param ghost2FixOn the ghost 2 fix on - * @param finalShutdownFlag the final shutdown flag - * @param cacheDbOkFlag the cacheDbOk flag - * @return the int - */ - private static int doTheGrooming(String fileNameForFixing, - Boolean edgesOnlyFlag, Boolean dontFixOrphansFlag, - int maxRecordsToFix, String groomOutFileName, String version, - Boolean singleCommits, - Boolean dupeCheckOff, Boolean dupeFixOn, - Boolean ghost2CheckOff, Boolean ghost2FixOn, - Boolean finalShutdownFlag, Boolean cacheDbOkFlag, - Boolean skipEdgeCheckFlag, long windowStartTime) { - - LOGGER.debug(" Entering doTheGrooming \n"); - - int cleanupCandidateCount = 0; - BufferedWriter bw = null; - TitanGraph graph = null; - TitanGraph graph2 = null; - int deleteCount = 0; - boolean executeFinalCommit = false; - Set<String> deleteCandidateList = new LinkedHashSet<>(); - Set<String> processedVertices = new LinkedHashSet<>(); - Graph g = null; - Graph g2 = null; - try { - AAIConfig.init(); - String targetDir = AAIConstants.AAI_HOME + AAIConstants.AAI_FILESEP - + "logs" + AAIConstants.AAI_FILESEP + "data" - + AAIConstants.AAI_FILESEP + "dataGrooming"; - - // Make sure the target directory exists - new File(targetDir).mkdirs(); - - if (!fileNameForFixing.equals("")) { - deleteCandidateList = getDeleteList(targetDir, - fileNameForFixing, edgesOnlyFlag, dontFixOrphansFlag, - dupeFixOn); - } - - if (deleteCandidateList.size() > maxRecordsToFix) { - LOGGER.warn(" >> WARNING >> Delete candidate list size (" - + deleteCandidateList.size() - + ") is too big. The maxFix we are using is: " - + maxRecordsToFix - + ". No candidates will be deleted. "); - // Clear out the list so it won't be processed below. - deleteCandidateList = new LinkedHashSet<>(); - } - - String fullOutputFileName = targetDir + AAIConstants.AAI_FILESEP - + groomOutFileName; - File groomOutFile = new File(fullOutputFileName); - try { - groomOutFile.createNewFile(); - } catch (IOException e) { - String emsg = " Problem creating output file [" - + fullOutputFileName + "], exception=" + e.getMessage(); - throw new AAIException("AAI_6124", emsg); - } - - LOGGER.info(" Will write to " + fullOutputFileName ); - bw = new BufferedWriter(new FileWriter(groomOutFile.getAbsoluteFile())); - ErrorLogHelper.loadProperties(); - - LOGGER.info(" ---- NOTE --- about to open graph (takes a little while)--------\n"); - - if( cacheDbOkFlag ){ - // Since we're just reading (not deleting/fixing anything), we can use - // a cached connection to the DB - graph = TitanFactory.open(AAIConstants.CACHED_DB_CONFIG); - } - else { - graph = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); - } - if (graph == null) { - String emsg = "null graph object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } - - LOGGER.debug(" Got the graph object. "); - - g = graph.newTransaction(); - if (g == null) { - String emsg = "null graphTransaction object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } - GraphTraversalSource source1 = g.traversal(); - - ArrayList<String> errArr = new ArrayList<>(); - int totalNodeCount = 0; - HashMap<String, String> misMatchedHash = new HashMap<String, String>(); - HashMap<String, Vertex> orphanNodeHash = new HashMap<String, Vertex>(); - HashMap<String, Vertex> missingDepNodeHash = new HashMap<String, Vertex>(); - HashMap<String, Edge> oneArmedEdgeHash = new HashMap<String, Edge>(); - HashMap<String, String> emptyVertexHash = new HashMap<String, String>(); - HashMap<String, Vertex> ghostNodeHash = new HashMap<String, Vertex>(); - ArrayList<String> dupeGroups = new ArrayList<>(); - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - - Set<Entry<String, Introspector>> entrySet = loader.getAllObjects().entrySet(); - String ntList = ""; - - LOGGER.info(" Starting DataGrooming Processing "); - - if (edgesOnlyFlag) { - LOGGER.info(" NOTE >> Skipping Node processing as requested. Will only process Edges. << "); - } - else { - for (Entry<String, Introspector> entry : entrySet) { - String nType = entry.getKey(); - int thisNtCount = 0; - int thisNtDeleteCount = 0; - LOGGER.debug(" > Look at : [" + nType + "] ..."); - ntList = ntList + "," + nType; - - // Get a collection of the names of the key properties for this nodeType to use later - // Determine what the key fields are for this nodeType - Collection <String> keyProps = entry.getValue().getKeys(); - - // Get the types of nodes that this nodetype depends on for uniqueness (if any) - Collection <String> depNodeTypes = loader.introspectorFromName(nType).getDependentOn(); - - // Loop through all the nodes of this Node type - int lastShownForNt = 0; - ArrayList <Vertex> tmpList = new ArrayList <> (); - Iterator <Vertex> iterv = source1.V().has("aai-node-type",nType); - while (iterv.hasNext()) { - // We put the nodes into an ArrayList because the graph.query iterator can time out - tmpList.add(iterv.next()); - } - - Iterator <Vertex> iter = tmpList.iterator(); - while (iter.hasNext()) { - try { - thisNtCount++; - if( thisNtCount == lastShownForNt + 250 ){ - lastShownForNt = thisNtCount; - LOGGER.debug("count for " + nType + " so far = " + thisNtCount ); - } - Vertex thisVtx = iter.next(); - if( windowStartTime > 0 ){ - // We only want nodes that are created after a passed-in timestamp - Object objTimeStamp = thisVtx.property("aai-created-ts").orElse(null); - if( objTimeStamp != null ){ - long thisNodeCreateTime = (long)objTimeStamp; - if( thisNodeCreateTime < windowStartTime ){ - // It is NOT in our window, so we can pass over it - continue; - } - } - } - - String thisVid = thisVtx.id().toString(); - if (processedVertices.contains(thisVid)) { - LOGGER.debug("skipping already processed vertex: " + thisVid); - continue; - } - totalNodeCount++; - List <Vertex> secondGetList = new ArrayList <> (); - // ----------------------------------------------------------------------- - // For each vertex of this nodeType, we want to: - // a) make sure that it can be retrieved using it's AAI defined key - // b) make sure that it is not a duplicate - // ----------------------------------------------------------------------- - - // For this instance of this nodeType, get the key properties - HashMap<String, Object> propHashWithKeys = new HashMap<>(); - Iterator<String> keyPropI = keyProps.iterator(); - while (keyPropI.hasNext()) { - String propName = keyPropI.next(); - String propVal = ""; - //delete an already deleted vertex - Object obj = thisVtx.<Object>property(propName).orElse(null); - if (obj != null) { - propVal = obj.toString(); - } - propHashWithKeys.put(propName, propVal); - } - try { - // If this node is dependent on another for uniqueness, then do the query from that parent node - // Note - all of our nodes that are dependent on others for uniqueness are - // "children" of that node. - boolean depNodeOk = true; - if( depNodeTypes.isEmpty() ){ - // This kind of node is not dependent on any other. - // Make sure we can get it back using it's key properties and that we only get one. - secondGetList = getNodeJustUsingKeyParams( TRANSID, FROMAPPID, source1, nType, - propHashWithKeys, version ); - } - else { - // This kind of node is dependent on another for uniqueness. - // Start at it's parent (the dependent vertex) and make sure we can get it - // back using it's key properties and that we only get one. - Iterator <Vertex> vertI2 = source1.V(thisVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV()); - Vertex parentVtx = null; - int pCount = 0; - while( vertI2 != null && vertI2.hasNext() ){ - parentVtx = vertI2.next(); - pCount++; - } - if( pCount <= 0 ){ - - - //List<Vertex> vertI2 = g.traversal().V(thisVtx).union(__.outE().has("isParent-REV",true).outV(),__.inE().has("isParent",true).inV()).toList(); - //if( vertI2.isEmpty()){ - - // It's Missing it's dependent/parent node - depNodeOk = false; - boolean zeroEdges = false; - try { - Iterator<Edge> tmpEdgeIter = thisVtx.edges(Direction.BOTH); - int edgeCount = 0; - while( tmpEdgeIter.hasNext() ){ - edgeCount++; - tmpEdgeIter.next(); - } - if( edgeCount == 0 ){ - zeroEdges = true; - } - } catch (Exception ex) { - LOGGER.warn("WARNING from inside the for-each-vid-loop orphan-edges-check ", ex); - } - - if (deleteCandidateList.contains(thisVid)) { - boolean okFlag = true; - try { - processedVertices.add(thisVtx.id().toString()); - thisVtx.remove(); - deleteCount++; - thisNtDeleteCount++; - } catch (Exception e) { - okFlag = false; - LOGGER.error("ERROR trying to delete missing-dep-node VID = " + thisVid, e); - } - if (okFlag) { - LOGGER.info(" DELETED missing-dep-node VID = " + thisVid); - } - } else { - // We count nodes missing their depNodes two ways - the first if it has - // at least some edges, and the second if it has zero edges. Either - // way, they are effectively orphaned. - // NOTE - Only nodes that have dependent nodes are ever considered "orphaned". - if( zeroEdges ){ - missingDepNodeHash.put(thisVid, thisVtx); - } - else { - orphanNodeHash.put(thisVid, thisVtx); - } - } - } - else if ( pCount > 1 ){ - // Not sure how this could happen? Should we do something here? - depNodeOk = false; - } - else { - // We found the parent - so use it to do the second-look. - // NOTE --- We're just going to do the same check from the other direction - because - // there could be duplicates or the pointer going the other way could be broken - ArrayList <Vertex> tmpListSec = new ArrayList <> (); - - tmpListSec = getConnectedChildrenOfOneType( source1, parentVtx, nType ) ; - Iterator<Vertex> vIter = tmpListSec.iterator(); - while (vIter.hasNext()) { - Vertex tmpV = vIter.next(); - if( vertexHasTheseKeys(tmpV, propHashWithKeys) ){ - secondGetList.add(tmpV); - } - } - } - } - - if( depNodeOk && (secondGetList == null || secondGetList.size() == 0) ){ - // We could not get the node back using it's own key info. - // So, it's a PHANTOM - if (deleteCandidateList.contains(thisVid)) { - boolean okFlag = true; - try { - thisVtx.remove(); - deleteCount++; - thisNtDeleteCount++; - } catch (Exception e) { - okFlag = false; - LOGGER.error("ERROR trying to delete phantom VID = " + thisVid, e); - } - if (okFlag) { - LOGGER.info(" DELETED VID = " + thisVid); - } - } else { - ghostNodeHash.put(thisVid, thisVtx); - } - } - else if( (secondGetList.size() > 1) && depNodeOk && !dupeCheckOff ){ - // Found some DUPLICATES - need to process them - LOGGER.info(" - now check Dupes for this guy - "); - List<String> tmpDupeGroups = checkAndProcessDupes( - TRANSID, FROMAPPID, g, source1, version, - nType, secondGetList, dupeFixOn, - deleteCandidateList, singleCommits, dupeGroups, loader); - Iterator<String> dIter = tmpDupeGroups.iterator(); - while (dIter.hasNext()) { - // Add in any newly found dupes to our running list - String tmpGrp = dIter.next(); - LOGGER.info("Found set of dupes: [" + tmpGrp + "]"); - dupeGroups.add(tmpGrp); - } - } - } - catch (AAIException e1) { - LOGGER.warn(" For nodeType = " + nType + " Caught exception", e1); - errArr.add(e1.getErrorObject().toString()); - } - catch (Exception e2) { - LOGGER.warn(" For nodeType = " + nType - + " Caught exception", e2); - errArr.add(e2.getMessage()); - } - }// try block to enclose looping of a single vertex - catch (Exception exx) { - LOGGER.warn("WARNING from inside the while-verts-loop ", exx); - } - - } // while loop for each record of a nodeType - - if ( (thisNtDeleteCount > 0) && singleCommits ) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - - } - thisNtDeleteCount = 0; - LOGGER.info( " Processed " + thisNtCount + " records for [" + nType + "], " + totalNodeCount + " total overall. " ); - - }// While-loop for each node type - }// end of check to make sure we weren't only supposed to do edges - - - if( !skipEdgeCheckFlag ){ - // -------------------------------------------------------------------------------------- - // Now, we're going to look for one-armed-edges. Ie. an edge that - // should have - // been deleted (because a vertex on one side was deleted) but - // somehow was not deleted. - // So the one end of it points to a vertexId -- but that vertex is - // empty. - // -------------------------------------------------------------------------------------- - - // To do some strange checking - we need a second graph object - LOGGER.debug(" ---- DEBUG --- about to open a SECOND graph (takes a little while)--------\n"); - // Note - graph2 just reads - but we want it to use a fresh connection to - // the database, so we are NOT using the CACHED DB CONFIG here. - graph2 = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); - if (graph2 == null) { - String emsg = "null graph2 object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } else { - LOGGER.debug("Got the graph2 object... \n"); - } - g2 = graph2.newTransaction(); - if (g2 == null) { - String emsg = "null graphTransaction2 object in DataGrooming\n"; - throw new AAIException("AAI_6101", emsg); - } - - ArrayList<Vertex> vertList = new ArrayList<>(); - Iterator<Vertex> vItor3 = g.traversal().V(); - // Gotta hold these in a List - or else HBase times out as you cycle - // through these - while (vItor3.hasNext()) { - Vertex v = vItor3.next(); - vertList.add(v); - } - int counter = 0; - int lastShown = 0; - Iterator<Vertex> vItor2 = vertList.iterator(); - LOGGER.info(" Checking for bad edges --- "); - - while (vItor2.hasNext()) { - Vertex v = null; - try { - try { - v = vItor2.next(); - } catch (Exception vex) { - LOGGER.warn(">>> WARNING trying to get next vertex on the vItor2 "); - continue; - } - - counter++; - String thisVertId = ""; - try { - thisVertId = v.id().toString(); - } catch (Exception ev) { - LOGGER.warn("WARNING when doing getId() on a vertex from our vertex list. "); - continue; - } - if (ghostNodeHash.containsKey(thisVertId)) { - // This is a phantom node, so don't try to use it - LOGGER.info(" >> Skipping edge check for edges from vertexId = " - + thisVertId - + ", since that guy is a Phantom Node"); - continue; - } - - if( windowStartTime > 0 ){ - // We only want to look at nodes that are created after a passed-in timestamp - Object objTimeStamp = v.property("aai-created-ts").orElse(null); - if( objTimeStamp != null ){ - long thisNodeCreateTime = (long)objTimeStamp; - if( thisNodeCreateTime < windowStartTime ){ - // It is NOT in our window, so we can pass over it - continue; - } - } - } - - if (counter == lastShown + 250) { - lastShown = counter; - LOGGER.info("... Checking edges for vertex # " - + counter); - } - Iterator<Edge> eItor = v.edges(Direction.BOTH); - while (eItor.hasNext()) { - Edge e = null; - Vertex vIn = null; - Vertex vOut = null; - try { - e = eItor.next(); - } catch (Exception iex) { - LOGGER.warn(">>> WARNING trying to get next edge on the eItor ", iex); - continue; - } - - try { - vIn = e.inVertex(); - } catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's In-vertex ", err); - } - String vNtI = ""; - String vIdI = ""; - Vertex ghost2 = null; - - Boolean keysMissing = true; - Boolean cantGetUsingVid = false; - if (vIn != null) { - try { - Object ob = vIn.<Object>property("aai-node-type").orElse(null); - if (ob != null) { - vNtI = ob.toString(); - keysMissing = anyKeyFieldsMissing(vNtI, vIn, loader); - } - ob = vIn.id(); - long vIdLong = 0L; - if (ob != null) { - vIdI = ob.toString(); - vIdLong = Long.parseLong(vIdI); - } - - if( ! ghost2CheckOff ){ - Vertex connectedVert = g2.traversal().V(vIdLong).next(); - if( connectedVert == null ) { - LOGGER.warn( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong); - cantGetUsingVid = true; - - // If we can NOT get this ghost with the SECOND graph-object, - // it is still a ghost since even though we can get data about it using the FIRST graph - // object. - try { - ghost2 = g.traversal().V(vIdLong).next(); - } - catch( Exception ex){ - LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex); - } - if( ghost2 != null ){ - ghostNodeHash.put(vIdI, ghost2); - } - } - }// end of the ghost2 checking - } - catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's In-vertex props ", err); - } - } - if (keysMissing || vIn == null || vNtI.equals("") - || cantGetUsingVid) { - // this is a bad edge because it points to a vertex - // that isn't there anymore or is corrupted - String thisEid = e.id().toString(); - if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdI)) { - boolean okFlag = true; - if (!vIdI.equals("")) { - // try to get rid of the corrupted vertex - try { - if( (ghost2 != null) && ghost2FixOn ){ - ghost2.remove(); - } - else { - vIn.remove(); - } - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception e1) { - okFlag = false; - LOGGER.warn("WARNING when trying to delete bad-edge-connected VERTEX VID = " - + vIdI, e1); - } - if (okFlag) { - LOGGER.info(" DELETED vertex from bad edge = " - + vIdI); - } - } else { - // remove the edge if we couldn't get the - // vertex - try { - e.remove(); - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception ex) { - // NOTE - often, the exception is just - // that this edge has already been - // removed - okFlag = false; - LOGGER.warn("WARNING when trying to delete edge = " - + thisEid); - } - if (okFlag) { - LOGGER.info(" DELETED edge = " + thisEid); - } - } - } else { - oneArmedEdgeHash.put(thisEid, e); - if ((vIn != null) && (vIn.id() != null)) { - emptyVertexHash.put(thisEid, vIn.id() - .toString()); - } - } - } - - try { - vOut = e.outVertex(); - } catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's Out-vertex "); - } - String vNtO = ""; - String vIdO = ""; - ghost2 = null; - keysMissing = true; - cantGetUsingVid = false; - if (vOut != null) { - try { - Object ob = vOut.<Object>property("aai-node-type").orElse(null); - if (ob != null) { - vNtO = ob.toString(); - keysMissing = anyKeyFieldsMissing(vNtO, - vOut, loader); - } - ob = vOut.id(); - long vIdLong = 0L; - if (ob != null) { - vIdO = ob.toString(); - vIdLong = Long.parseLong(vIdO); - } - - if( ! ghost2CheckOff ){ - Vertex connectedVert = g2.traversal().V(vIdLong).next(); - if( connectedVert == null ) { - cantGetUsingVid = true; - LOGGER.info( "GHOST2 -- got NULL when doing getVertex for vid = " + vIdLong); - // If we can get this ghost with the other graph-object, then get it -- it's still a ghost - try { - ghost2 = g.traversal().V(vIdLong).next(); - } - catch( Exception ex){ - LOGGER.warn( "GHOST2 -- Could not get the ghost info for a bad edge for vtxId = " + vIdLong, ex); - } - if( ghost2 != null ){ - ghostNodeHash.put(vIdO, ghost2); - } - } - } - } catch (Exception err) { - LOGGER.warn(">>> WARNING trying to get edge's Out-vertex props ", err); - } - } - if (keysMissing || vOut == null || vNtO.equals("") - || cantGetUsingVid) { - // this is a bad edge because it points to a vertex - // that isn't there anymore - String thisEid = e.id().toString(); - if (deleteCandidateList.contains(thisEid) || deleteCandidateList.contains(vIdO)) { - boolean okFlag = true; - if (!vIdO.equals("")) { - // try to get rid of the corrupted vertex - try { - if( (ghost2 != null) && ghost2FixOn ){ - ghost2.remove(); - } - else if (vOut != null) { - vOut.remove(); - } - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception e1) { - okFlag = false; - LOGGER.warn("WARNING when trying to delete bad-edge-connected VID = " - + vIdO, e1); - } - if (okFlag) { - LOGGER.info(" DELETED vertex from bad edge = " - + vIdO); - } - } else { - // remove the edge if we couldn't get the - // vertex - try { - e.remove(); - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - deleteCount++; - } catch (Exception ex) { - // NOTE - often, the exception is just - // that this edge has already been - // removed - okFlag = false; - LOGGER.warn("WARNING when trying to delete edge = " - + thisEid, ex); - } - if (okFlag) { - LOGGER.info(" DELETED edge = " + thisEid); - } - } - } else { - oneArmedEdgeHash.put(thisEid, e); - if ((vOut != null) && (vOut.id() != null)) { - emptyVertexHash.put(thisEid, vOut.id() - .toString()); - } - } - } - }// End of while-edges-loop - } catch (Exception exx) { - LOGGER.warn("WARNING from in the while-verts-loop ", exx); - } - }// End of while-vertices-loop (the edge-checking) - } // end of -- if we're not skipping the edge-checking - - - deleteCount = deleteCount + dupeGrpsDeleted; - if (!singleCommits && deleteCount > 0) { - try { - LOGGER.info("About to do the commit for " - + deleteCount + " removes. "); - executeFinalCommit = true; - LOGGER.info("Commit was successful "); - } catch (Exception excom) { - LOGGER.error(" >>>> ERROR <<<< Could not commit changes. ", excom); - deleteCount = 0; - } - } - - int ghostNodeCount = ghostNodeHash.size(); - int orphanNodeCount = orphanNodeHash.size(); - int missingDepNodeCount = missingDepNodeHash.size(); - int oneArmedEdgeCount = oneArmedEdgeHash.size(); - int dupeCount = dupeGroups.size(); - - deleteCount = deleteCount + dupeGrpsDeleted; - - bw.write("\n\n ============ Summary ==============\n"); - bw.write("Ran these nodeTypes: " + ntList + "\n\n"); - bw.write("There were this many delete candidates from previous run = " - + deleteCandidateList.size() + "\n"); - if (dontFixOrphansFlag) { - bw.write(" Note - we are not counting orphan nodes since the -dontFixOrphans parameter was used. \n"); - } - bw.write("Deleted this many delete candidates = " + deleteCount - + "\n"); - bw.write("Total number of nodes looked at = " + totalNodeCount - + "\n"); - bw.write("Ghost Nodes identified = " + ghostNodeCount + "\n"); - bw.write("Orphan Nodes identified = " + orphanNodeCount + "\n"); - bw.write("Bad Edges identified = " + oneArmedEdgeCount + "\n"); - bw.write("Missing Dependent Edge (but not orphaned) node count = " - + missingDepNodeCount + "\n"); - bw.write("Duplicate Groups count = " + dupeCount + "\n"); - bw.write("MisMatching Label/aai-node-type count = " - + misMatchedHash.size() + "\n"); - - bw.write("\n ------------- Delete Candidates ---------\n"); - for (Map.Entry<String, Vertex> entry : ghostNodeHash - .entrySet()) { - String vid = entry.getKey(); - bw.write("DeleteCandidate: Phantom Vid = [" + vid + "]\n"); - cleanupCandidateCount++; - } - for (Map.Entry<String, Vertex> entry : orphanNodeHash - .entrySet()) { - String vid = entry.getKey(); - bw.write("DeleteCandidate: OrphanDepNode Vid = [" + vid + "]\n"); - if (!dontFixOrphansFlag) { - cleanupCandidateCount++; - } - } - for (Map.Entry<String, Edge> entry : oneArmedEdgeHash.entrySet()) { - String eid = entry.getKey(); - bw.write("DeleteCandidate: Bad EDGE Edge-id = [" + eid + "]\n"); - cleanupCandidateCount++; - } - for (Map.Entry<String, Vertex> entry : missingDepNodeHash - .entrySet()) { - String vid = entry.getKey(); - bw.write("DeleteCandidate: (maybe) missingDepNode Vid = [" - + vid + "]\n"); - cleanupCandidateCount++; - } - bw.write("\n-- NOTE - To see DeleteCandidates for Duplicates, you need to look in the Duplicates Detail section below.\n"); - - bw.write("\n ------------- GHOST NODES - detail "); - for (Map.Entry<String, Vertex> entry : ghostNodeHash - .entrySet()) { - try { - String vid = entry.getKey(); - bw.write("\n ==> Phantom Vid = " + vid + "\n"); - ArrayList<String> retArr = showPropertiesForNode( - TRANSID, FROMAPPID, entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, FROMAPPID, - entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - } catch (Exception dex) { - LOGGER.error("error trying to print detail info for a ghost-node: ", dex); - } - } - - bw.write("\n ------------- Missing Dependent Edge ORPHAN NODES - detail: "); - for (Map.Entry<String, Vertex> entry : orphanNodeHash - .entrySet()) { - try { - String vid = entry.getKey(); - bw.write("\n> Orphan Node Vid = " + vid + "\n"); - ArrayList<String> retArr = showPropertiesForNode( - TRANSID, FROMAPPID, entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, FROMAPPID, - entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - } catch (Exception dex) { - LOGGER.error("error trying to print detail info for a Orphan Node /missing dependent edge", dex); - } - } - - bw.write("\n ------------- Missing Dependent Edge (but not orphan) NODES: "); - for (Map.Entry<String, Vertex> entry : missingDepNodeHash - .entrySet()) { - try { - String vid = entry.getKey(); - bw.write("\n> Missing edge to Dependent Node (but has edges) Vid = " - + vid + "\n"); - ArrayList<String> retArr = showPropertiesForNode( - TRANSID, FROMAPPID, entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, FROMAPPID, - entry.getValue()); - for (String info : retArr) { - bw.write(info + "\n"); - } - } catch (Exception dex) { - LOGGER.error("error trying to print detail info for a node missing its dependent edge but not an orphan", dex); - } - } - - bw.write("\n ------------- EDGES pointing to empty/bad vertices: "); - for (Map.Entry<String, Edge> entry : oneArmedEdgeHash.entrySet()) { - try { - String eid = entry.getKey(); - Edge thisE = entry.getValue(); - String badVid = emptyVertexHash.get(eid); - bw.write("\n> Edge pointing to bad vertex (Vid = " - + badVid + ") EdgeId = " + eid + "\n"); - bw.write("Label: [" + thisE.label() + "]\n"); - Iterator<Property<Object>> pI = thisE.properties(); - while (pI.hasNext()) { - Property<Object> propKey = pI.next(); - bw.write("Prop: [" + propKey + "], val = [" - + propKey.value() + "]\n"); - } - } catch (Exception pex) { - LOGGER.error("error trying to print empty/bad vertex data: ", pex); - } - } - - bw.write("\n ------------- Duplicates: "); - Iterator<String> dupeIter = dupeGroups.iterator(); - int dupeSetCounter = 0; - while (dupeIter.hasNext()) { - dupeSetCounter++; - String dset = (String) dupeIter.next(); - - bw.write("\n --- Duplicate Group # " + dupeSetCounter - + " Detail -----------\n"); - try { - // We expect each line to have at least two vid's, followed - // by the preferred one to KEEP - String[] dupeArr = dset.split("\\|"); - ArrayList<String> idArr = new ArrayList<>(); - int lastIndex = dupeArr.length - 1; - for (int i = 0; i <= lastIndex; i++) { - if (i < lastIndex) { - // This is not the last entry, it is one of the - // dupes, so we want to show all its info - bw.write(" >> Duplicate Group # " - + dupeSetCounter + " Node # " + i - + " ----\n"); - String vidString = dupeArr[i]; - idArr.add(vidString); - long longVertId = Long.parseLong(vidString); - Iterator<Vertex> vtxIterator = g.vertices(longVertId); - Vertex vtx = null; - if (vtxIterator.hasNext()) { - vtx = vtxIterator.next(); - } - ArrayList<String> retArr = showPropertiesForNode(TRANSID, FROMAPPID, vtx); - for (String info : retArr) { - bw.write(info + "\n"); - } - - retArr = showAllEdgesForNode(TRANSID, - FROMAPPID, vtx); - for (String info : retArr) { - bw.write(info + "\n"); - } - } else { - // This is the last entry which should tell us if we - // have a preferred keeper - String prefString = dupeArr[i]; - if (prefString.equals("KeepVid=UNDETERMINED")) { - bw.write("\n For this group of duplicates, could not tell which one to keep.\n"); - bw.write(" >>> This group needs to be taken care of with a manual/forced-delete.\n"); - } else { - // If we know which to keep, then the prefString - // should look like, "KeepVid=12345" - String[] prefArr = prefString.split("="); - if (prefArr.length != 2 - || (!prefArr[0].equals("KeepVid"))) { - throw new Exception("Bad format. Expecting KeepVid=999999"); - } else { - String keepVidStr = prefArr[1]; - if (idArr.contains(keepVidStr)) { - bw.write("\n The vertex we want to KEEP has vertexId = " - + keepVidStr); - bw.write("\n The others become delete candidates: \n"); - idArr.remove(keepVidStr); - for (int x = 0; x < idArr.size(); x++) { - cleanupCandidateCount++; - bw.write("DeleteCandidate: Duplicate Vid = [" - + idArr.get(x) + "]\n"); - } - } else { - throw new Exception("ERROR - Vertex Id to keep not found in list of dupes. dset = [" - + dset + "]"); - } - } - }// else we know which one to keep - }// else last entry - }// for each vertex in a group - } catch (Exception dex) { - LOGGER.error("error trying to print duplicate vertex data", dex); - } - - }// while - work on each group of dupes - - bw.write("\n ------------- Mis-matched Label/aai-node-type Nodes: \n "); - for (Map.Entry<String, String> entry : misMatchedHash.entrySet()) { - String msg = entry.getValue(); - bw.write("MixedMsg = " + msg + "\n"); - } - - bw.write("\n ------------- Got these errors while processing: \n"); - Iterator<String> errIter = errArr.iterator(); - while (errIter.hasNext()) { - String line = (String) errIter.next(); - bw.write(line + "\n"); - } - - bw.close(); - - LOGGER.info("\n ------------- Done doing all the checks ------------ "); - LOGGER.info("Output will be written to " + fullOutputFileName); - - if (cleanupCandidateCount > 0) { - // Technically, this is not an error -- but we're throwing this - // error so that hopefully a - // monitoring system will pick it up and do something with it. - throw new AAIException("AAI_6123", "See file: [" + fullOutputFileName - + "] and investigate delete candidates. "); - } - } catch (AAIException e) { - LOGGER.error("Caught AAIException while grooming data", e); - ErrorLogHelper.logException(e); - } catch (Exception ex) { - LOGGER.error("Caught exception while grooming data", ex); - ErrorLogHelper.logError("AAI_6128", ex.getMessage() + ", resolve and rerun dataGrooming"); - } finally { - - if (bw != null) { - try { - bw.close(); - } catch (IOException iox) { - LOGGER.warn("Got an IOException trying to close bufferedWriter() \n", iox); - } - } - - if (g != null && g.tx().isOpen()) { - // Any changes that worked correctly should have already done - // their commits. - try { - if (executeFinalCommit) { - g.tx().commit(); - } - g.tx().rollback(); - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed - LOGGER.warn("WARNING from final graphTransaction.rollback()", ex); - } - } - - if (g2 != null && g2.tx().isOpen()) { - // Any changes that worked correctly should have already done - // their commits. - try { - g2.tx().rollback(); - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed - LOGGER.warn("WARNING from final graphTransaction2.rollback()", ex); - } - } - - if( finalShutdownFlag ){ - try { - if( graph != null && graph.isOpen() ){ - graph.tx().close(); - graph.close(); - } - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed{ - LOGGER.warn("WARNING from final graph.shutdown()", ex); - } - - try { - if( graph2 != null && graph2.isOpen() ){ - graph2.tx().close(); - graph2.close(); - } - } catch (Exception ex) { - // Don't throw anything because Titan sometimes is just saying that the graph is already closed{ - LOGGER.warn("WARNING from final graph2.shutdown()", ex); - } - } - - } - - return cleanupCandidateCount; - - }// end of doTheGrooming() - - - /** - * Vertex has these keys. - * - * @param tmpV the tmp V - * @param propHashWithKeys the prop hash with keys - * @return the boolean - */ - private static Boolean vertexHasTheseKeys( Vertex tmpV, HashMap <String, Object> propHashWithKeys) { - Iterator <?> it = propHashWithKeys.entrySet().iterator(); - while( it.hasNext() ){ - String propName = ""; - String propVal = ""; - Map.Entry <?,?>propEntry = (Map.Entry<?,?>)it.next(); - Object propNameObj = propEntry.getKey(); - if( propNameObj != null ){ - propName = propNameObj.toString(); - } - Object propValObj = propEntry.getValue(); - if( propValObj != null ){ - propVal = propValObj.toString(); - } - Object checkValObj = tmpV.<Object>property(propName).orElse(null); - if( checkValObj == null ) { - return false; - } - else if( !propVal.equals(checkValObj.toString()) ){ - return false; - } - } - return true; - } - - - /** - * Any key fields missing. - * - * @param nType the n type - * @param v the v - * @return the boolean - */ - private static Boolean anyKeyFieldsMissing(String nType, Vertex v, Loader loader) { - - try { - Introspector obj = null; - try { - obj = loader.introspectorFromName(nType); - } catch (AAIUnknownObjectException e) { - // They gave us a non-empty nodeType but our NodeKeyProps does - // not have data for it. Since we do not know what the - // key params are for this type of node, we will just - // return "false". - String emsg = " -- WARNING -- Unrecognized nodeType: [" + nType - + "]. We cannot determine required keys for this nType. "; - // NOTE - this will be caught below and a "false" returned - throw new AAIException("AAI_6121", emsg); - } - - // Determine what the key fields are for this nodeType - Collection <String> keyPropNamesColl = obj.getKeys(); - Iterator<String> keyPropI = keyPropNamesColl.iterator(); - while (keyPropI.hasNext()) { - String propName = keyPropI.next(); - Object ob = v.<Object>property(propName).orElse(null); - if (ob == null || ob.toString().equals("")) { - // It is missing a key property - return true; - } - } - } catch (AAIException e) { - // Something was wrong -- but since we weren't able to check - // the keys, we will not declare that it is missing keys. - return false; - } - return false; - } - - - /** - * Gets the delete list. - * - * @param targetDir the target dir - * @param fileName the file name - * @param edgesOnlyFlag the edges only flag - * @param dontFixOrphans the dont fix orphans - * @param dupeFixOn the dupe fix on - * @return the delete list - * @throws AAIException the AAI exception - */ - private static Set<String> getDeleteList(String targetDir, - String fileName, Boolean edgesOnlyFlag, Boolean dontFixOrphans, - Boolean dupeFixOn) throws AAIException { - - // Look in the file for lines formated like we expect - pull out any - // Vertex Id's to delete on this run - Set<String> delList = new LinkedHashSet<>(); - String fullFileName = targetDir + AAIConstants.AAI_FILESEP + fileName; - - try(BufferedReader br = new BufferedReader(new FileReader(fullFileName))) { - String line = br.readLine(); - while (line != null) { - if (!"".equals(line) && line.startsWith("DeleteCandidate")) { - if (edgesOnlyFlag && (!line.contains("Bad Edge"))) { - // We're not going to process edge guys - } else if (dontFixOrphans && line.contains("Orphan")) { - // We're not going to process orphans - } else if (!dupeFixOn && line.contains("Duplicate")) { - // We're not going to process Duplicates - } else { - int begIndex = line.indexOf("id = "); - int endIndex = line.indexOf("]"); - String vidVal = line.substring(begIndex + 6, endIndex); - delList.add(vidVal); - } - } - line = br.readLine(); - } - br.close(); - } catch (IOException e) { - throw new AAIException("AAI_6124", e, "Could not open input-file [" + fullFileName - + "], exception= " + e.getMessage()); - } - - return delList; - - }// end of getDeleteList - - /** - * Gets the preferred dupe. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param dupeVertexList the dupe vertex list - * @param ver the ver - * @return Vertex - * @throws AAIException the AAI exception - */ - public static Vertex getPreferredDupe(String transId, - String fromAppId, GraphTraversalSource g, - ArrayList<Vertex> dupeVertexList, String ver, Loader loader) - throws AAIException { - - // This method assumes that it is being passed a List of vertex objects - // which - // violate our uniqueness constraints. - - Vertex nullVtx = null; - - if (dupeVertexList == null) { - return nullVtx; - } - int listSize = dupeVertexList.size(); - if (listSize == 0) { - return nullVtx; - } - if (listSize == 1) { - return (dupeVertexList.get(0)); - } - - Vertex vtxPreferred = null; - Vertex currentFaveVtx = dupeVertexList.get(0); - for (int i = 1; i < listSize; i++) { - Vertex vtxB = dupeVertexList.get(i); - vtxPreferred = pickOneOfTwoDupes(transId, fromAppId, g, - currentFaveVtx, vtxB, ver, loader); - if (vtxPreferred == null) { - // We couldn't choose one - return nullVtx; - } else { - currentFaveVtx = vtxPreferred; - } - } - - return (currentFaveVtx); - - } // end of getPreferredDupe() - - /** - * Pick one of two dupes. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param vtxA the vtx A - * @param vtxB the vtx B - * @param ver the ver - * @return Vertex - * @throws AAIException the AAI exception - */ - public static Vertex pickOneOfTwoDupes(String transId, - String fromAppId, GraphTraversalSource g, Vertex vtxA, - Vertex vtxB, String ver, Loader loader) throws AAIException { - - Vertex nullVtx = null; - Vertex preferredVtx = null; - - Long vidA = new Long(vtxA.id().toString()); - Long vidB = new Long(vtxB.id().toString()); - - String vtxANodeType = ""; - String vtxBNodeType = ""; - Object objType = vtxA.<Object>property("aai-node-type").orElse(null); - if (objType != null) { - vtxANodeType = objType.toString(); - } - objType = vtxB.<Object>property("aai-node-type").orElse(null); - if (objType != null) { - vtxBNodeType = objType.toString(); - } - - if (vtxANodeType.equals("") || (!vtxANodeType.equals(vtxBNodeType))) { - // Either they're not really dupes or there's some bad data - so - // don't pick one - return nullVtx; - } - - // Check that node A and B both have the same key values (or else they - // are not dupes) - // (We'll check dep-node later) - // Determine what the key fields are for this nodeType - Collection <String> keyProps = new ArrayList <>(); - try { - keyProps = loader.introspectorFromName(vtxANodeType).getKeys(); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Required property not found", e); - throw new AAIException("AAI_6105", "Required Property name(s) not found for nodeType = " + vtxANodeType + ")"); - } - - Iterator<String> keyPropI = keyProps.iterator(); - while (keyPropI.hasNext()) { - String propName = keyPropI.next(); - String vtxAKeyPropVal = ""; - objType = vtxA.<Object>property(propName).orElse(null); - if (objType != null) { - vtxAKeyPropVal = objType.toString(); - } - String vtxBKeyPropVal = ""; - objType = vtxB.<Object>property(propName).orElse(null); - if (objType != null) { - vtxBKeyPropVal = objType.toString(); - } - - if (vtxAKeyPropVal.equals("") - || (!vtxAKeyPropVal.equals(vtxBKeyPropVal))) { - // Either they're not really dupes or they are missing some key - // data - so don't pick one - return nullVtx; - } - } - - // Collect the vid's and aai-node-types of the vertices that each vertex - // (A and B) is connected to. - ArrayList<String> vtxIdsConn2A = new ArrayList<>(); - ArrayList<String> vtxIdsConn2B = new ArrayList<>(); - HashMap<String, String> nodeTypesConn2A = new HashMap<>(); - HashMap<String, String> nodeTypesConn2B = new HashMap<>(); - - ArrayList<Vertex> vertListA = getConnectedNodes( g, vtxA ); - if (vertListA != null) { - Iterator<Vertex> iter = vertListA.iterator(); - while (iter.hasNext()) { - Vertex tvCon = iter.next(); - String conVid = tvCon.id().toString(); - String nt = ""; - objType = tvCon.<Object>property("aai-node-type").orElse(null); - if (objType != null) { - nt = objType.toString(); - } - nodeTypesConn2A.put(nt, conVid); - vtxIdsConn2A.add(conVid); - } - } - - ArrayList<Vertex> vertListB = getConnectedNodes( g, vtxB ); - if (vertListB != null) { - Iterator<Vertex> iter = vertListB.iterator(); - while (iter.hasNext()) { - Vertex tvCon = iter.next(); - String conVid = tvCon.id().toString(); - String nt = ""; - objType = tvCon.<Object>property("aai-node-type").orElse(null); - if (objType != null) { - nt = objType.toString(); - } - nodeTypesConn2B.put(nt, conVid); - vtxIdsConn2B.add(conVid); - } - } - - // 1 - If this kind of node needs a dependent node for uniqueness, then - // verify that they both nodes - // point to the same dependent node (otherwise they're not really - // duplicates) - // Note - there are sometimes more than one dependent node type since - // one nodeType can be used in - // different ways. But for a particular node, it will only have one - // dependent node that it's - // connected to. - Collection <String> depNodeTypes = loader.introspectorFromName(vtxANodeType).getDependentOn(); - - if (depNodeTypes.isEmpty()) { - // This kind of node is not dependent on any other. That is ok. - } else { - String depNodeVtxId4A = ""; - String depNodeVtxId4B = ""; - Iterator<String> iter = depNodeTypes.iterator(); - while (iter.hasNext()) { - String depNodeType = iter.next(); - if (nodeTypesConn2A.containsKey(depNodeType)) { - // This is the dependent node type that vertex A is using - depNodeVtxId4A = nodeTypesConn2A.get(depNodeType); - } - if (nodeTypesConn2B.containsKey(depNodeType)) { - // This is the dependent node type that vertex B is using - depNodeVtxId4B = nodeTypesConn2B.get(depNodeType); - } - } - if (depNodeVtxId4A.equals("") - || (!depNodeVtxId4A.equals(depNodeVtxId4B))) { - // Either they're not really dupes or there's some bad data - so - // don't pick either one - return nullVtx; - } - } - - if (vtxIdsConn2A.size() == vtxIdsConn2B.size()) { - // 2 - If they both have edges to all the same vertices, then return - // the one with the lower vertexId. - boolean allTheSame = true; - Iterator<String> iter = vtxIdsConn2A.iterator(); - while (iter.hasNext()) { - String vtxIdConn2A = iter.next(); - if (!vtxIdsConn2B.contains(vtxIdConn2A)) { - allTheSame = false; - break; - } - } - - if (allTheSame) { - if (vidA < vidB) { - preferredVtx = vtxA; - } else { - preferredVtx = vtxB; - } - } - } else if (vtxIdsConn2A.size() > vtxIdsConn2B.size()) { - // 3 - VertexA is connected to more things than vtxB. - // We'll pick VtxA if its edges are a superset of vtxB's edges. - boolean missingOne = false; - Iterator<String> iter = vtxIdsConn2B.iterator(); - while (iter.hasNext()) { - String vtxIdConn2B = iter.next(); - if (!vtxIdsConn2A.contains(vtxIdConn2B)) { - missingOne = true; - break; - } - } - if (!missingOne) { - preferredVtx = vtxA; - } - } else if (vtxIdsConn2B.size() > vtxIdsConn2A.size()) { - // 4 - VertexB is connected to more things than vtxA. - // We'll pick VtxB if its edges are a superset of vtxA's edges. - boolean missingOne = false; - Iterator<String> iter = vtxIdsConn2A.iterator(); - while (iter.hasNext()) { - String vtxIdConn2A = iter.next(); - if (!vtxIdsConn2B.contains(vtxIdConn2A)) { - missingOne = true; - break; - } - } - if (!missingOne) { - preferredVtx = vtxB; - } - } else { - preferredVtx = nullVtx; - } - - return (preferredVtx); - - } // end of pickOneOfTwoDupes() - - /** - * Check and process dupes. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param version the version - * @param nType the n type - * @param passedVertList the passed vert list - * @param dupeFixOn the dupe fix on - * @param deleteCandidateList the delete candidate list - * @param singleCommits the single commits - * @param alreadyFoundDupeGroups the already found dupe groups - * @param dbMaps the db maps - * @return the array list - */ - private static List<String> checkAndProcessDupes(String transId, - String fromAppId, Graph g, GraphTraversalSource source, String version, String nType, - List<Vertex> passedVertList, Boolean dupeFixOn, - Set<String> deleteCandidateList, Boolean singleCommits, - ArrayList<String> alreadyFoundDupeGroups, Loader loader ) { - - ArrayList<String> returnList = new ArrayList<>(); - ArrayList<Vertex> checkVertList = new ArrayList<>(); - ArrayList<String> alreadyFoundDupeVidArr = new ArrayList<>(); - Boolean noFilterList = true; - Iterator<String> afItr = alreadyFoundDupeGroups.iterator(); - while (afItr.hasNext()) { - String dupeGrpStr = afItr.next(); - String[] dupeArr = dupeGrpStr.split("\\|"); - int lastIndex = dupeArr.length - 1; - for (int i = 0; i < lastIndex; i++) { - // Note: we don't want the last one... - String vidString = dupeArr[i]; - alreadyFoundDupeVidArr.add(vidString); - noFilterList = false; - } - } - - // For a given set of Nodes that were found with a set of KEY - // Parameters, (nodeType + key data) we will - // see if we find any duplicate nodes that need to be cleaned up. Note - - // it's legit to have more than one - // node with the same key data if the nodes depend on a parent for - // uniqueness -- as long as the two nodes - // don't hang off the same Parent. - // If we find duplicates, and we can figure out which of each set of - // duplicates is the one that we - // think should be preserved, we will record that. Whether we can tell - // which one should be - // preserved or not, we will return info about any sets of duplicates - // found. - // - // Each element in the returned arrayList might look like this: - // "1234|5678|keepVid=UNDETERMINED" (if there were 2 dupes, and we - // couldn't figure out which one to keep) - // or, "100017|200027|30037|keepVid=30037" (if there were 3 dupes and we - // thought the third one was the one that should survive) - - // Because of the way the calling code loops over stuff, we can get the - // same data multiple times - so we should - // not process any vertices that we've already seen. - - try { - Iterator<Vertex> pItr = passedVertList.iterator(); - while (pItr.hasNext()) { - Vertex tvx = pItr.next(); - String passedId = tvx.id().toString(); - if (noFilterList || !alreadyFoundDupeVidArr.contains(passedId)) { - // We haven't seen this one before - so we should check it. - checkVertList.add(tvx); - } - } - - if (checkVertList.size() < 2) { - // Nothing new to check. - return returnList; - } - - if (loader.introspectorFromName(nType).isTopLevel()) { - // If this was a node that does NOT depend on other nodes for - // uniqueness, and we - // found more than one node using its key -- record the found - // vertices as duplicates. - String dupesStr = ""; - for (int i = 0; i < checkVertList.size(); i++) { - dupesStr = dupesStr - + ((checkVertList.get(i))).id() - .toString() + "|"; - } - if (dupesStr != "") { - Vertex prefV = getPreferredDupe(transId, fromAppId, - source, checkVertList, version, loader); - if (prefV == null) { - // We could not determine which duplicate to keep - dupesStr = dupesStr + "KeepVid=UNDETERMINED"; - returnList.add(dupesStr); - } else { - dupesStr = dupesStr + "KeepVid=" + prefV.id(); - Boolean didRemove = false; - if (dupeFixOn) { - didRemove = deleteNonKeepersIfAppropriate(g, - dupesStr, prefV.id().toString(), - deleteCandidateList, singleCommits); - } - if (didRemove) { - dupeGrpsDeleted++; - } else { - // keep them on our list - returnList.add(dupesStr); - } - } - } - } else { - // More than one node have the same key fields since they may - // depend on a parent node for uniqueness. Since we're finding - // more than one, we want to check to see if any of the - // vertices that have this set of keys (and are the same nodeType) - // are also pointing at the same 'parent' node. - // Note: for a given set of key data, it is possible that there - // could be more than one set of duplicates. - HashMap<String, ArrayList<Vertex>> vertsGroupedByParentHash = groupVertsByDepNodes( - transId, fromAppId, source, version, nType, - checkVertList, loader); - for (Map.Entry<String, ArrayList<Vertex>> entry : vertsGroupedByParentHash - .entrySet()) { - ArrayList<Vertex> thisParentsVertList = entry - .getValue(); - if (thisParentsVertList.size() > 1) { - // More than one vertex found with the same key info - // hanging off the same parent/dependent node - String dupesStr = ""; - for (int i = 0; i < thisParentsVertList.size(); i++) { - dupesStr = dupesStr - + ((thisParentsVertList - .get(i))).id() + "|"; - } - if (dupesStr != "") { - Vertex prefV = getPreferredDupe(transId, - fromAppId, source, thisParentsVertList, - version, loader); - - if (prefV == null) { - // We could not determine which duplicate to - // keep - dupesStr = dupesStr + "KeepVid=UNDETERMINED"; - returnList.add(dupesStr); - } else { - Boolean didRemove = false; - dupesStr = dupesStr + "KeepVid=" - + prefV.id().toString(); - if (dupeFixOn) { - didRemove = deleteNonKeepersIfAppropriate( - g, dupesStr, prefV.id() - .toString(), - deleteCandidateList, singleCommits); - } - if (didRemove) { - dupeGrpsDeleted++; - } else { - // keep them on our list - returnList.add(dupesStr); - } - } - } - } - } - } - } catch (Exception e) { - LOGGER.warn(" >>> Threw an error in checkAndProcessDupes - just absorb this error and move on. ", e); - } - - return returnList; - - }// End of checkAndProcessDupes() - - /** - * Group verts by dep nodes. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param g the g - * @param version the version - * @param nType the n type - * @param passedVertList the passed vert list - * @param dbMaps the db maps - * @return the hash map - * @throws AAIException the AAI exception - */ - private static HashMap<String, ArrayList<Vertex>> groupVertsByDepNodes( - String transId, String fromAppId, GraphTraversalSource g, String version, - String nType, ArrayList<Vertex> passedVertList, Loader loader) - throws AAIException { - // Given a list of Titan Vertices of one nodeType (see AAI-8956), group - // them together by the parent node they depend on. - // Ie. if given a list of ip address nodes (assumed to all have the - // same key info) they might sit under several different parent vertices. - // Under Normal conditions, there would only be one per parent -- but - // we're trying to find duplicates - so we - // allow for the case where more than one is under the same parent node. - - HashMap<String, ArrayList<Vertex>> retHash = new HashMap<String, ArrayList<Vertex>>(); - if (loader.introspectorFromName(nType).isTopLevel()) { - // This method really should not have been called if this is not the - // kind of node - // that depends on a parent for uniqueness, so just return the empty - // hash. - return retHash; - } - - // Find out what types of nodes the passed in nodes can depend on - ArrayList<String> depNodeTypeL = new ArrayList<>(); - Collection<String> depNTColl = loader.introspectorFromName(nType).getDependentOn(); - Iterator<String> ntItr = depNTColl.iterator(); - while (ntItr.hasNext()) { - depNodeTypeL.add(ntItr.next()); - } - // For each vertex, we want find its depended-on/parent vertex so we - // can track what other vertexes that are dependent on that same guy. - if (passedVertList != null) { - Iterator<Vertex> iter = passedVertList.iterator(); - while (iter.hasNext()) { - Vertex thisVert = iter.next(); - Vertex tmpParentVtx = getConnectedParent( g, thisVert ); - if( tmpParentVtx != null ) { - String parentNt = null; - Object obj = tmpParentVtx.<Object>property("aai-node-type").orElse(null); - if (obj != null) { - parentNt = obj.toString(); - } - if (depNTColl.contains(parentNt)) { - // This must be the parent/dependent node - String parentVid = tmpParentVtx.id().toString(); - if (retHash.containsKey(parentVid)) { - // add this vert to the list for this parent key - retHash.get(parentVid).add(thisVert); - } else { - // This is the first one we found on this parent - ArrayList<Vertex> vList = new ArrayList<>(); - vList.add(thisVert); - retHash.put(parentVid, vList); - } - } - } - } - } - - return retHash; - - }// end of groupVertsByDepNodes() - - /** - * Delete non keepers if appropriate. - * - * @param g the g - * @param dupeInfoString the dupe info string - * @param vidToKeep the vid to keep - * @param deleteCandidateList the delete candidate list - * @param singleCommits the single commits - * @return the boolean - */ - private static Boolean deleteNonKeepersIfAppropriate(Graph g, - String dupeInfoString, String vidToKeep, - Set<String> deleteCandidateList, Boolean singleCommits) { - - Boolean deletedSomething = false; - // This assumes that the dupeInfoString is in the format of - // pipe-delimited vid's followed by - // ie. "3456|9880|keepVid=3456" - if (deleteCandidateList == null || deleteCandidateList.size() == 0) { - // No vid's on the candidate list -- so no deleting will happen on - // this run - return false; - } - - String[] dupeArr = dupeInfoString.split("\\|"); - ArrayList<String> idArr = new ArrayList<>(); - int lastIndex = dupeArr.length - 1; - for (int i = 0; i <= lastIndex; i++) { - if (i < lastIndex) { - // This is not the last entry, it is one of the dupes, - String vidString = dupeArr[i]; - idArr.add(vidString); - } else { - // This is the last entry which should tell us if we have a - // preferred keeper - String prefString = dupeArr[i]; - if (prefString.equals("KeepVid=UNDETERMINED")) { - // They sent us a bad string -- nothing should be deleted if - // no dupe could be tagged as preferred - return false; - } else { - // If we know which to keep, then the prefString should look - // like, "KeepVid=12345" - String[] prefArr = prefString.split("="); - if (prefArr.length != 2 || (!prefArr[0].equals("KeepVid"))) { - LOGGER.error("Bad format. Expecting KeepVid=999999"); - return false; - } else { - String keepVidStr = prefArr[1]; - if (idArr.contains(keepVidStr)) { - idArr.remove(keepVidStr); - - // So now, the idArr should just contain the vid's - // that we want to remove. - for (int x = 0; x < idArr.size(); x++) { - boolean okFlag = true; - String thisVid = idArr.get(x); - if (deleteCandidateList.contains(thisVid)) { - // This vid is a valid delete candidate from - // a prev. run, so we can remove it. - try { - long longVertId = Long - .parseLong(thisVid); - Vertex vtx = g - .traversal().V(longVertId).next(); - vtx.remove(); - if (singleCommits) { - // NOTE - the singleCommits option is not used in normal processing - g.tx().commit(); - g = AAIGraph.getInstance().getGraph().newTransaction(); - } - } catch (Exception e) { - okFlag = false; - LOGGER.error("ERROR trying to delete VID = " + thisVid, e); - } - if (okFlag) { - LOGGER.info(" DELETED VID = " + thisVid); - deletedSomething = true; - } - } - } - } else { - LOGGER.error("ERROR - Vertex Id to keep not found in list of dupes. dupeInfoString = [" - + dupeInfoString + "]"); - return false; - } - } - }// else we know which one to keep - }// else last entry - }// for each vertex in a group - - return deletedSomething; - - }// end of deleteNonKeepersIfAppropriate() - - - /** - * Gets the node just using key params. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param graph the graph - * @param nodeType the node type - * @param keyPropsHash the key props hash - * @param apiVersion the api version - * @return the node just using key params - * @throws AAIException the AAI exception - */ - public static List <Vertex> getNodeJustUsingKeyParams( String transId, String fromAppId, GraphTraversalSource graph, String nodeType, - HashMap<String,Object> keyPropsHash, String apiVersion ) throws AAIException{ - - List <Vertex> retVertList = new ArrayList <> (); - - // We assume that all NodeTypes have at least one key-property defined. - // Note - instead of key-properties (the primary key properties), a user could pass - // alternate-key values if they are defined for the nodeType. - List<String> kName = new ArrayList<>(); - List<Object> kVal = new ArrayList<>(); - if( keyPropsHash == null || keyPropsHash.isEmpty() ) { - throw new AAIException("AAI_6120", " NO key properties passed for this getNodeJustUsingKeyParams() request. NodeType = [" + nodeType + "]. "); - } - - int i = -1; - for( Map.Entry<String, Object> entry : keyPropsHash.entrySet() ){ - i++; - kName.add(i, entry.getKey()); - kVal.add(i, entry.getValue()); - } - int topPropIndex = i; - Vertex tiV = null; - String propsAndValuesForMsg = ""; - Iterator <Vertex> verts = null; - - try { - if( topPropIndex == 0 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ") "; - verts= graph.V().has(kName.get(0),kVal.get(0)).has("aai-node-type",nodeType); - } - else if( topPropIndex == 1 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " - + kName.get(1) + " = " + kVal.get(1) + ") "; - verts = graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has("aai-node-type",nodeType); - } - else if( topPropIndex == 2 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " - + kName.get(1) + " = " + kVal.get(1) + ", " - + kName.get(2) + " = " + kVal.get(2) + ") "; - verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has("aai-node-type",nodeType); - } - else if( topPropIndex == 3 ){ - propsAndValuesForMsg = " (" + kName.get(0) + " = " + kVal.get(0) + ", " - + kName.get(1) + " = " + kVal.get(1) + ", " - + kName.get(2) + " = " + kVal.get(2) + ", " - + kName.get(3) + " = " + kVal.get(3) + ") "; - verts= graph.V().has(kName.get(0),kVal.get(0)).has(kName.get(1),kVal.get(1)).has(kName.get(2),kVal.get(2)).has(kName.get(3),kVal.get(3)).has("aai-node-type",nodeType); - } - else { - throw new AAIException("AAI_6114", " We only support 4 keys per nodeType for now \n"); - } - } - catch( Exception ex ){ - LOGGER.error( " ERROR trying to get node for: [" + propsAndValuesForMsg + "]", ex); - } - - if( verts != null ){ - while( verts.hasNext() ){ - tiV = verts.next(); - retVertList.add(tiV); - } - } - - if( retVertList.size() == 0 ){ - LOGGER.debug("DEBUG No node found for nodeType = [" + nodeType + - "], propsAndVal = " + propsAndValuesForMsg ); - } - - return retVertList; - - }// End of getNodeJustUsingKeyParams() - - /** - * Show all edges for node. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param tVert the t vert - * @return the array list - */ - private static ArrayList <String> showAllEdgesForNode( String transId, String fromAppId, Vertex tVert ){ - - ArrayList <String> retArr = new ArrayList <> (); - Iterator <Edge> eI = tVert.edges(Direction.IN); - if( ! eI.hasNext() ){ - retArr.add("No IN edges were found for this vertex. "); - } - while( eI.hasNext() ){ - Edge ed = eI.next(); - String lab = ed.label(); - Vertex vtx; - if (tVert.equals(ed.inVertex())) { - vtx = ed.outVertex(); - } else { - vtx = ed.inVertex(); - } - if( vtx == null ){ - retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); - } - else { - String nType = vtx.<String>property("aai-node-type").orElse(null); - String vid = vtx.id().toString(); - retArr.add("Found an IN edge (" + lab + ") to this vertex from a [" + nType + "] node with VtxId = " + vid ); - - } - } - - eI = tVert.edges(Direction.OUT); - if( ! eI.hasNext() ){ - retArr.add("No OUT edges were found for this vertex. "); - } - while( eI.hasNext() ){ - Edge ed = eI.next(); - String lab = ed.label(); - Vertex vtx; - if (tVert.equals(ed.inVertex())) { - vtx = ed.outVertex(); - } else { - vtx = ed.inVertex(); - } - if( vtx == null ){ - retArr.add(" >>> COULD NOT FIND VERTEX on the other side of this edge edgeId = " + ed.id() + " <<< "); - } - else { - String nType = vtx.<String>property("aai-node-type").orElse(null); - String vid = vtx.id().toString(); - retArr.add("Found an OUT edge (" + lab + ") from this vertex to a [" + nType + "] node with VtxId = " + vid ); - } - } - return retArr; - } - - - /** - * Show properties for node. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param tVert the t vert - * @return the array list - */ - private static ArrayList <String> showPropertiesForNode( String transId, String fromAppId, Vertex tVert ){ - - ArrayList <String> retArr = new ArrayList <> (); - if( tVert == null ){ - retArr.add("null Node object passed to showPropertiesForNode()\n"); - } - else { - String nodeType = ""; - Object ob = tVert.<Object>property("aai-node-type").orElse(null); - if( ob == null ){ - nodeType = "null"; - } - else{ - nodeType = ob.toString(); - } - - retArr.add(" AAINodeType/VtxID for this Node = [" + nodeType + "/" + tVert.id() + "]"); - retArr.add(" Property Detail: "); - Iterator<VertexProperty<Object>> pI = tVert.properties(); - while( pI.hasNext() ){ - VertexProperty<Object> tp = pI.next(); - Object val = tp.value(); - retArr.add("Prop: [" + tp.key() + "], val = [" + val + "] "); - } - } - return retArr; - } - - - private static ArrayList <Vertex> getConnectedNodes(GraphTraversalSource g, Vertex startVtx ) - throws AAIException { - - ArrayList <Vertex> retArr = new ArrayList <> (); - if( startVtx == null ){ - return retArr; - } - else { - GraphTraversal<Vertex, Vertex> modPipe = null; - modPipe = g.V(startVtx).both(); - if( modPipe != null && modPipe.hasNext() ){ - while( modPipe.hasNext() ){ - Vertex conVert = modPipe.next(); - retArr.add(conVert); - } - } - } - return retArr; - - }// End of getConnectedNodes() - - - private static ArrayList <Vertex> getConnectedChildrenOfOneType( GraphTraversalSource g, - Vertex startVtx, String childNType ) throws AAIException{ - - ArrayList <Vertex> childList = new ArrayList <> (); - Iterator <Vertex> vertI = g.V(startVtx).union(__.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).inV(), __.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).outV()); - - Vertex tmpVtx = null; - while( vertI != null && vertI.hasNext() ){ - tmpVtx = vertI.next(); - Object ob = tmpVtx.<Object>property("aai-node-type").orElse(null); - if (ob != null) { - String tmpNt = ob.toString(); - if( tmpNt.equals(childNType)){ - childList.add(tmpVtx); - } - } - } - - return childList; - - }// End of getConnectedChildrenOfOneType() - - - private static Vertex getConnectedParent( GraphTraversalSource g, - Vertex startVtx ) throws AAIException{ - - Vertex parentVtx = null; - Iterator <Vertex> vertI = g.V(startVtx).union(__.inE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).outV(), __.outE().has(EdgeProperty.CONTAINS.toString(), AAIDirection.IN.toString()).inV()); - - while( vertI != null && vertI.hasNext() ){ - // Note - there better only be one! - parentVtx = vertI.next(); - } - - return parentVtx; - - }// End of getConnectedParent() - - - private static long figureWindowStartTime( int timeWindowMinutes ){ - // Given a window size, calculate what the start-timestamp would be. - - if( timeWindowMinutes <= 0 ){ - // This just means that there is no window... - return 0; - } - long unixTimeNow = System.currentTimeMillis(); - long windowInMillis = timeWindowMinutes * 60L * 1000; - - long startTimeStamp = unixTimeNow - windowInMillis; - - return startTimeStamp; - } // End of figureWindowStartTime() - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/GenTester.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/GenTester.java deleted file mode 100644 index 7847d3d6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/GenTester.java +++ /dev/null @@ -1,143 +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 com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; -import org.openecomp.aai.dbmap.AAIGraph; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; - -import java.util.Properties; - - -public class GenTester { - - private static EELFLogger LOGGER; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - TitanGraph graph = null; - - // Set the logging file properties to be used by EELFManager - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, AAIConstants.AAI_CREATE_DB_SCHEMA_LOGBACK_PROPS); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - LOGGER = EELFManager.getInstance().getLogger(GenTester.class); - boolean addDefaultCR = true; - - try { - AAIConfig.init(); - if (args != null && args.length > 0 ){ - if( "genDbRulesOnly".equals(args[0]) ){ - ErrorLogHelper.logError("AAI_3100", - " This option is no longer supported. What was in DbRules is now derived from the OXM files. "); - return; - } - else if ( "GEN_DB_WITH_NO_SCHEMA".equals(args[0]) ){ - // Note this is done to create an empty DB with no Schema so that - // an HBase copyTable can be used to set up a copy of the db. - String imsg = " ---- NOTE --- about to load a graph without doing any schema processing (takes a little while) -------- "; - System.out.println(imsg); - LOGGER.info(imsg); - graph = AAIGraph.getInstance().getGraph(); - - if( graph == null ){ - ErrorLogHelper.logError("AAI_5102", "Error creating Titan graph."); - return; - } - else { - String amsg = "Successfully loaded a Titan graph without doing any schema work. "; - System.out.println(amsg); - LOGGER.auditEvent(amsg); - return; - } - } else if ("GEN_DB_WITH_NO_DEFAULT_CR".equals(args[0])) { - addDefaultCR = false; - } - else { - ErrorLogHelper.logError("AAI_3000", "Unrecognized argument passed to GenTester.java: [" + args[0] + "]. "); - - String emsg = "Unrecognized argument passed to GenTester.java: [" + args[0] + "]. "; - System.out.println(emsg); - LOGGER.error(emsg); - - emsg = "Either pass no argument for normal processing, or use 'GEN_DB_WITH_NO_SCHEMA'."; - System.out.println(emsg); - LOGGER.error(emsg); - - return; - } - } - - //AAIConfig.init(); - ErrorLogHelper.loadProperties(); - String imsg = " ---- NOTE --- about to open graph (takes a little while)--------;"; - System.out.println(imsg); - LOGGER.info(imsg); - graph = AAIGraph.getInstance().getGraph(); - - if( graph == null ){ - ErrorLogHelper.logError("AAI_5102", "Error creating Titan graph. "); - return; - } - - // Load the propertyKeys, indexes and edge-Labels into the DB - TitanManagement graphMgt = graph.openManagement(); - - imsg = "-- Loading new schema elements into Titan --"; - System.out.println(imsg); - LOGGER.info(imsg); - SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt, addDefaultCR ); - - } catch(Exception ex) { - ErrorLogHelper.logError("AAI_4000", ex.getMessage()); - } - - - if( graph != null ){ - String imsg = "-- graph commit"; - System.out.println(imsg); - LOGGER.info(imsg); - graph.tx().commit(); - - imsg = "-- graph shutdown "; - System.out.println(imsg); - LOGGER.info(imsg); - graph.close(); - } - - LOGGER.auditEvent("-- all done, if program does not exit, please kill."); - System.exit(0); - } - -} - - diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/PropertyLimitDesc.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/PropertyLimitDesc.java deleted file mode 100644 index 8d0bf7ea..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/PropertyLimitDesc.java +++ /dev/null @@ -1,27 +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; - -public enum PropertyLimitDesc { - SHOW_NONE, - SHOW_ALL, - SHOW_NAME_AND_KEYS_ONLY -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dbgen/SchemaGenerator.java b/aai-core/src/main/java/org/openecomp/aai/dbgen/SchemaGenerator.java deleted file mode 100644 index 9f85d029..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbgen/SchemaGenerator.java +++ /dev/null @@ -1,193 +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.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.util.AAIConfig; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.collect.Multimap; -import com.thinkaurelius.titan.core.Cardinality; -import com.thinkaurelius.titan.core.Multiplicity; -import com.thinkaurelius.titan.core.PropertyKey; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; - - - -public class SchemaGenerator{ - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(SchemaGenerator.class); - private static boolean addDefaultCR = true; - - - /** - * Load schema into titan. - * - * @param graph the graph - * @param graphMgmt the graph mgmt - * @param addDefaultCloudRegion the add default cloud region - */ - public static void loadSchemaIntoTitan(final TitanGraph graph, final TitanManagement graphMgmt, boolean addDefaultCloudRegion) { - addDefaultCR = addDefaultCloudRegion; - loadSchemaIntoTitan(graph, graphMgmt); - } - - /** - * Load schema into titan. - * - * @param graph the graph - * @param graphMgmt the graph mgmt - */ - public static void loadSchemaIntoTitan(final TitanGraph graph, final TitanManagement graphMgmt) { - - try { - AAIConfig.init(); - } - catch (Exception ex){ - LOGGER.error(" ERROR - Could not run AAIConfig.init(). ", ex); - System.out.println(" ERROR - Could not run AAIConfig.init(). "); - System.exit(1); - } - - // NOTE - Titan 0.5.3 doesn't keep a list of legal node Labels. - // They are only used when a vertex is actually being created. Titan 1.1 will keep track (we think). - - - // Use EdgeRules to make sure edgeLabels are defined in the db. NOTE: the multiplicty used here is - // always "MULTI". This is not the same as our internal "Many2Many", "One2One", "One2Many" or "Many2One" - // We use the same edge-label for edges between many different types of nodes and our internal - // multiplicty definitions depends on which two types of nodes are being connected. - - Multimap<String, EdgeRule> edges = null; - Set<String> labels = new HashSet<>(); - - edges = EdgeRules.getInstance().getAllRules(); - for (EdgeRule rule : edges.values()) { - labels.add(rule.getLabel()); - } - - for( String label: labels){ - if( graphMgmt.containsRelationType(label) ) { - String dmsg = " EdgeLabel [" + label + "] already existed. "; - System.out.println(dmsg); - LOGGER.debug(dmsg); - } else { - String dmsg = "Making EdgeLabel: [" + label + "]"; - System.out.println(dmsg); - LOGGER.debug(dmsg); - graphMgmt.makeEdgeLabel(label).multiplicity(Multiplicity.valueOf("MULTI")).make(); - } - } - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - Map<String, Introspector> objs = loader.getAllObjects(); - Map<String, PropertyKey> seenProps = new HashMap<>(); - - for (Introspector obj : objs.values()) { - for (String propName : obj.getProperties()) { - String dbPropName = propName; - Optional<String> alias = obj.getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS); - if (alias.isPresent()) { - dbPropName = alias.get(); - } - if( graphMgmt.containsRelationType(propName) ){ - String dmsg = " PropertyKey [" + propName + "] already existed in the DB. "; - System.out.println(dmsg); - LOGGER.debug(dmsg); - } else { - Class<?> type = obj.getClass(propName); - Cardinality cardinality = Cardinality.SINGLE; - boolean process = false; - if (obj.isListType(propName) && obj.isSimpleGenericType(propName)) { - cardinality = Cardinality.SET; - type = obj.getGenericTypeClass(propName); - process = true; - } else if (obj.isSimpleType(propName)) { - process = true; - } - - if (process) { - - String imsg = "Creating PropertyKey: [" + dbPropName + "], ["+ type.getSimpleName() + "], [" + cardinality + "]"; - System.out.println(imsg); - LOGGER.info(imsg); - PropertyKey propK; - if (!seenProps.containsKey(dbPropName)) { - propK = graphMgmt.makePropertyKey(dbPropName).dataType(type).cardinality(cardinality).make(); - seenProps.put(dbPropName, propK); - } else { - propK = seenProps.get(dbPropName); - } - if (graphMgmt.containsGraphIndex(dbPropName)) { - String dmsg = " Index [" + dbPropName + "] already existed in the DB. "; - System.out.println(dmsg); - LOGGER.debug(dmsg); - } else { - if( obj.getIndexedProperties().contains(propName) ){ - if( obj.getUniqueProperties().contains(propName) ){ - imsg = "Add Unique index for PropertyKey: [" + dbPropName + "]"; - System.out.println(imsg); - LOGGER.info(imsg); - graphMgmt.buildIndex(dbPropName,Vertex.class).addKey(propK).unique().buildCompositeIndex(); - } else { - imsg = "Add index for PropertyKey: [" + dbPropName + "]"; - System.out.println(imsg); - LOGGER.info(imsg); - graphMgmt.buildIndex(dbPropName,Vertex.class).addKey(propK).buildCompositeIndex(); - } - } else { - imsg = "No index added for PropertyKey: [" + dbPropName + "]"; - System.out.println(imsg); - LOGGER.info(imsg); - } - } - } - } - } - } - - String imsg = "-- About to call graphMgmt commit"; - System.out.println(imsg); - LOGGER.info(imsg); - - graphMgmt.commit(); - }// End of loadSchemaIntoTitan() - -} - - diff --git a/aai-core/src/main/java/org/openecomp/aai/dbmap/AAIGraph.java b/aai-core/src/main/java/org/openecomp/aai/dbmap/AAIGraph.java deleted file mode 100644 index 4921b91d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbmap/AAIGraph.java +++ /dev/null @@ -1,196 +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.dbmap; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.lang.exception.ExceptionUtils; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.io.IoCore; -import org.openecomp.aai.dbgen.SchemaGenerator; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.util.AAIConstants; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; - -/** - * Database Mapping class which acts as the middle man between the REST - * interface objects and Titan DB objects. This class provides methods to commit - * the objects received on the REST interface into the Titan graph database as - * vertices and edges. Transactions are also managed here by using a TitanGraph - * object to load, commit/rollback and shutdown for each request. The data model - * rules such as keys/required properties are handled by calling DBMeth methods - * which are driven by a specification file in json. - * - - */ -public class AAIGraph { - - private static final EELFLogger logger = EELFManager.getInstance().getLogger(AAIGraph.class); - protected static final String COMPONENT = "aaidbmap"; - protected Map<String, TitanGraph> graphs = new HashMap<>(); - private final String REALTIME_DB = "realtime"; - private final String CACHED_DB = "cached"; - - - - /** - * Instantiates a new AAI graph. - */ - private AAIGraph() { - try { - String rtConfig = System.getProperty("realtime.db.config"); - String cachedConfig = System.getProperty("cached.db.config"); - if (rtConfig == null) { - rtConfig = AAIConstants.REALTIME_DB_CONFIG; - } - if (cachedConfig == null) { - cachedConfig = AAIConstants.CACHED_DB_CONFIG; - } - this.loadGraph(REALTIME_DB, rtConfig); - this.loadGraph(CACHED_DB, cachedConfig); - } catch (Exception e) { - throw new RuntimeException("Failed to instantiate graphs", e); - } - } - - private static class Helper { - private static final AAIGraph INSTANCE = new AAIGraph(); - } - - /** - * Gets the single instance of AAIGraph. - * - * @return single instance of AAIGraph - */ - public static AAIGraph getInstance() { - return Helper.INSTANCE; - } - - private void loadGraph(String name, String configPath) throws AAIException { - // Graph being opened by TitanFactory is being placed in hashmap to be used later - // These graphs shouldn't be closed until the application shutdown - TitanGraph graph = TitanFactory.open(configPath); - try (InputStream is = new FileInputStream(configPath)) { - - Properties graphProps = new Properties(); - graphProps.load(is); - - if ("inmemory".equals(graphProps.get("storage.backend"))) { - // Load the propertyKeys, indexes and edge-Labels into the DB - loadSchema(graph); - loadSnapShotToInMemoryGraph(graph, graphProps); - } - - if (graph == null) { - throw new AAIException("AAI_5102"); - } - - graphs.put(name, graph); - } catch (FileNotFoundException fnfe) { - throw new AAIException("AAI_4001"); - } catch (IOException e) { - throw new AAIException("AAI_4002"); - } - } - - private void loadSnapShotToInMemoryGraph(TitanGraph graph, Properties graphProps) { - if (logger.isDebugEnabled()) { - logger.debug("Load Snapshot to InMemory Graph"); - } - if (graphProps.containsKey("load.snapshot.file")) { - String value = graphProps.getProperty("load.snapshot.file"); - if ("true".equals(value)) { - try (Graph transaction = graph.newTransaction()) { - String location = System.getProperty("snapshot.location"); - logAndPrint(logger, "Loading snapshot to inmemory graph."); - transaction.io(IoCore.graphson()).readGraph(location); - transaction.tx().commit(); - logAndPrint(logger, "Snapshot loaded to inmemory graph."); - } catch (Exception e) { - logAndPrint(logger, - "ERROR: Could not load datasnapshot to in memory graph. \n" - + ExceptionUtils.getFullStackTrace(e)); - System.exit(0); - } - } - } - } - - private void loadSchema(TitanGraph graph) { - // Load the propertyKeys, indexes and edge-Labels into the DB - TitanManagement graphMgt = graph.openManagement(); - - System.out.println("-- loading schema into Titan"); - SchemaGenerator.loadSchemaIntoTitan( graph, graphMgt ); - } - - /** - * Graph shutdown. - */ - public void graphShutdown() { - graphs.get(REALTIME_DB).close(); - } - - /** - * Gets the graph. - * - * @return the graph - */ - public TitanGraph getGraph() { - return graphs.get(REALTIME_DB); - } - - public void graphShutdown(DBConnectionType connectionType) { - - graphs.get(this.getGraphName(connectionType)).close(); - } - - public TitanGraph getGraph(DBConnectionType connectionType) { - return graphs.get(this.getGraphName(connectionType)); - } - - private String getGraphName(DBConnectionType connectionType) { - String graphName = ""; - if (DBConnectionType.CACHED.equals(connectionType)) { - graphName = this.CACHED_DB; - } else if (DBConnectionType.REALTIME.equals(connectionType)) { - graphName = this.REALTIME_DB; - } - - return graphName; - } - - private void logAndPrint(EELFLogger logger, String msg) { - System.out.println(msg); - logger.info(msg); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dbmap/DBConnectionType.java b/aai-core/src/main/java/org/openecomp/aai/dbmap/DBConnectionType.java deleted file mode 100644 index 26495275..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dbmap/DBConnectionType.java +++ /dev/null @@ -1,26 +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.dbmap; - -public enum DBConnectionType { - REALTIME, - CACHED -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSConsumer.java b/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSConsumer.java deleted file mode 100644 index db72d63d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSConsumer.java +++ /dev/null @@ -1,143 +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.dmaap; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import org.apache.log4j.MDC; -import org.json.JSONException; -import org.json.JSONObject; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.logging.LoggingContext; -import org.openecomp.aai.logging.LoggingContext.LoggingField; -import org.openecomp.aai.logging.LoggingContext.StatusCode; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.TextMessage; -import javax.ws.rs.core.MediaType; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.Properties; - -public class AAIDmaapEventJMSConsumer implements MessageListener { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIDmaapEventJMSConsumer.class); - - private Client httpClient; - - private Properties aaiEventProps; - private String aaiEventUrl = ""; - - public AAIDmaapEventJMSConsumer() throws org.apache.commons.configuration.ConfigurationException { - super(); - try(FileReader reader = new FileReader(new File(AAIConstants.AAI_EVENT_DMAAP_PROPS))) { - - if (this.httpClient == null) { - aaiEventProps = new Properties(); - aaiEventProps.load(reader); - - String host = aaiEventProps.getProperty("host"); - String topic = aaiEventProps.getProperty("topic"); - String protocol = aaiEventProps.getProperty("Protocol"); - - aaiEventUrl = protocol + "://" + host + "/events/" + topic; - httpClient = Client.create(); - } - - } catch (IOException e) { - ErrorLogHelper.logError("AAI_4000", "Error updating dmaap config file for aai event."); - LOGGER.error(e.getMessage(), e); - } - - } - - @Override - public void onMessage(Message message) { - - String jsmMessageTxt = ""; - String aaiEvent = ""; - String eventName = ""; - - if (message instanceof TextMessage) { - try { - jsmMessageTxt = ((TextMessage) message).getText(); - JSONObject jo = new JSONObject(jsmMessageTxt); - - if (jo.has("aaiEventPayload")) { - aaiEvent = jo.getJSONObject("aaiEventPayload").toString(); - } else { - return; - } - if (jo.getString("transId") != null) { - MDC.put("requestId", jo.getString("transId")); - } - if (jo.getString("fromAppId") != null) { - MDC.put("partnerName", jo.getString("fromAppId")); - } - if (jo.getString("event-topic") != null) { - eventName = jo.getString("event-topic"); - } - - LOGGER.info(eventName + "|" + aaiEvent); - if ("AAI-EVENT".equals(eventName)) { - this.sentWithHttp(this.httpClient, this.aaiEventUrl, aaiEvent); - } else { - LoggingContext.statusCode(StatusCode.ERROR); - LOGGER.error(eventName + "|Event Topic invalid."); - } - } catch (java.net.SocketException e) { - if (!e.getMessage().contains("Connection reset")) { - LOGGER.error("AAI_7304 Error reaching DMaaP to send event. " + aaiEvent, e); - } - } catch (IOException e) { - LOGGER.error("AAI_7304 Error reaching DMaaP to send event. " + aaiEvent, e); - } catch (JMSException | JSONException e) { - LOGGER.error("AAI_7350 Error parsing aaievent jsm message for sending to dmaap. " + jsmMessageTxt, e); - } catch (Exception e) { - LOGGER.error("AAI_7350 Error sending message to dmaap. " + jsmMessageTxt, e); - } - } - - } - - private boolean sentWithHttp(Client client, String url, String aaiEvent) throws IOException { - - WebResource webResource = client.resource(url); - - ClientResponse response = webResource - .accept(MediaType.APPLICATION_JSON) - .type(MediaType.APPLICATION_JSON) - .post(ClientResponse.class, aaiEvent); - - if (response.getStatus() != 200) { - LOGGER.info("Failed : HTTP error code : " + response.getStatus()); - return false; - } - return true; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSProducer.java b/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSProducer.java deleted file mode 100644 index 89ed9348..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/dmaap/AAIDmaapEventJMSProducer.java +++ /dev/null @@ -1,49 +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.dmaap; - -import org.apache.activemq.ActiveMQConnectionFactory; -import org.apache.activemq.command.ActiveMQQueue; -import org.json.JSONObject; -import org.openecomp.aai.util.AAIConfig; -import org.springframework.jms.connection.CachingConnectionFactory; -import org.springframework.jms.core.JmsTemplate; - -public class AAIDmaapEventJMSProducer { - - private JmsTemplate jmsTemplate; - - public AAIDmaapEventJMSProducer() { - if(AAIConfig.get("aai.jms.enable", "true").equals("true")){ - this.jmsTemplate = new JmsTemplate(); - this.jmsTemplate.setConnectionFactory(new CachingConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61447"))); - this.jmsTemplate.setDefaultDestination(new ActiveMQQueue("IN_QUEUE")); - } - } - - public void sendMessageToDefaultDestination(JSONObject finalJson) { - if(jmsTemplate != null){ - jmsTemplate.convertAndSend(finalJson.toString()); - CachingConnectionFactory ccf = (CachingConnectionFactory) this.jmsTemplate.getConnectionFactory(); - ccf.destroy(); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/NotificationEvent.java b/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/NotificationEvent.java deleted file mode 100644 index 865d045f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/NotificationEvent.java +++ /dev/null @@ -1,564 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2016.01.06 at 05:38:00 PM EST -// - - -package org.openecomp.aai.domain.notificationEvent; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; -import org.w3c.dom.Element; - - -/** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="cambria.partition" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="event-header" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * <any processContents='lax' namespace='##other' minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "cambriaPartition", - "eventHeader", - "entity" -}) -@XmlRootElement(name = "NotificationEvent") -public class NotificationEvent { - - @XmlElement(name = "cambria.partition") - protected String cambriaPartition; - @XmlElement(name = "event-header") - protected NotificationEvent.EventHeader eventHeader; - @XmlAnyElement(lax = true) - protected Object entity; - - /** - * Gets the value of the eventHeader property. - * - * @return - * possible object is - * {@link NotificationEvent.EventHeader } - * - */ - public NotificationEvent.EventHeader getEventHeader() { - return eventHeader; - } - - /** - * Sets the value of the eventHeader property. - * - * @param value - * allowed object is - * {@link NotificationEvent.EventHeader } - * - */ - public void setEventHeader(NotificationEvent.EventHeader value) { - this.eventHeader = value; - } - - /** - * Gets the value of the any property. - * - * @return - * possible object is - * {@link Object } - * {@link Element } - * - */ - public Object getEntity() { - return entity; - } - - /** - * Sets the value of the any property. - * - * @param value - * allowed object is - * {@link Object } - * {@link Element } - * - */ - public void setEntity(Object value) { - this.entity = value; - } - - /** - * Gets the value of the cambriaPartition property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getCambriaPartition() { - return cambriaPartition; - } - - /** - * Sets the value of the cambriaPartition property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setCambriaPartition(String value) { - this.cambriaPartition = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="id" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="timestamp" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="source-name" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="domain" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="sequence-number" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="severity" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="event-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="version" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="action" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="top-entity-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="entity-link" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="status" type="{http://www.w3.org/2001/XMLSchema}string"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "id", - "timestamp", - "sourceName", - "domain", - "sequenceNumber", - "severity", - "eventType", - "version", - "action", - "entityType", - "topEntityType", - "entityLink", - "status" - }) - public static class EventHeader { - - @XmlElement(required = true) - protected String id; - @XmlElement(required = true) - protected String timestamp; - @XmlElement(name = "source-name", required = true) - protected String sourceName; - @XmlElement(required = true) - protected String domain; - @XmlElement(name = "sequence-number", required = true) - protected String sequenceNumber; - @XmlElement(required = true) - protected String severity; - @XmlElement(name = "event-type", required = true) - protected String eventType; - @XmlElement(required = true) - protected String version; - @XmlElement(required = true) - protected String action; - @XmlElement(name = "entity-type", required = true) - protected String entityType; - @XmlElement(name = "top-entity-type", required = true) - protected String topEntityType; - @XmlElement(name = "entity-link", required = true) - protected String entityLink; - @XmlElement(required = true) - protected String status; - - /** - * Gets the value of the id property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getId() { - return id; - } - - /** - * Sets the value of the id property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setId(String value) { - this.id = value; - } - - /** - * Gets the value of the timestamp property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTimestamp() { - return timestamp; - } - - /** - * Sets the value of the timestamp property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTimestamp(String value) { - this.timestamp = value; - } - - /** - * Gets the value of the sourceName property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSourceName() { - return sourceName; - } - - /** - * Sets the value of the sourceName property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSourceName(String value) { - this.sourceName = value; - } - - /** - * Gets the value of the domain property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getDomain() { - return domain; - } - - /** - * Sets the value of the domain property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setDomain(String value) { - this.domain = value; - } - - /** - * Gets the value of the sequenceNumber property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSequenceNumber() { - return sequenceNumber; - } - - /** - * Sets the value of the sequenceNumber property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSequenceNumber(String value) { - this.sequenceNumber = value; - } - - /** - * Gets the value of the severity property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSeverity() { - return severity; - } - - /** - * Sets the value of the severity property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSeverity(String value) { - this.severity = value; - } - - /** - * Gets the value of the eventType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getEventType() { - return eventType; - } - - /** - * Sets the value of the eventType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setEventType(String value) { - this.eventType = value; - } - - /** - * Gets the value of the version property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getVersion() { - return version; - } - - /** - * Sets the value of the version property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setVersion(String value) { - this.version = value; - } - - /** - * Gets the value of the action property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getAction() { - return action; - } - - /** - * Sets the value of the action property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setAction(String value) { - this.action = value; - } - - /** - * Gets the value of the entityType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getEntityType() { - return entityType; - } - - /** - * Sets the value of the entityType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setEntityType(String value) { - this.entityType = value; - } - - /** - * Gets the value of the topEntityType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTopEntityType() { - return topEntityType; - } - - /** - * Sets the value of the topEntityType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTopEntityType(String value) { - this.topEntityType = value; - } - - /** - * Gets the value of the entityLink property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getEntityLink() { - return entityLink; - } - - /** - * Sets the value of the entityLink property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setEntityLink(String value) { - this.entityLink = value; - } - - /** - * Gets the value of the status property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getStatus() { - return status; - } - - /** - * Sets the value of the status property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setStatus(String value) { - this.status = value; - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/ObjectFactory.java deleted file mode 100644 index c331aab2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/notificationEvent/ObjectFactory.java +++ /dev/null @@ -1,77 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2016.01.06 at 05:38:00 PM EST -// - - -package org.openecomp.aai.domain.notificationEvent; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.openecomp.aai.domain.notificationEvent package. - * <p>An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.aai.domain.notificationEvent - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link NotificationEvent }. - * - * @return the notification event - */ - public NotificationEvent createNotificationEvent() { - return new NotificationEvent(); - } - - /** - * Create an instance of {@link NotificationEvent.EventHeader } - * - * @return the event header - */ - public NotificationEvent.EventHeader createNotificationEventEventHeader() { - return new NotificationEvent.EventHeader(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessage.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessage.java deleted file mode 100644 index b3f03247..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessage.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessageCode", - "aaiResponseMessageResourceType", - "aaiResponseMessageDescription", - "aaiResponseMessageData", -}) -@XmlRootElement(name = "aai-response-message", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessage { - - @XmlElement(name = "aai-response-message-code", required = true) - protected String aaiResponseMessageCode; - @XmlElement(name = "aai-response-message-resource-type") - protected String aaiResponseMessageResourceType; - @XmlElement(name = "aai-response-message-description") - protected String aaiResponseMessageDescription; - @XmlElement(name = "aai-response-message-data") - protected AAIResponseMessageData aaiResponseMessageData; - - /** - * Gets the aai response message code. - * - * @return the aai response message code - */ - public String getAaiResponseMessageCode() { - return aaiResponseMessageCode; - } - - /** - * Sets the aai response message code. - * - * @param aaiResponseMessageCode the new aai response message code - */ - public void setAaiResponseMessageCode(String aaiResponseMessageCode) { - this.aaiResponseMessageCode = aaiResponseMessageCode; - } - - /** - * Gets the aai response message resource type. - * - * @return the aai response message resource type - */ - public String getAaiResponseMessageResourceType() { - return aaiResponseMessageResourceType; - } - - /** - * Sets the aai response message resource type. - * - * @param aaiResponseMessageResourceType the new aai response message resource type - */ - public void setAaiResponseMessageResourceType( - String aaiResponseMessageResourceType) { - this.aaiResponseMessageResourceType = aaiResponseMessageResourceType; - } - - /** - * Gets the aai response message description. - * - * @return the aai response message description - */ - public String getAaiResponseMessageDescription() { - return aaiResponseMessageDescription; - } - - /** - * Sets the aai response message description. - * - * @param aaiResponseMessageDescription the new aai response message description - */ - public void setAaiResponseMessageDescription( - String aaiResponseMessageDescription) { - this.aaiResponseMessageDescription = aaiResponseMessageDescription; - } - - /** - * Gets the aai response message data. - * - * @return the aai response message data - */ - public AAIResponseMessageData getAaiResponseMessageData() { - if (aaiResponseMessageData == null) { - aaiResponseMessageData = new AAIResponseMessageData(); - } - return aaiResponseMessageData; - } - - /** - * Sets the AAI response message data. - * - * @param aaiResponseMessageData the new AAI response message data - */ - public void setAAIResponseMessageData( - AAIResponseMessageData aaiResponseMessageData) { - this.aaiResponseMessageData = aaiResponseMessageData; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageData.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageData.java deleted file mode 100644 index 16f9c6dd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageData.java +++ /dev/null @@ -1,78 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - - -// -//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -//See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -//Any modifications to this file will be lost upon recompilation of the source schema. -//Generated on: 2015.09.11 at 11:53:27 AM EDT -// - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessageDatum", - "any" -}) -@XmlRootElement(name = "aai-response-message-data", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessageData { - - @XmlElement(name = "aai-response-message-datum") - protected List<AAIResponseMessageDatum> aaiResponseMessageDatum; - @XmlAnyElement(lax = true) - protected List<Object> any; - - /** - * Gets the AAI response message datum. - * - * @return the AAI response message datum - */ - public List<AAIResponseMessageDatum> getAAIResponseMessageDatum() { - if (aaiResponseMessageDatum == null) { - aaiResponseMessageDatum = new ArrayList<AAIResponseMessageDatum>(); - } - return this.aaiResponseMessageDatum; - } - - /** - * Gets the any. - * - * @return the any - */ - public List<Object> getAny() { - if (any == null) { - any = new ArrayList<Object>(); - } - return this.any; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageDatum.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageDatum.java deleted file mode 100644 index 8b64651f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessageDatum.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessageDatumKey", - "aaiResponseMessageDatumValue", - -}) - -@XmlRootElement(name = "aai-response-message-datum", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessageDatum { - - @XmlElement(name = "aai-response-message-datum-key", required = true) - protected String aaiResponseMessageDatumKey; - @XmlElement(name = "aai-response-message-datum-value", required = true) - protected String aaiResponseMessageDatumValue; - - /** - * Gets the aai response message datum key. - * - * @return the aai response message datum key - */ - public String getAaiResponseMessageDatumKey() { - return aaiResponseMessageDatumKey; - } - - /** - * Sets the aai response message datum key. - * - * @param aaiResponseMessageDatumKey the new aai response message datum key - */ - public void setAaiResponseMessageDatumKey(String aaiResponseMessageDatumKey) { - this.aaiResponseMessageDatumKey = aaiResponseMessageDatumKey; - } - - /** - * Gets the aai response message datum value. - * - * @return the aai response message datum value - */ - public String getAaiResponseMessageDatumValue() { - return aaiResponseMessageDatumValue; - } - - /** - * Sets the aai response message datum value. - * - * @param aaiResponseMessageDatumValue the new aai response message datum value - */ - public void setAaiResponseMessageDatumValue(String aaiResponseMessageDatumValue) { - this.aaiResponseMessageDatumValue = aaiResponseMessageDatumValue; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessages.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessages.java deleted file mode 100644 index 41ff5610..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/AAIResponseMessages.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.responseMessage; - - -// -//This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -//See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -//Any modifications to this file will be lost upon recompilation of the source schema. -//Generated on: 2015.09.11 at 11:53:27 AM EDT -// - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAnyElement; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -/** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="flavor" maxOccurs="unbounded" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="flavor-id" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="flavor-name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> - * <element name="flavor-vcpus" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/> - * <element name="flavor-ram" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/> - * <element name="flavor-disk" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/> - * <element name="flavor-ephemeral" type="{http://www.w3.org/2001/XMLSchema}short" minOccurs="0"/> - * <element name="flavor-swap" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> - * <element name="flavor-is-public" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> - * <element name="flavor-selflink" type="{urn:ietf:params:xml:ns:yang:ietf-inet-types}uri" minOccurs="0"/> - * <element name="flavor-disabled" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> - * <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> - * <element ref="{http://org.openecomp.aai.inventory/v3}relationship-list" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "aaiResponseMessage", - "any" -}) -@XmlRootElement(name = "aai-response-messages", namespace = "http://org.openecomp.aai.inventory") -public class AAIResponseMessages { - @XmlElement(name = "aai-response-message") - protected List<AAIResponseMessage> aaiResponseMessage; - @XmlAnyElement(lax = true) - protected List<Object> any; - - /** - * Gets the AAI response message. - * - * @return the AAI response message - */ - public List<AAIResponseMessage> getAAIResponseMessage() { - if (aaiResponseMessage == null) { - aaiResponseMessage = new ArrayList<AAIResponseMessage>(); - } - return this.aaiResponseMessage; - } - - /** - * Gets the any. - * - * @return the any - */ - public List<Object> getAny() { - if (any == null) { - any = new ArrayList<Object>(); - } - return this.any; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/package-info.java b/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/package-info.java deleted file mode 100644 index cfb4981a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/responseMessage/package-info.java +++ /dev/null @@ -1,32 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.06.15 at 03:03:58 PM EDT -// - -@javax.xml.bind.annotation.XmlSchema( - namespace = "http://org.openecomp.aai.inventory", - elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) -package org.openecomp.aai.domain.responseMessage; - diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/Fault.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/Fault.java deleted file mode 100644 index f32268b3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/Fault.java +++ /dev/null @@ -1,382 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:39 PM EST -// - - -package org.openecomp.aai.domain.restPolicyException; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="requestError"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="policyException"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "requestError" -}) -@XmlRootElement(name = "Fault") -public class Fault { - - @XmlElement(required = true) - protected Fault.RequestError requestError; - - /** - * Gets the value of the requestError property. - * - * @return - * possible object is - * {@link Fault.RequestError } - * - */ - public Fault.RequestError getRequestError() { - return requestError; - } - - /** - * Sets the value of the requestError property. - * - * @param value - * allowed object is - * {@link Fault.RequestError } - * - */ - public void setRequestError(Fault.RequestError value) { - this.requestError = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="policyException"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "policyException" - }) - public static class RequestError { - - @XmlElement(required = true) - protected Fault.RequestError.PolicyException policyException; - - /** - * Gets the value of the policyException property. - * - * @return - * possible object is - * {@link Fault.RequestError.PolicyException } - * - */ - public Fault.RequestError.PolicyException getPolicyException() { - return policyException; - } - - /** - * Sets the value of the policyException property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.PolicyException } - * - */ - public void setPolicyException(Fault.RequestError.PolicyException value) { - this.policyException = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "messageId", - "text", - "variables" - }) - public static class PolicyException { - - @XmlElement(required = true) - protected String messageId; - @XmlElement(required = true) - protected String text; - @XmlElement(required = true) - protected Fault.RequestError.PolicyException.Variables variables; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the text property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getText() { - return text; - } - - /** - * Sets the value of the text property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setText(String value) { - this.text = value; - } - - /** - * Gets the value of the variables property. - * - * @return - * possible object is - * {@link Fault.RequestError.PolicyException.Variables } - * - */ - public Fault.RequestError.PolicyException.Variables getVariables() { - return variables; - } - - /** - * Sets the value of the variables property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.PolicyException.Variables } - * - */ - public void setVariables(Fault.RequestError.PolicyException.Variables value) { - this.variables = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "variable" - }) - public static class Variables { - - protected List<String> variable; - - /** - * Gets the value of the variable property. - * - * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the variable property. - * - * <p> - * For example, to add a new item, do as follows: - * <pre> - * getVariable().add(newItem); - * </pre> - * - * - * <p> - * Objects of the following type(s) are allowed in the list - * {@link String } - * - * @return the variable - */ - public List<String> getVariable() { - if (variable == null) { - variable = new ArrayList<String>(); - } - return this.variable; - } - - } - - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/ObjectFactory.java deleted file mode 100644 index 3cf31ed0..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/ObjectFactory.java +++ /dev/null @@ -1,95 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:39 PM EST -// - - -package org.openecomp.aai.domain.restPolicyException; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.openecomp.aai.domain.restPolicyException package. - * <p>An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.aai.domain.restPolicyException - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Fault }. - * - * @return the fault - */ - public Fault createFault() { - return new Fault(); - } - - /** - * Create an instance of {@link Fault.RequestError } - * - * @return the request error - */ - public Fault.RequestError createFaultRequestError() { - return new Fault.RequestError(); - } - - /** - * Create an instance of {@link Fault.RequestError.PolicyException } - * - * @return the policy exception - */ - public Fault.RequestError.PolicyException createFaultRequestErrorPolicyException() { - return new Fault.RequestError.PolicyException(); - } - - /** - * Create an instance of {@link Fault.RequestError.PolicyException.Variables } - * - * @return the variables - */ - public Fault.RequestError.PolicyException.Variables createFaultRequestErrorPolicyExceptionVariables() { - return new Fault.RequestError.PolicyException.Variables(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/PolicyException.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/PolicyException.java deleted file mode 100644 index a55ce62e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/PolicyException.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.restPolicyException; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "messageId", - "text", - "variables" -}) -public class PolicyException { - - @JsonProperty("messageId") - private String messageId; - @JsonProperty("text") - private String text; - @JsonProperty("variables") - private List<String> variables = new ArrayList<String>(); - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * Gets the message id. - * - * @return The messageId - */ - @JsonProperty("messageId") - public String getMessageId() { - return messageId; - } - - /** - * Sets the message id. - * - * @param messageId The messageId - */ - @JsonProperty("messageId") - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - /** - * Gets the text. - * - * @return The text - */ - @JsonProperty("text") - public String getText() { - return text; - } - - /** - * Sets the text. - * - * @param text The text - */ - @JsonProperty("text") - public void setText(String text) { - this.text = text; - } - - /** - * Gets the variables. - * - * @return The variables - */ - @JsonProperty("variables") - public List<String> getVariables() { - return variables; - } - - /** - * Sets the variables. - * - * @param variables The variables - */ - @JsonProperty("variables") - public void setVariables(List<String> variables) { - this.variables = variables; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RESTResponse.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RESTResponse.java deleted file mode 100644 index eb9deb27..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RESTResponse.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.restPolicyException; - -import java.util.HashMap; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "requestError" -}) -public class RESTResponse { - - @JsonProperty("requestError") - private RequestError requestError; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * Gets the request error. - * - * @return The requestError - */ - @JsonProperty("requestError") - public RequestError getRequestError() { - return requestError; - } - - /** - * Sets the request error. - * - * @param requestError The requestError - */ - @JsonProperty("requestError") - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RequestError.java b/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RequestError.java deleted file mode 100644 index a4d4e74e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restPolicyException/RequestError.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.restPolicyException; - -import java.util.HashMap; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "policyException" -}) -public class RequestError { - - @JsonProperty("policyException") - private PolicyException policyException; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * Gets the policy exception. - * - * @return The policyException - */ - @JsonProperty("policyException") - public PolicyException getPolicyException() { - return policyException; - } - - /** - * Sets the policy exception. - * - * @param policyException The policyException - */ - @JsonProperty("policyException") - public void setPolicyException(PolicyException policyException) { - this.policyException = policyException; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} - diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/Info.java b/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/Info.java deleted file mode 100644 index 6a1f8e4a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/Info.java +++ /dev/null @@ -1,385 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.10.28 at 05:53:17 PM EDT -// - - -package org.openecomp.aai.domain.restResponseInfo; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="responseMessages" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="responseMessage" maxOccurs="unbounded" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "responseMessages" -}) -@XmlRootElement(name = "Info") -public class Info { - - protected Info.ResponseMessages responseMessages; - - /** - * Gets the value of the responseMessages property. - * - * @return - * possible object is - * {@link Info.ResponseMessages } - * - */ - public Info.ResponseMessages getResponseMessages() { - return responseMessages; - } - - /** - * Sets the value of the responseMessages property. - * - * @param value - * allowed object is - * {@link Info.ResponseMessages } - * - */ - public void setResponseMessages(Info.ResponseMessages value) { - this.responseMessages = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="responseMessage" maxOccurs="unbounded" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "responseMessage" - }) - public static class ResponseMessages { - - protected List<Info.ResponseMessages.ResponseMessage> responseMessage; - - /** - * Gets the value of the responseMessage property. - * - * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the responseMessage property. - * - * <p> - * For example, to add a new item, do as follows: - * <pre> - * getResponseMessage().add(newItem); - * </pre> - * - * - * <p> - * Objects of the following type(s) are allowed in the list - * {@link Info.ResponseMessages.ResponseMessage } - * - * @return the response message - */ - public List<Info.ResponseMessages.ResponseMessage> getResponseMessage() { - if (responseMessage == null) { - responseMessage = new ArrayList<Info.ResponseMessages.ResponseMessage>(); - } - return this.responseMessage; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "messageId", - "text", - "variables" - }) - public static class ResponseMessage { - - @XmlElement(required = true) - protected String messageId; - @XmlElement(required = true) - protected String text; - @XmlElement(required = true) - protected Info.ResponseMessages.ResponseMessage.Variables variables; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the text property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getText() { - return text; - } - - /** - * Sets the value of the text property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setText(String value) { - this.text = value; - } - - /** - * Gets the value of the variables property. - * - * @return - * possible object is - * {@link Info.ResponseMessages.ResponseMessage.Variables } - * - */ - public Info.ResponseMessages.ResponseMessage.Variables getVariables() { - return variables; - } - - /** - * Sets the value of the variables property. - * - * @param value - * allowed object is - * {@link Info.ResponseMessages.ResponseMessage.Variables } - * - */ - public void setVariables(Info.ResponseMessages.ResponseMessage.Variables value) { - this.variables = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "variable" - }) - public static class Variables { - - protected List<String> variable; - - /** - * Gets the value of the variable property. - * - * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the variable property. - * - * <p> - * For example, to add a new item, do as follows: - * <pre> - * getVariable().add(newItem); - * </pre> - * - * - * <p> - * Objects of the following type(s) are allowed in the list - * {@link String } - * - * @return the variable - */ - public List<String> getVariable() { - if (variable == null) { - variable = new ArrayList<String>(); - } - return this.variable; - } - - } - - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/ObjectFactory.java deleted file mode 100644 index 70449586..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restResponseInfo/ObjectFactory.java +++ /dev/null @@ -1,95 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.10.28 at 05:53:17 PM EDT -// - - -package org.openecomp.aai.domain.restResponseInfo; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.openecomp.aai.domain.restResponseInfo package. - * <p>An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.aai.domain.restResponseInfo - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Info }. - * - * @return the info - */ - public Info createInfo() { - return new Info(); - } - - /** - * Create an instance of {@link Info.ResponseMessages } - * - * @return the response messages - */ - public Info.ResponseMessages createInfoResponseMessages() { - return new Info.ResponseMessages(); - } - - /** - * Create an instance of {@link Info.ResponseMessages.ResponseMessage } - * - * @return the response message - */ - public Info.ResponseMessages.ResponseMessage createInfoResponseMessagesResponseMessage() { - return new Info.ResponseMessages.ResponseMessage(); - } - - /** - * Create an instance of {@link Info.ResponseMessages.ResponseMessage.Variables } - * - * @return the variables - */ - public Info.ResponseMessages.ResponseMessage.Variables createInfoResponseMessagesResponseMessageVariables() { - return new Info.ResponseMessages.ResponseMessage.Variables(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/Fault.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/Fault.java deleted file mode 100644 index 3356a54f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/Fault.java +++ /dev/null @@ -1,382 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:29 PM EST -// - - -package org.openecomp.aai.domain.restServiceException; - -import java.util.ArrayList; -import java.util.List; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="requestError"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="serviceException"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "requestError" -}) -@XmlRootElement(name = "Fault") -public class Fault { - - @XmlElement(required = true) - protected Fault.RequestError requestError; - - /** - * Gets the value of the requestError property. - * - * @return - * possible object is - * {@link Fault.RequestError } - * - */ - public Fault.RequestError getRequestError() { - return requestError; - } - - /** - * Sets the value of the requestError property. - * - * @param value - * allowed object is - * {@link Fault.RequestError } - * - */ - public void setRequestError(Fault.RequestError value) { - this.requestError = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="serviceException"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "serviceException" - }) - public static class RequestError { - - @XmlElement(required = true) - protected Fault.RequestError.ServiceException serviceException; - - /** - * Gets the value of the serviceException property. - * - * @return - * possible object is - * {@link Fault.RequestError.ServiceException } - * - */ - public Fault.RequestError.ServiceException getServiceException() { - return serviceException; - } - - /** - * Sets the value of the serviceException property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.ServiceException } - * - */ - public void setServiceException(Fault.RequestError.ServiceException value) { - this.serviceException = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="messageId" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="text" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="variables"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "messageId", - "text", - "variables" - }) - public static class ServiceException { - - @XmlElement(required = true) - protected String messageId; - @XmlElement(required = true) - protected String text; - @XmlElement(required = true) - protected Fault.RequestError.ServiceException.Variables variables; - - /** - * Gets the value of the messageId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getMessageId() { - return messageId; - } - - /** - * Sets the value of the messageId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setMessageId(String value) { - this.messageId = value; - } - - /** - * Gets the value of the text property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getText() { - return text; - } - - /** - * Sets the value of the text property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setText(String value) { - this.text = value; - } - - /** - * Gets the value of the variables property. - * - * @return - * possible object is - * {@link Fault.RequestError.ServiceException.Variables } - * - */ - public Fault.RequestError.ServiceException.Variables getVariables() { - return variables; - } - - /** - * Sets the value of the variables property. - * - * @param value - * allowed object is - * {@link Fault.RequestError.ServiceException.Variables } - * - */ - public void setVariables(Fault.RequestError.ServiceException.Variables value) { - this.variables = value; - } - - - /** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="variable" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ - @XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "", propOrder = { - "variable" - }) - public static class Variables { - - protected List<String> variable; - - /** - * Gets the value of the variable property. - * - * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the variable property. - * - * <p> - * For example, to add a new item, do as follows: - * <pre> - * getVariable().add(newItem); - * </pre> - * - * - * <p> - * Objects of the following type(s) are allowed in the list - * {@link String } - * - * @return the variable - */ - public List<String> getVariable() { - if (variable == null) { - variable = new ArrayList<String>(); - } - return this.variable; - } - - } - - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ObjectFactory.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ObjectFactory.java deleted file mode 100644 index 09c59b3c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ObjectFactory.java +++ /dev/null @@ -1,95 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.02.11 at 04:54:29 PM EST -// - - -package org.openecomp.aai.domain.restServiceException; - -import javax.xml.bind.annotation.XmlRegistry; - - -/** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.openecomp.aai.domain.restServiceException package. - * <p>An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. - * - */ -@XmlRegistry -public class ObjectFactory { - - - /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.openecomp.aai.domain.restServiceException - * - */ - public ObjectFactory() { - } - - /** - * Create an instance of {@link Fault }. - * - * @return the fault - */ - public Fault createFault() { - return new Fault(); - } - - /** - * Create an instance of {@link Fault.RequestError } - * - * @return the request error - */ - public Fault.RequestError createFaultRequestError() { - return new Fault.RequestError(); - } - - /** - * Create an instance of {@link Fault.RequestError.ServiceException } - * - * @return the service exception - */ - public Fault.RequestError.ServiceException createFaultRequestErrorServiceException() { - return new Fault.RequestError.ServiceException(); - } - - /** - * Create an instance of {@link Fault.RequestError.ServiceException.Variables } - * - * @return the variables - */ - public Fault.RequestError.ServiceException.Variables createFaultRequestErrorServiceExceptionVariables() { - return new Fault.RequestError.ServiceException.Variables(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RESTResponse.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RESTResponse.java deleted file mode 100644 index 9aa55f44..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RESTResponse.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.restServiceException; - -import java.util.HashMap; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "requestError" -}) -public class RESTResponse { - - @JsonProperty("requestError") - private RequestError requestError; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * Gets the request error. - * - * @return The requestError - */ - @JsonProperty("requestError") - public RequestError getRequestError() { - return requestError; - } - - /** - * Sets the request error. - * - * @param requestError The requestError - */ - @JsonProperty("requestError") - public void setRequestError(RequestError requestError) { - this.requestError = requestError; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RequestError.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RequestError.java deleted file mode 100644 index edc465e8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/RequestError.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.restServiceException; - -import java.util.HashMap; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "serviceException" -}) -public class RequestError { - - @JsonProperty("serviceException") - private ServiceException serviceException; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * Gets the service exception. - * - * @return The serviceException - */ - @JsonProperty("serviceException") - public ServiceException getServiceException() { - return serviceException; - } - - /** - * Sets the service exception. - * - * @param serviceException The serviceException - */ - @JsonProperty("serviceException") - public void setServiceException(ServiceException serviceException) { - this.serviceException = serviceException; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ServiceException.java b/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ServiceException.java deleted file mode 100644 index 56872696..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/restServiceException/ServiceException.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.restServiceException; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "messageId", - "text", - "variables" -}) -public class ServiceException { - - @JsonProperty("messageId") - private String messageId; - @JsonProperty("text") - private String text; - @JsonProperty("variables") - private List<String> variables = new ArrayList<String>(); - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * Gets the message id. - * - * @return The messageId - */ - @JsonProperty("messageId") - public String getMessageId() { - return messageId; - } - - /** - * Sets the message id. - * - * @param messageId The messageId - */ - @JsonProperty("messageId") - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - /** - * Gets the text. - * - * @return The text - */ - @JsonProperty("text") - public String getText() { - return text; - } - - /** - * Sets the text. - * - * @param text The text - */ - @JsonProperty("text") - public void setText(String text) { - this.text = text; - } - - /** - * Gets the variables. - * - * @return The variables - */ - @JsonProperty("variables") - public List<String> getVariables() { - return variables; - } - - /** - * Sets the variables. - * - * @param variables The variables - */ - @JsonProperty("variables") - public void setVariables(List<String> variables) { - this.variables = variables; - } - - /** - * Gets the additional properties. - * - * @return the additional properties - */ - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - /** - * Sets the additional property. - * - * @param name the name - * @param value the value - */ - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntries.java b/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntries.java deleted file mode 100644 index 83f5b356..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntries.java +++ /dev/null @@ -1,131 +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========================================================= - */ - -// -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.03.20 at 09:46:47 AM CDT -// - - -package org.openecomp.aai.domain.translog; - -import java.util.ArrayList; -import java.util.List; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - - -/** - * <p>Java class for anonymous complex type. - * - * <p>The following schema fragment specifies the expected content contained within this class. - * - * <pre> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="update" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="update-node-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="update-node-key" maxOccurs="unbounded" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="key-name" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="key-value" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * <element name="action" maxOccurs="unbounded" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="action-type" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="action-data" maxOccurs="unbounded" minOccurs="0"> - * <complexType> - * <complexContent> - * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> - * <sequence> - * <element name="property-name" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <element name="property-value" type="{http://www.w3.org/2001/XMLSchema}string"/> - * <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </element> - * <any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> - * </sequence> - * </restriction> - * </complexContent> - * </complexType> - * </pre> - * - * - */ -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "transactionLogEntries" -}) -@XmlRootElement(name = "transaction-log-entries", namespace = "http://org.openecomp.aai.inventory") -public class TransactionLogEntries { - - protected List<TransactionLogEntry> transactionLogEntries; - - /** - * Gets the transaction log entries. - * - * @return the transaction log entries - */ - public List<TransactionLogEntry> getTransactionLogEntries() { - if (transactionLogEntries == null) { - transactionLogEntries = new ArrayList<TransactionLogEntry>(); - } - return this.transactionLogEntries; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntry.java b/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntry.java deleted file mode 100644 index c3724e34..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/domain/translog/TransactionLogEntry.java +++ /dev/null @@ -1,438 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.domain.translog; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import org.eclipse.persistence.oxm.annotations.XmlCDATA; - -@XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "transactionLogEntryId", - "status", - "rqstDate", - "respDate", - "sourceId", - "resourceId", - "resourceType", - "rqstBuf", - "respBuf", - "notificationPayload", - "notificationId", - "notificationStatus", - "notificationTopic", - "notificationEntityLink", - "notificationAction" -}) -@XmlRootElement(name = "transaction-log-entry", namespace = "http://org.openecomp.aai.inventory") -public class TransactionLogEntry { - - @XmlElement(name = "transaction-log-entry-id", required = true) - protected String transactionLogEntryId; - @XmlElement(name = "status") - protected String status; - @XmlElement(name = "rqst-date") - protected String rqstDate; - @XmlElement(name = "resp-date") - protected String respDate; - @XmlElement(name = "source-id") - protected String sourceId; - @XmlElement(name = "resource-id") - protected String resourceId; - @XmlElement(name = "resource-type") - protected String resourceType; - @XmlElement(name = "rqst-buf") - protected String rqstBuf; - @XmlElement(name = "resp-buf") - protected String respBuf; - @XmlElement(name = "notification-payload") - protected String notificationPayload; - @XmlElement(name = "notification-id") - protected String notificationId; - @XmlElement(name = "notification-status") - protected String notificationStatus; - @XmlElement(name = "notification-topic") - private String notificationTopic; - @XmlElement(name = "notification-entity-link") - private String notificationEntityLink; - @XmlElement(name = "notification-action") - private String notificationAction; - - /** - * Gets the value of the transcationLogEntryId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getTransactionLogEntryId() { - return transactionLogEntryId; - } - - /** - * Sets the value of the transactionLogEntryId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setTransactionLogEntryId(String value) { - this.transactionLogEntryId = value; - } - - /** - * Gets the value of the status property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getStatus() { - return status; - } - - /** - * Sets the value of the status property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setStatus(String value) { - this.status = value; - } - - /** - * Gets the value of the rqstDate property. - * - * @return - * possible object is - * {@link String } - * - */ - - public String getRqstDate() { - return rqstDate; - } - - /** - * Sets the value of the rqstDate property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRqstDate(String value) { - this.rqstDate = value; - } - - - /** - * Gets the value of the respDate property. - * - * @return - * possible object is - * {@link String } - * - */ - - public String getRespDate() { - return respDate; - } - - /** - * Sets the value of the respDate property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setRespDate(String value) { - this.respDate = value; - } - /** - * Gets the value of the sourceId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSourceId() { - return sourceId; - } - - /** - * Sets the value of the sourceId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setSourceId(String value) { - this.sourceId = value; - } - - /** - * Gets the value of the resourceId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getResourceId() { - return resourceId; - } - - /** - * Sets the value of the resourceId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setResourceId(String value) { - this.resourceId = value; - } - - /** - * Gets the value of the resourceType property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getResourceType() { - return resourceType; - } - - /** - * Sets the value of the resourceType property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setResourceType(String value) { - this.resourceType = value; - } - - /** - * Gets the value of the rqstBuf property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getRqstBuf() { - return rqstBuf; - } - - /** - * Sets the value of the rqstBuf property. - * - * @param value - * allowed object is - * {@link String } - * - */ - @XmlCDATA - public void setRqstBuf(String value) { - this.rqstBuf = value; - } - - /** - * Gets the value of the respBuf property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getrespBuf() { - return respBuf; - } - - /** - * Sets the value of the respBuf property. - * - * @param value - * allowed object is - * {@link String } - * - */ - @XmlCDATA - public void setrespBuf(String value) { - this.respBuf = value; - } - - /** - * Gets the value of the notificationPayload property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNotificationPayload() { - return notificationPayload; - } - - /** - * Sets the value of the notificationPayload property. - * - * @param value - * allowed object is - * {@link String } - * - */ - @XmlCDATA - public void setNotificationPayload(String value) { - this.notificationPayload = value; - } - - - /** - * Gets the value of the notificationId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNotificationId() { - return notificationId; - } - - /** - * Sets the value of the notificationId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setNotificationId(String value) { - this.notificationId = value; - } - - /** - * Gets the value of the notificationId property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNotificationStatus() { - return notificationStatus; - } - - /** - * Sets the value of the notificationId property. - * - * @param value - * allowed object is - * {@link String } - * - */ - public void setNotificationStatus(String value) { - this.notificationStatus = value; - } - - /** - * Gets the value of the notificationTopic property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNotificationTopic() { - return notificationTopic; - } - - /** - * Sets the value of the notificationTopic property. - * - * @param topic the new notification topic - */ - public void setNotificationTopic(String topic) { - this.notificationTopic = topic; - } - - /** - * Gets the value of the notificationEntityLink property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getNotificationEntityLink() { - return notificationEntityLink; - } - - /** - * Sets the value of the notificationEntityLink property. - * - * @param entityLink the new notification entity link - */ - public void setNotificationEntityLink(String entityLink) { - this.notificationEntityLink = entityLink; - } - - /** - * Sets the value of the notificationAction property. - * - * @return the notification action - */ - public String getNotificationAction() { - return notificationAction; - } - - /** - * Sets the value of the notificationAction property. - * - * @param action the new notification action - */ - public void setNotificationAction(String action) { - this.notificationAction = action; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIException.java b/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIException.java deleted file mode 100644 index e3bce33d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIException.java +++ /dev/null @@ -1,146 +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.exceptions; - -import java.util.Collection; -import java.util.LinkedList; - -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.logging.ErrorObject; -import org.openecomp.aai.logging.ErrorObjectNotFoundException; - -public class AAIException extends Exception { - - public static final String DEFAULT_EXCEPTION_CODE = "AAI_4000"; - private static final long serialVersionUID = 1L; - - private final String code; - private final ErrorObject errorObject; - private final Collection<String> templateVars; - - /** - * Instantiates a new AAI exception. - */ - public AAIException() { - super(); - this.code = DEFAULT_EXCEPTION_CODE; - this.templateVars = new LinkedList<String> (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - */ - public AAIException(String code) { - super(); - - this.code = code; - this.templateVars = new LinkedList<String> (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - * @param details the details - */ - public AAIException(String code, String details) { - super(details); - - this.code = code; - this.templateVars = new LinkedList<String> (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - * @param cause the cause - */ - public AAIException(String code, Throwable cause) { - super(cause); - - this.code = code; - this.templateVars = new LinkedList<String> (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - /** - * Instantiates a new AAI exception. - * - * @param code the code - * @param cause the cause - * @param details the details - */ - public AAIException(String code, Throwable cause, String details) { - super(details, cause); - - this.code = code; - this.templateVars = new LinkedList<String> (); - - try { - this.errorObject = ErrorLogHelper.getErrorObject(getCode()); - } catch (ErrorObjectNotFoundException e) { - throw new RuntimeException("Failed to instantiate AAIException with code=" + getCode() - + " - update error.properties before using this exception code"); - } - } - - public String getCode() { - return code; - } - - public ErrorObject getErrorObject() { - return errorObject; - } - - public Collection<String> getTemplateVars() { - return templateVars; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIExceptionWithInfo.java b/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIExceptionWithInfo.java deleted file mode 100644 index f1b15396..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/exceptions/AAIExceptionWithInfo.java +++ /dev/null @@ -1,134 +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.exceptions; - -import java.util.HashMap; - -public class AAIExceptionWithInfo extends AAIException { - - HashMap<String, Object> infoHash; - String info; - - /** - * Instantiates a new AAI exception with info. - * - * @param infoHash the info hash - * @param info the info - */ - public AAIExceptionWithInfo(HashMap<String, Object> infoHash, String info) { - super(); - setInfoHash(infoHash); - setInfo(info); - } - - /** - * Instantiates a new AAI exception with info. - * - * @param code the code - * @param infoHash the info hash - * @param info the info - */ - public AAIExceptionWithInfo(String code, HashMap<String, Object> infoHash, String info) { - super(code); - setInfoHash(infoHash); - setInfo(info); - } - - /** - * Instantiates a new AAI exception with info. - * - * @param code the code - * @param details the details - * @param infoHash the info hash - * @param info the info - */ - public AAIExceptionWithInfo(String code, String details, HashMap<String, Object> infoHash, String info) { - super(code, details); - setInfoHash(infoHash); - setInfo(info); - } - - /** - * Instantiates a new AAI exception with info. - * - * @param code the code - * @param cause the cause - * @param infoHash the info hash - * @param info the info - */ - public AAIExceptionWithInfo(String code, Throwable cause, HashMap<String, Object> infoHash, String info) { - super(code, cause); - setInfoHash(infoHash); - setInfo(info); - } - - /** - * Instantiates a new AAI exception with info. - * - * @param code the code - * @param cause the cause - * @param details the details - * @param infoHash the info hash - * @param info the info - */ - public AAIExceptionWithInfo(String code, Throwable cause, String details, HashMap<String, Object> infoHash, String info) { - super(code, cause, details); - setInfoHash(infoHash); - setInfo(info); - } - - /** - * Gets the info hash. - * - * @return the info hash - */ - public HashMap<String, Object> getInfoHash() { - return infoHash; - } - - /** - * Sets the info hash. - * - * @param infoHash the info hash - */ - public void setInfoHash(HashMap<String, Object> infoHash) { - this.infoHash = infoHash; - } - - /** - * Gets the info. - * - * @return the info - */ - public String getInfo() { - return info; - } - - /** - * Sets the info. - * - * @param info the new info - */ - public void setInfo(String info) { - this.info = info; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/extensions/AAIExtensionMap.java b/aai-core/src/main/java/org/openecomp/aai/extensions/AAIExtensionMap.java deleted file mode 100644 index 11a8920a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/extensions/AAIExtensionMap.java +++ /dev/null @@ -1,825 +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.extensions; - -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.openecomp.aai.domain.responseMessage.AAIResponseMessages; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.rest.db.DBRequest; -import org.openecomp.aai.rest.db.HttpEntry; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.servlet.http.HttpServletRequest; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriInfo; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; - -public class AAIExtensionMap { - // ======================================================================= - // Attribute | Type - // ======================================================================= - // message | java.lang.String (RW) - // ---------------------------------------------------------------------- - // templateVars | java.lang.ArrayList<String> (RW) - // ----------------------------------------------------------------------- - // preExtException | java.lang.Exception (RW) - // ----------------------------------------------------------------------- - // preExtErrorCallback | java.lang.reflect.Method (RW) - // ----------------------------------------------------------------------- - // postExtException | java.lang.Exception (RW) - // ----------------------------------------------------------------------- - // postExtErrorCallback | java.lang.reflect.Method (RW) - // ----------------------------------------------------------------------- - // servletRequest | javax.servlet.http.HttpServletRequest (RO) - // ----------------------------------------------------------------------- - // headers | javax.ws.rs.core.HttpHeaders (RO) - // ----------------------------------------------------------------------- - // objFromRequestType | String (ex. ?org.openecomp.aai.domain.yang.Vce?) (RO) - // ----------------------------------------------------------------------- - // objFromRequest | $TYPE {ObjFromRequestType) (RO) - // ----------------------------------------------------------------------- - // preExtFailOnError | java.lang.Boolean (RW) - // ----------------------------------------------------------------------- - // postExtFailOnError | java.lang.Boolean (RW) - // ----------------------------------------------------------------------- - // preExtSkipErrorCallback | java.lang.Boolean (RW) - // ----------------------------------------------------------------------- - // postExtSkipErrorCallback | java.lang.Boolean (RW) - // ----------------------------------------------------------------------- - // graph | com.thinkaurelius.titan.core.TitanGraph (RW) - // ----------------------------------------------------------------------- - // objectFromResponse | Object - // ----------------------------------------------------------------------- - // precheckAddedList | java.util.HashMap - // ----------------------------------------------------------------------- - // precheckResponseMessages | org.openecomp.aai.extensions.AAIResponseMessages - // ======================================================================= - - private String message; - private ArrayList<String> templateVars; - private Exception preExtException; - private Exception postExtException; - private Method preExtErrorCallback; - private Method postExtErrorCallback; - private HttpServletRequest servletRequest; - private HttpHeaders httpHeaders; - private String objectFromRequestType; - private Object objectFromRequest; - private boolean preExtFailOnError = true; - private boolean postExtFailOnError = true; - private boolean preExtSkipErrorCallback = true; - private boolean postExtSkipErrorCallback = true; - private String fromAppId; - private String transId; - private Graph graph; - private Object objectFromResponse; - private HashMap<String, Object> lookupHashMap; - private HashMap<String, ArrayList<String>> precheckAddedList; - private AAIResponseMessages precheckResponseMessages; - private HashMap<String, Object> topology; - private HashMap<String, Vertex> vertexCache; - private String baseObject; - private String namespace; - private String fullResourceName; - private String topObjectFullResourceName; - private String uri; - private String notificationUri; - private String apiVersion; - private long startTime; - private long checkpointTime; - private DynamicJAXBContext jaxbContext; - private String objectFromResponseType; - private String eventAction; - private TransactionalGraphEngine dbEngine; - private Loader loader; - private UriInfo uriInfo; - private DBRequest dbRequest; - private HttpEntry httpEntry; - /** - * Sets the message. - * - * @param _message the new message - */ - public void setMessage(String _message) { - this.message = _message; - } - - /** - * Sets the template vars. - * - * @param _templateVars the new template vars - */ - public void setTemplateVars(ArrayList<String> _templateVars) { - this.templateVars = _templateVars; - } - - /** - * Sets the pre ext exception. - * - * @param _exception the new pre ext exception - */ - public void setPreExtException(Exception _exception) { - this.preExtException = _exception; - } - - /** - * Sets the pre ext error callback. - * - * @param _errorCallback the new pre ext error callback - */ - public void setPreExtErrorCallback(Method _errorCallback) { - this.preExtErrorCallback = _errorCallback; - } - - /** - * Sets the post ext exception. - * - * @param _exception the new post ext exception - */ - public void setPostExtException(Exception _exception) { - this.postExtException = _exception; - } - - /** - * Sets the post ext error callback. - * - * @param _errorCallback the new post ext error callback - */ - public void setPostExtErrorCallback(Method _errorCallback) { - this.postExtErrorCallback = _errorCallback; - } - - /** - * Sets the servlet request. - * - * @param _httpServletRequest the new servlet request - */ - public void setServletRequest(HttpServletRequest _httpServletRequest) { - this.servletRequest = _httpServletRequest; - } - - /** - * Sets the http headers. - * - * @param _httpHeaders the new http headers - */ - public void setHttpHeaders(HttpHeaders _httpHeaders) { - this.httpHeaders = _httpHeaders; - } - - /** - * Sets the object from request type. - * - * @param _objectFromRequestType the new object from request type - */ - public void setObjectFromRequestType(String _objectFromRequestType) { - this.objectFromRequestType = _objectFromRequestType; - } - - /** - * Sets the object from request. - * - * @param _objectFromRequest the new object from request - */ - public void setObjectFromRequest(Object _objectFromRequest) { - this.objectFromRequest = _objectFromRequest; - } - - /** - * Sets the object from response type. - * - * @param resourceClassName the new object from response type - */ - public void setObjectFromResponseType(String resourceClassName) { - // TODO Auto-generated method stub - this.objectFromResponseType = resourceClassName; - } - - /** - * Gets the object from response type. - * - * @return the object from response type - */ - public String getObjectFromResponseType() { - // TODO Auto-generated method stub - return this.objectFromResponseType; - } - - /** - * Sets the pre ext fail on error. - * - * @param _failOnError the new pre ext fail on error - */ - public void setPreExtFailOnError(boolean _failOnError) { - this.preExtFailOnError = _failOnError; - } - - /** - * Sets the post ext fail on error. - * - * @param _failOnError the new post ext fail on error - */ - public void setPostExtFailOnError(boolean _failOnError) { - this.postExtFailOnError = _failOnError; - } - - /** - * Gets the message. - * - * @return the message - */ - public String getMessage() { - return this.message; - } - - /** - * Gets the template vars. - * - * @return the template vars - */ - public ArrayList<String> getTemplateVars() { - if (this.templateVars == null) { - this.templateVars = new ArrayList<String>(); - } - return this.templateVars; - } - - /** - * Gets the pre ext exception. - * - * @return the pre ext exception - */ - public Exception getPreExtException() { - return this.preExtException; - } - - /** - * Gets the pre ext error callback. - * - * @return the pre ext error callback - */ - public Method getPreExtErrorCallback() { - return this.preExtErrorCallback; - } - - /** - * Gets the post ext exception. - * - * @return the post ext exception - */ - public Exception getPostExtException() { - return this.postExtException; - } - - /** - * Gets the post ext error callback. - * - * @return the post ext error callback - */ - public Method getPostExtErrorCallback() { - return this.postExtErrorCallback; - } - - /** - * Gets the http servlet request. - * - * @return the http servlet request - */ - public HttpServletRequest getHttpServletRequest() { - return this.servletRequest; - } - - /** - * Gets the http headers. - * - * @return the http headers - */ - public HttpHeaders getHttpHeaders() { - return this.httpHeaders; - } - - /** - * Gets the object from request type. - * - * @return the object from request type - */ - public String getObjectFromRequestType() { - return this.objectFromRequestType; - } - - /** - * Gets the object from request. - * - * @return the object from request - */ - public Object getObjectFromRequest() { - return this.objectFromRequest; - } - - /** - * Gets the pre ext fail on error. - * - * @return the pre ext fail on error - */ - public boolean getPreExtFailOnError() { - return this.preExtFailOnError; - } - - /** - * Gets the post ext fail on error. - * - * @return the post ext fail on error - */ - public boolean getPostExtFailOnError() { - return this.postExtFailOnError; - } - - /** - * Gets the from app id. - * - * @return the from app id - */ - public String getFromAppId() { - return this.fromAppId; - } - - /** - * Sets the from app id. - * - * @param fromAppId the new from app id - */ - public void setFromAppId(String fromAppId) { - this.fromAppId = fromAppId; - } - - /** - * Gets the trans id. - * - * @return the trans id - */ - public String getTransId() { - return this.transId; - } - - /** - * Sets the trans id. - * - * @param transId the new trans id - */ - public void setTransId(String transId) { - this.transId = transId; - } - - /** - * Gets the pre ext skip error callback. - * - * @return the pre ext skip error callback - */ - public boolean getPreExtSkipErrorCallback() { - return preExtSkipErrorCallback; - } - - /** - * Sets the pre ext skip error callback. - * - * @param preExtSkipErrorCallback the new pre ext skip error callback - */ - public void setPreExtSkipErrorCallback(boolean preExtSkipErrorCallback) { - this.preExtSkipErrorCallback = preExtSkipErrorCallback; - } - - /** - * Gets the post ext skip error callback. - * - * @return the post ext skip error callback - */ - public boolean getPostExtSkipErrorCallback() { - return postExtSkipErrorCallback; - } - - /** - * Sets the post ext skip error callback. - * - * @param postExtSkipErrorCallback the new post ext skip error callback - */ - public void setPostExtSkipErrorCallback(boolean postExtSkipErrorCallback) { - this.postExtSkipErrorCallback = postExtSkipErrorCallback; - } - - /** - * Gets the graph. - * - * @return the graph - */ - public Graph getGraph() { - return graph; - } - - /** - * Sets the graph. - * - * @param graph the new graph - */ - public void setGraph(Graph graph) { - this.graph = graph; - } - - /** - * Gets the object from response. - * - * @return the object from response - */ - public Object getObjectFromResponse() { - return objectFromResponse; - } - - /** - * Sets the object from response. - * - * @param objectFromResponse the new object from response - */ - public void setObjectFromResponse(Object objectFromResponse) { - this.objectFromResponse = objectFromResponse; - } - - /** - * Gets the lookup hash map. - * - * @return the lookup hash map - */ - public HashMap<String, Object> getLookupHashMap() { - if (this.lookupHashMap == null) { - this.lookupHashMap = new HashMap<String, Object>(); - } - return this.lookupHashMap; - } - - /** - * Sets the lookup hash map. - * - * @param lookupHashMap the lookup hash map - */ - public void setLookupHashMap(HashMap<String, Object> lookupHashMap) { - this.lookupHashMap = lookupHashMap; - } - - /** - * Gets the precheck added list. - * - * @return the precheck added list - */ - public HashMap<String, ArrayList<String>> getPrecheckAddedList() { - if (this.precheckAddedList == null) { - this.precheckAddedList = new HashMap<String, ArrayList<String>>(); - } - return precheckAddedList; - } - - /** - * Sets the precheck added list. - * - * @param precheckAddedList the precheck added list - */ - public void setPrecheckAddedList(HashMap<String, ArrayList<String>> precheckAddedList) { - this.precheckAddedList = precheckAddedList; - } - - /** - * Gets the precheck response messages. - * - * @return the precheck response messages - */ - public AAIResponseMessages getPrecheckResponseMessages() { - if (this.precheckResponseMessages == null) { - this.precheckResponseMessages = new AAIResponseMessages(); - } - return precheckResponseMessages; - } - - /** - * Sets the precheck response messages. - * - * @param precheckResponseData the new precheck response messages - */ - public void setPrecheckResponseMessages(AAIResponseMessages precheckResponseData) { - this.precheckResponseMessages = precheckResponseData; - } - - /** - * Gets the topology. - * - * @return the topology - */ - public HashMap<String, Object> getTopology() { - if (this.topology == null) { - this.topology = new HashMap<String, Object>(); - } - return topology; - } - - /** - * Gets the vertex cache. - * - * @return the vertex cache - */ - public HashMap<String, Vertex> getVertexCache() { - if (this.vertexCache == null) { - this.vertexCache = new HashMap<String, Vertex>(); - } - return vertexCache; - } - - /** - * Gets the base object. - * - * @return the base object - */ - public String getBaseObject() { - return baseObject; - } - - /** - * Sets the base object. - * - * @param baseObject the new base object - */ - public void setBaseObject(String baseObject) { - this.baseObject = baseObject; - } - - /** - * Gets the namespace. - * - * @return the namespace - */ - public String getNamespace() { - return namespace; - } - - /** - * Sets the namespace. - * - * @param namespace the new namespace - */ - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - /** - * Gets the full resource name. - * - * @return the full resource name - */ - public String getFullResourceName() { - return fullResourceName; - } - - /** - * Sets the full resource name. - * - * @param fullResourceName the new full resource name - */ - public void setFullResourceName(String fullResourceName) { - this.fullResourceName = fullResourceName; - } - - /** - * Gets the top object full resource name. - * - * @return the top object full resource name - */ - public String getTopObjectFullResourceName() { - return topObjectFullResourceName; - } - - /** - * Sets the top object full resource name. - * - * @param topObjectFullResourceName the new top object full resource name - */ - public void setTopObjectFullResourceName(String topObjectFullResourceName) { - this.topObjectFullResourceName = topObjectFullResourceName; - } - - /** - * Gets the uri. - * - * @return the uri - */ - public String getUri() { - return uri; - } - - /** - * Sets the uri. - * - * @param uri the new uri - */ - public void setUri(String uri) { - this.uri = uri; - } - - /** - * Gets the api version. - * - * @return the api version - */ - public String getApiVersion() { - return apiVersion; - } - - /** - * Sets the api version. - * - * @param apiVersion the new api version - */ - public void setApiVersion(String apiVersion) { - this.apiVersion = apiVersion; - } - - /** - * Sets the notification uri. - * - * @param uri the new notification uri - */ - public void setNotificationUri(String uri) { - this.notificationUri = uri; - - } - - /** - * Gets the notification uri. - * - * @return the notification uri - */ - public String getNotificationUri() { - return this.notificationUri; - - } - - /** - * Gets the start time. - * - * @return the start time - */ - public long getStartTime() { - return startTime; - } - - /** - * Sets the start time. - * - * @param startTime the new start time - */ - public void setStartTime(long startTime) { - this.startTime = startTime; - } - - /** - * Gets the checkpoint time. - * - * @return the checkpoint time - */ - public long getCheckpointTime() { - return checkpointTime; - } - - /** - * Sets the checkpoint time. - * - * @param checkpointTime the new checkpoint time - */ - public void setCheckpointTime(long checkpointTime) { - this.checkpointTime = checkpointTime; - } - - /** - * Gets the jaxb context. - * - * @return the jaxb context - */ - public DynamicJAXBContext getJaxbContext() { - return jaxbContext; - } - - /** - * Sets the jaxb context. - * - * @param jaxbContext the new jaxb context - */ - public void setJaxbContext(DynamicJAXBContext jaxbContext) { - this.jaxbContext = jaxbContext; - } - - /** - * Sets the event action. - * - * @param eventAction the new event action - */ - public void setEventAction(String eventAction) { - this.eventAction = eventAction; - } - - /** - * Gets the event action. - * - * @return the event action - */ - public String getEventAction() { - return this.eventAction; - } - - /** - * Gets the transactional graph engine. - * - * @return the transactional graph engine - */ - public TransactionalGraphEngine getTransactionalGraphEngine() { - return this.dbEngine; - - } - - /** - * Sets the transactional graph engine. - * - * @param dbEngine the new transactional graph engine - */ - public void setTransactionalGraphEngine(TransactionalGraphEngine dbEngine) { - this.dbEngine = dbEngine; - - } - - /** - * Gets the loader. - * - * @return the loader - */ - public Loader getLoader() { - return loader; - } - - /** - * Sets the loader. - * - * @param loader the new loader - */ - public void setLoader(Loader loader) { - this.loader = loader; - } - - /** - * Gets the uri info. - * - * @return the uri info - */ - public UriInfo getUriInfo() { - return uriInfo; - } - - /** - * Sets the uri info. - * - * @param uriInfo the new uri info - */ - public void setUriInfo(UriInfo uriInfo) { - this.uriInfo = uriInfo; - } - - public DBRequest getDbRequest() { - return dbRequest; - } - - public void setDbRequest(DBRequest dbRequest) { - this.dbRequest = dbRequest; - } - - public HttpEntry getHttpEntry() { - return httpEntry; - } - - public void setHttpEntry(HttpEntry httpEntry) { - this.httpEntry = httpEntry; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/extensions/ExtensionController.java b/aai-core/src/main/java/org/openecomp/aai/extensions/ExtensionController.java deleted file mode 100644 index cea0e9b7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/extensions/ExtensionController.java +++ /dev/null @@ -1,145 +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.extensions; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.util.AAIConfig; - -import java.lang.reflect.Method; - -public class ExtensionController { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ExtensionController.class); - - /** - * Run extension. - * - * @param apiVersion the api version - * @param namespace the namespace - * @param resourceName the resource name - * @param methodName the method name - * @param aaiExtMap the aai ext map - * @param isPreExtension the is pre extension - * @throws AAIException the AAI exception - */ - public void runExtension(String apiVersion, String namespace, - String resourceName, String methodName, AAIExtensionMap aaiExtMap, - boolean isPreExtension) throws AAIException { - String extensionClassName = "org.openecomp.aai.extensions." - + apiVersion.toLowerCase() + "." + namespace + "." - + resourceName + "Extension"; - String defaultErrorCallback = resourceName + "ExtensionErrorCallback"; - - String configOption = "aai.extensions." + apiVersion.toLowerCase() - + "." + namespace.toLowerCase() + "." - + resourceName.toLowerCase() + ".enabled"; - - try { - - String extensionEnabled = AAIConfig.get(configOption, "true"); - if (extensionEnabled.equalsIgnoreCase("false")) { - return; - } - - Class<?> clazz = Class.forName(extensionClassName); - - Method extension = clazz.getMethod(methodName, - new Class[] { AAIExtensionMap.class }); - if (extension != null) { - - Object ret = extension.invoke(clazz.newInstance(), aaiExtMap); - - if (ret instanceof Integer) { - Exception e = null; - - if (isPreExtension == true) { - e = aaiExtMap.getPreExtException(); - } else { - e = aaiExtMap.getPostExtException(); - } - - boolean failOnError = true; - if (isPreExtension == true) { - failOnError = aaiExtMap.getPreExtFailOnError(); - } else { - failOnError = aaiExtMap.getPostExtFailOnError(); - } - - if (e != null) { - boolean handleException = true; - if (isPreExtension == true) { - if (aaiExtMap.getPreExtSkipErrorCallback() == true) { - handleException = false; - } - } else { - if (aaiExtMap.getPostExtSkipErrorCallback() == true) { - handleException = false; - } - } - if (handleException == true) { - Method errorCallback = null; - if (isPreExtension == true) { - errorCallback = aaiExtMap - .getPreExtErrorCallback(); - } else { - errorCallback = aaiExtMap - .getPostExtErrorCallback(); - } - - if (errorCallback != null) { - errorCallback.invoke(clazz.newInstance(), - aaiExtMap); - } else { - Method defaultErrorCallbackExtension = clazz - .getMethod( - defaultErrorCallback, - new Class[] { AAIExtensionMap.class }); - defaultErrorCallbackExtension.invoke( - clazz.newInstance(), aaiExtMap); - } - } - } - - if (failOnError == true && e != null) { - throw e; - } else if (failOnError == false && e != null) { // in this - // case, we - // just note - // the error - // without - // stopping - LOGGER.warn("Error while processing extension - " + aaiExtMap.getMessage()); - } - } - } - } catch (ClassNotFoundException ex) { - LOGGER.debug("Extension class not found: " + extensionClassName + ", method: " + methodName + "."); - } catch (NoSuchMethodException e) { - LOGGER.debug("Method " + methodName + " does not exist for class " + extensionClassName); - } catch (AAIException e) { - throw e; - } catch (Exception e) { - throw new AAIException("AAI_5105", e); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java b/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java deleted file mode 100644 index 885f2854..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/ingestModel/CreateWidgetModels.java +++ /dev/null @@ -1,144 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.ingestModel; - -import java.io.File; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; -import java.util.Map.Entry; -import java.util.UUID; - -import javax.xml.transform.stream.StreamSource; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; - -/** - * The Class CreateWidgetModels. - */ -public class CreateWidgetModels -{ - /** - * The main method. - * - * @param args the arguments - * @throws Exception the exception - */ - public static void main(String[] args) throws Exception { - - String _apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP); - String widgetJsonDir = null; - String modelVersion = null; - if (args.length > 0) { - if (args[0] != null) { - _apiVersion = args[0]; - } - if (args[1] != null) { - widgetJsonDir = args[1]; - } - if (args[2] != null) { - modelVersion = args[2]; - } - } - - if (widgetJsonDir == null) { - System.err.println("You must specify a directory for widgetModelJson"); - System.exit(0); - } - if (modelVersion == null) { - System.err.println("You must specify a modelVersion"); - System.exit(0); - } - - - Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.valueOf(_apiVersion)); - - // iterate the collection of resources - - ArrayList<String> processedWidgets = new ArrayList<String>(); - for (Entry<String, Introspector> aaiResEnt : loader.getAllObjects().entrySet()) { - Introspector meObject = loader.introspectorFromName("model"); - // no need for a ModelVers DynamicEntity - - Introspector aaiRes = aaiResEnt.getValue(); - - if (!(aaiRes.isContainer() || aaiRes.getName().equals("aai-internal"))) { - String resource = aaiRes.getName(); - - if (processedWidgets.contains(resource)) { - continue; - } - processedWidgets.add(resource); - - String widgetName = resource; - String filePathString = widgetJsonDir + "/" + widgetName + "-" + modelVersion + ".json"; - File f = new File(filePathString); - - String filePathString2 = widgetJsonDir + "/../widget-model-json-old/" + widgetName + "-" + modelVersion + ".json"; - File f2 = new File(filePathString2); - - if(!f.exists() && !f.isDirectory()) { - - if (f2.exists()) { - System.out.println("Using old file for " + resource + "."); - - meObject = loader.unmarshal("model", new StreamSource(f2).getReader().toString()); - // override, some of them are wrong - meObject.setValue("model-version", modelVersion); - } else { - System.out.println("Making new file for " + resource + "."); - meObject.setValue("model-invariant-id", UUID.randomUUID().toString()); - meObject.setValue("model-type", "widget"); - Introspector mevObject = loader.introspectorFromName("model-ver"); - Introspector mevsObject = loader.introspectorFromName("model-vers"); - mevObject.setValue("model-version-id", UUID.randomUUID().toString()); - mevObject.setValue("model-version", modelVersion); - mevObject.setValue("model-Name", widgetName); - // make a list of dynamic Entities - List<Object> mevsList = new ArrayList<>(); - // add this one, it will be the only one in the list in this case - mevsList.add(mevObject.getUnderlyingObject()); - mevsObject.setValue("model-ver", mevsList); - // Have to figure out how to add my mev object to the mevsObject, - // the modelVers is a list of dynamic entities so we can just attach the array here - meObject.setValue("model-vers",mevsObject.getUnderlyingObject()); - } - - // put it out as JSON - - PrintWriter out = new PrintWriter(f); - out.println(meObject.marshal(true)); - out.close(); - - } else { - System.out.println("File already exists for " + resource + ". Skipping."); - } - } - } - System.exit(0); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java deleted file mode 100644 index 1c8baa10..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Introspector.java +++ /dev/null @@ -1,617 +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.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import org.apache.commons.lang.ClassUtils; -import org.eclipse.persistence.exceptions.DynamicException; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.workarounds.NamingExceptions; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.util.*; - -public abstract class Introspector implements Cloneable { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(Introspector.class); - - protected String className; - protected String uriChain = ""; - protected Loader loader; - protected final NamingExceptions namingException = NamingExceptions.getInstance(); - private Set<String> uniqueProperties = null; - private Set<String> indexedProperties = null; - private Set<String> allKeys = null; - protected Introspector(Object obj) { - } - - public abstract boolean hasProperty(String name); - - protected String convertPropertyName (String name) { - return CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name); - } - - protected abstract Object get(String name); - protected abstract void set(String name, Object value); - /** - * - * @param name the property name you'd like to retrieve the value for - * @return the value of the property - */ - public <T> T getValue(String name) { - String convertedName = convertPropertyName(name); - Object result = null; - - if (this.hasProperty(name)) { - result = this.get(convertedName); - } else { - /* property not found - slightly ambiguous */ - return null; - } - - Class<?> clazz = this.getClass(name); - if (this.isListType(name) && result == null) { - try { - this.set(convertedName, clazz.newInstance()); - result = this.get(convertedName); - } catch (DynamicException | InstantiationException | IllegalAccessException e) { - - } - } - - return (T)result; - } - - public Introspector getWrappedValue(String name) { - String convertedName = convertPropertyName(name); - Object value = null; - - if (this.hasProperty(name)) { - value = this.get(convertedName); - } else { - /* property not found - slightly ambiguous */ - return null; - } - - Class<?> clazz = this.getClass(name); - if (this.isListType(name) && value == null) { - try { - this.set(convertedName, clazz.newInstance()); - value = this.get(convertedName); - } catch (DynamicException | InstantiationException | IllegalAccessException e) { - - } - } - if (value != null) { - return IntrospectorFactory.newInstance(this.getModelType(), value); - } else { - //no value - return null; - } - - } - - public List<Introspector> getWrappedListValue(String name) { - String convertedName = convertPropertyName(name); - Object value = null; - List<Introspector> resultList = new ArrayList<>(); - if (this.hasProperty(name)) { - value = this.get(convertedName); - } else { - /* property not found - slightly ambiguous */ - return null; - } - boolean isListType = this.isListType(name); - if (!this.isListType(name)) { - return null; - } - Class<?> clazz = this.getClass(name); - if (isListType && value == null) { - try { - this.set(convertedName, clazz.newInstance()); - value = this.get(convertedName); - } catch (DynamicException | InstantiationException | IllegalAccessException e) { - - } - } - - List<Object> valueList = (List<Object>)value; - - for (Object item : valueList) { - resultList.add(IntrospectorFactory.newInstance(this.getModelType(), item)); - } - - return resultList; - - } - - public Object castValueAccordingToSchema(String name, Object obj) { - Object result = obj; - Class<?> nameClass = this.getClass(name); - if (nameClass == null) { - throw new IllegalArgumentException("property: " + name + " does not exist on " + this.getDbName()); - } - if (obj != null) { - - try { - if (!obj.getClass().getName().equals(nameClass.getName())) { - if (nameClass.isPrimitive()) { - nameClass = ClassUtils.primitiveToWrapper(nameClass); - result = nameClass.getConstructor(String.class).newInstance(obj.toString()); - } - if (obj instanceof String) { - result = nameClass.getConstructor(String.class).newInstance(obj); - } else if (!this.isListType(name) && !this.isComplexType(name)){ - //box = obj.toString(); - result = nameClass.getConstructor(String.class).newInstance(obj.toString()); - } - } - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException | SecurityException e) { - ErrorLogHelper.logError("AAI_4017", e.getMessage()); - } - } - return result; - } - - public List<Object> castValueAccordingToSchema(String name, List<?> objs) { - List<Object> result = new ArrayList<>(); - - for (Object item : objs) { - result.add(this.castValueAccordingToSchema(name, item)); - } - - return result; - - } - /** - * - * @param name the property name you'd like to set the value of - * @param obj the value to be set - * @return - */ - public void setValue(String name, Object obj) throws IllegalArgumentException { - Object box = this.castValueAccordingToSchema(name, obj); - - name = convertPropertyName(name); - this.set(name, box); - } - /** - * - * @return a list of all the properties available on the object - */ - public abstract Set<String> getProperties(); - - public Set<String> getProperties(PropertyPredicate<Introspector, String> p) { - final Set<String> temp = new LinkedHashSet<>(); - this.getProperties().stream().filter(item -> { - return p.test(this, item); - }).forEach(item -> { - temp.add(item); - }); - final Set<String> result = Collections.unmodifiableSet(temp); - - return result; - - } - /** - * - * @return a list of the required properties on the object - */ - public abstract Set<String> getRequiredProperties(); - /** - * - * @return a list of the properties that can be used to query the object in the db - */ - public abstract Set<String> getKeys(); - /** - * - * @return a list of the all key properties for this object - */ - public Set<String> getAllKeys() { - Set<String> result = null; - if (this.allKeys == null) { - Set<String> keys = this.getKeys(); - result = new LinkedHashSet<>(); - result.addAll(keys); - String altKeys = this.getMetadata(ObjectMetadata.ALTERNATE_KEYS_1); - if (altKeys != null) { - String[] altKeysArray = altKeys.split(","); - for (String altKey : altKeysArray) { - result.add(altKey); - } - } - result = Collections.unmodifiableSet(result); - this.allKeys = result; - } - result = this.allKeys; - return result; - } - - public Set<String> getIndexedProperties() { - Set<String> result = null; - - if (this.indexedProperties == null) { - result = new LinkedHashSet<>(); - Set<String> keys = this.getKeys(); - result.addAll(keys); - String altKeys = this.getMetadata(ObjectMetadata.INDEXED_PROPS); - if (altKeys != null) { - String[] altKeysArray = altKeys.split(","); - for (String altKey : altKeysArray) { - result.add(altKey); - } - } - this.indexedProperties = Collections.unmodifiableSet(result); - } - result = this.indexedProperties; - return result; - } - - public Set<String> getUniqueProperties() { - Set<String> result = null; - if (this.uniqueProperties == null) { - String altKeys = this.getMetadata(ObjectMetadata.UNIQUE_PROPS); - result = new LinkedHashSet<>(); - if (altKeys != null) { - String[] altKeysArray = altKeys.split(","); - for (String altKey : altKeysArray) { - result.add(altKey); - } - } - this.uniqueProperties = Collections.unmodifiableSet(result); - - } - result = this.uniqueProperties; - return result; - } - - public Set<String> getDependentOn() { - String dependentOn = this.getMetadata(ObjectMetadata.DEPENDENT_ON); - if (dependentOn == null) { - return new LinkedHashSet<>(); - } - return new LinkedHashSet<>(Arrays.asList(dependentOn.split(","))); - } - /** - * - * @param name - * @return the string name of the java class of the named property - */ - public String getType(String name) { - Class<?> resultClass = this.getClass(name); - String result = ""; - - if (resultClass != null) { - result = resultClass.getName(); - if (result.equals("java.util.ArrayList")) { - result = "java.util.List"; - } - } - - return result; - } - /** - * This will returned the generic parameterized type of the underlying - * object if it exists - * @param name - * @return the generic type of the java class of the underlying object - */ - public String getGenericType(String name) { - Class<?> resultClass = this.getGenericTypeClass(name); - String result = ""; - - if (resultClass != null) { - result = resultClass.getName(); - } - - return result; - } - /** - * - * @return the string name of the java class of the underlying object - */ - public abstract String getJavaClassName(); - - /** - * - * @param name the property name - * @return the Class object - */ - public abstract Class<?> getClass(String name); - - public abstract Class<?> getGenericTypeClass(String name); - - /** - * - * @param name the property name - * @return a new instance of the underlying type of this property - * @throws AAIUnknownObjectException - */ - public Object newInstanceOfProperty(String name) throws AAIUnknownObjectException { - String type = this.getType(name); - return loader.objectFromName(type); - } - - public Object newInstanceOfNestedProperty(String name) throws AAIUnknownObjectException { - String type = this.getGenericType(name); - return loader.objectFromName(type); - } - - - public Introspector newIntrospectorInstanceOfProperty(String name) throws AAIUnknownObjectException { - - Introspector result = IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfProperty(name)); - - return result; - - } - - public Introspector newIntrospectorInstanceOfNestedProperty(String name) throws AAIUnknownObjectException { - - Introspector result = IntrospectorFactory.newInstance(this.getModelType(), this.newInstanceOfNestedProperty(name)); - - return result; - - } - /** - * Is this type not a Java String or primitive - * @param name - * @return - */ - public boolean isComplexType(String name) { - String result = this.getType(name); - - if (result.contains("aai") || result.equals("java.lang.Object")) { - return true; - } else { - return false; - } - } - - public boolean isComplexGenericType(String name) { - String result = this.getGenericType(name); - - if (result.contains("aai")) { - return true; - } else { - return false; - } - } - - public boolean isSimpleType(String name) { - return !(this.isComplexType(name) || this.isListType(name)); - } - - public boolean isSimpleGenericType(String name) { - return !this.isComplexGenericType(name); - } - - public boolean isListType(String name) { - String result = this.getType(name); - - if (result.contains("java.util.List")) { - return true; - } else { - return false; - } - } - - public boolean isContainer() { - Set<String> props = this.getProperties(); - boolean result = false; - if (props.size() == 1 && this.isListType(props.iterator().next())) { - result = true; - } - - return result; - } - - public abstract String getChildName(); - public String getChildDBName() { - String result = this.getChildName(); - - result = namingException.getDBName(result); - return result; - } - public abstract String getName(); - - public String getDbName() { - String lowerHyphen = this.getName(); - - lowerHyphen = namingException.getDBName(lowerHyphen); - - return lowerHyphen; - } - - public abstract ModelType getModelType(); - - public boolean hasChild(Introspector child) { - boolean result = false; - //check all inheriting types for this child - if ("true".equals(this.getMetadata(ObjectMetadata.ABSTRACT))) { - String[] inheritors = this.getMetadata(ObjectMetadata.INHERITORS).split(","); - for (String inheritor : inheritors) { - try { - Introspector temp = this.loader.introspectorFromName(inheritor); - result = temp.hasProperty(child.getName()); - if (result) { - break; - } - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping inheritor " + inheritor + " (Unknown Object)", e); - } - } - } else { - result = this.hasProperty(child.getName()); - } - return result; - } - - public void setURIChain(String uri) { - this.uriChain = uri; - } - public abstract String getObjectId() throws UnsupportedEncodingException; - - public String getURI() throws UnsupportedEncodingException { - //String result = this.uriChain; - String result = ""; - String namespace = this.getMetadata(ObjectMetadata.NAMESPACE); - String container = this.getMetadata(ObjectMetadata.CONTAINER); - if (this.isContainer()) { - result += "/" + this.getName(); - } else { - - if (container != null) { - result += "/" + container; - } - result += "/" + this.getDbName() + "/" + this.findKey(); - - if (namespace != null && !namespace.equals("")) { - result = "/" + namespace + result; - } - } - - - return result; - } - - public String getGenericURI() { - String result = ""; - if (this.isContainer()) { - result += "/" + this.getName(); - } else { - result += "/" + this.getDbName(); - for (String key : this.getKeys()) { - result += "/{" + this.getDbName() + "-" + key + "}"; - } - } - - return result; - } - - public String getFullGenericURI() { - String result = ""; - String namespace = this.getMetadata(ObjectMetadata.NAMESPACE); - String container = this.getMetadata(ObjectMetadata.CONTAINER); - if (this.isContainer()) { - result += "/" + this.getName(); - } else { - - - if (container != null) { - result += "/" + container; - } - result += "/" + this.getDbName(); - - for (String key : this.getKeys()) { - result += "/{" + this.getDbName() + "-" + key + "}"; - } - if (namespace != null && !namespace.equals("")) { - result = "/" + namespace + result; - } - - } - - return result; - } - - public abstract String preProcessKey(String key); - - protected abstract String findKey() throws UnsupportedEncodingException; - - public abstract String marshal(MarshallerProperties properties); - - public abstract Object clone(); - - public abstract Object getUnderlyingObject(); - - public String marshal(boolean formatted) { - MarshallerProperties properties = - new MarshallerProperties.Builder(MediaType.APPLICATION_JSON_TYPE).formatted(formatted).build(); - - return marshal(properties); - } - public String makeSingular(String word) { - - String result = word; - result = result.replaceAll("(?:([ho])es|s)$", ""); - - if (result.equals("ClassesOfService")) { - result = "ClassOfService"; - } else if (result.equals("CvlanTag")) { - result = "CvlanTagEntry"; - } else if (result.equals("Metadata")) { - result = "Metadatum"; - } - return result; - } - - protected String makePlural(String word) { - String result = word; - - if (result.equals("cvlan-tag-entry")) { - return "cvlan-tags"; - } else if (result.equals("class-of-service")) { - return "classes-of-service"; - } else if (result.equals("metadatum")) { - return "metadata"; - } - result = result.replaceAll("([a-z])$", "$1s"); - result = result.replaceAll("([hox])s$", "$1es"); - /* - if (result.equals("classes-of-services")) { - result = "classes-of-service"; - }*/ - - return result; - } - - public abstract String getMetadata(ObjectMetadata metadataName); - public abstract Map<PropertyMetadata, String> getPropertyMetadata(String propName); - public Optional<String> getPropertyMetadata(String propName, PropertyMetadata metadataName) { - final String resultValue = this.getPropertyMetadata(propName).getOrDefault(metadataName, ""); - Optional<String> result = Optional.empty(); - - if (!resultValue.isEmpty()) { - result = Optional.of(resultValue); - } - return result; - - } - - public abstract Version getVersion(); - public Loader getLoader() { - return this.loader; - } - - public boolean isTopLevel() { - - return this.getMetadata(ObjectMetadata.NAMESPACE) != null; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorFactory.java b/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorFactory.java deleted file mode 100644 index 760f3a68..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorFactory.java +++ /dev/null @@ -1,65 +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.introspection; - -public class IntrospectorFactory { - - /** - * New instance. - * - * @param type the type - * @param o the o - * @param llBuilder the ll builder - * @return the introspector - */ - public static Introspector newInstance(ModelType type, Object o) { - - if (type.equals(ModelType.MOXY)) { - return new MoxyStrategy(o); - } else if (type.equals(ModelType.POJO)) { - return new PojoStrategy(o); - } else if (type.equals(ModelType.JSON)) { - return new JSONStrategy(o); - } else { - throw new IllegalArgumentException("Unknown class type: " + type); - } - - } - - /** - * New instance. - * - * @param type the type - * @param o the o - * @param namedType the named type - * @param llBuilder the ll builder - * @return the introspector - */ - public static Introspector newInstance(ModelType type, Object o, String namedType) { - - if (type.equals(ModelType.JSON)) { - return new JSONStrategy(o, namedType); - } else { - throw new IllegalArgumentException("Unknown class type: " + type); - } - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorWalker.java b/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorWalker.java deleted file mode 100644 index 8eddac3b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/IntrospectorWalker.java +++ /dev/null @@ -1,193 +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.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; - -public class IntrospectorWalker { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(IntrospectorWalker.class); - - private Wanderer w = null; - private Set<String> blacklist = null; - private boolean preventCycles = false; - private final PropertyPredicate<Introspector, String> propVisibility; - - /** - * Instantiates a new introspector walker. - * - * @param w the w - * @param llBuilder the ll builder - */ - public IntrospectorWalker(Wanderer w) { - this.w = w; - this.blacklist = new HashSet<>(); - this.propVisibility = null; - } - - public IntrospectorWalker(Wanderer w, PropertyPredicate<Introspector, String> p) { - this.w = w; - this.blacklist = new HashSet<>(); - this.propVisibility = p; - } - - - /** - * Sets the blacklist. - * - * @param list the new blacklist - */ - public void setBlacklist(List<String> list) { - blacklist.addAll(list); - } - - /** - * Prevent cycles. - * - * @param prevent the prevent - */ - public void preventCycles(boolean prevent) { - this.preventCycles = prevent; - } - - /** - * Walk. - * - * @param obj the obj - * @throws AAIException - */ - public void walk(Introspector obj) throws AAIException { - Set<String> visited = new HashSet<>(); - - walk(obj, null, visited); - } - - /** - * Walk. - * - * @param obj the obj - * @param parent the parent - * @throws AAIException - */ - private void walk(Introspector obj, Introspector parent, Set<String> visited) throws AAIException { - boolean stopRecursion = false; - Set<String> localVisited = new HashSet<>(); - localVisited.addAll(visited); - if (preventCycles) { - if (visited.contains(obj.getName())) { - stopRecursion = true; - } - if (!obj.isContainer()) { - localVisited.add(obj.getName()); //so we don't recurse while walking its children - } - } - Set<String> props; - //props must duplicate the result from getProperties because - //it is unmodifiable - if (this.propVisibility == null) { - props = new LinkedHashSet<>(obj.getProperties()); - } else { - props = new LinkedHashSet<>(obj.getProperties(this.propVisibility)); - } - - w.processComplexObj(obj); - props.removeAll(blacklist); - if (!obj.isContainer()) { - parent = obj; - } - for (String prop : props) { - - if (obj.isSimpleType(prop)) { - - w.processPrimitive(prop, obj); - } else if (obj.isListType(prop) && !stopRecursion) { - - List<Object> listReference = obj.getValue(prop); - boolean isComplexType = obj.isComplexGenericType(prop); - if (isComplexType) { - List<Introspector> list = obj.getWrappedListValue(prop); - try { - Introspector child = obj.newIntrospectorInstanceOfNestedProperty(prop); - w.modifyComplexList(list, listReference, parent, child); - for (Object item : listReference) { - child = IntrospectorFactory.newInstance(obj.getModelType(), item); - walk(child, parent, localVisited); - } - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping property " + prop + " (Unknown Object)", e); - } - } else { - w.processPrimitiveList(prop, obj); - } - if (listReference.size() == 0) { - if (isComplexType) { - try { - Introspector child = obj.newIntrospectorInstanceOfNestedProperty(prop); - int size = w.createComplexListSize(parent, child); - for (int i = 0; i < size; i++) { - child = obj.newIntrospectorInstanceOfNestedProperty(prop); - walk(child, parent, localVisited); - listReference.add(child.getUnderlyingObject()); - } - - obj.setValue(prop, listReference); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping property " + prop + " (Unknown Object)", e); - } - } else if (!isComplexType){ - w.processPrimitiveList(prop, obj); - } - } - - } else if (obj.isComplexType(prop) && !stopRecursion) { - Introspector child = null; - if (obj.getValue(prop) != null) { - child = IntrospectorFactory.newInstance(obj.getModelType(), obj.getValue(prop)); - } else { - if (w.createComplexObjIfNull()) { - try { - child = obj.newIntrospectorInstanceOfProperty(prop); - obj.setValue(prop, child.getUnderlyingObject()); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping property " + prop + " (Unknown Object)", e); - } - } - } - if (child != null) { - walk(child, obj, localVisited); - } - } - - } - /* - if (preventCycles && !obj.isContainer()) { - visited.remove(obj.getName()); //so we can see it down another path that isn't in danger of recursing over it - }*/ - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/JSONStrategy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/JSONStrategy.java deleted file mode 100644 index 7dae20ee..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/JSONStrategy.java +++ /dev/null @@ -1,359 +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.introspection; - -import org.json.simple.JSONObject; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.io.UnsupportedEncodingException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -public class JSONStrategy extends Introspector { - - private JSONObject json = null; - private String namedType = ""; - protected JSONStrategy(Object o) { - super(o); - json = (JSONObject)o; - //Assumes you provide a wrapper - Set<String> keySet = json.keySet(); - if (keySet.size() == 1) { - namedType = keySet.iterator().next(); - json = (JSONObject)json.get(namedType); - } else { - throw new IllegalArgumentException("This object has no named type."); - } - } - - protected JSONStrategy(Object o, String namedType) { - super(o); - json = (JSONObject)o; - this.namedType = namedType; - - } - - @Override - public boolean hasProperty(String name) { - //TODO - return true; - } - @Override - public Object getValue(String name) { - Object result = ""; - result = json.get(name); - - return result; - } - - @Override - public void setValue(String name, Object obj) { - json.put(name, obj); - - } - @Override - public Object getUnderlyingObject() { - return this.json; - } - - @Override - public Set<String> getProperties() { - Set<String> result = json.keySet(); - return result; - } - - @Override - public Set<String> getRequiredProperties() { - //unknowable - - return this.getProperties(); - } - - @Override - public Set<String> getKeys() { - //unknowable - return this.getProperties(); - } - - @Override - public Set<String> getAllKeys() { - //unknowable - return this.getProperties(); - } - - @Override - public String getType(String name) { - String result = ""; - Class<?> resultClass = this.getClass(name); - if (resultClass != null) { - result = resultClass.getName(); - } - - if (result.equals("org.json.simple.JSONArray")) { - result = "java.util.List"; - } - - return result; - } - - @Override - public String getGenericType(String name) { - String result = ""; - Class<?> resultClass = this.getGenericTypeClass(name); - if (resultClass != null) { - result = resultClass.getName(); - } - return result; - } - - @Override - public String getJavaClassName() { - return json.getClass().getName(); - } - - @Override - public Class<?> getClass(String name) { - Class<?> result = null; - result = json.get(name).getClass(); - - return result; - } - - @Override - public Class<?> getGenericTypeClass(String name) { - Object resultObject = null; - Class<?> resultClass = null; - resultObject = this.getValue(name); - if (resultObject.getClass().getName().equals("org.json.simple.JSONArray")) { - resultClass = ((List)resultObject).get(0).getClass(); - } - - return resultClass; - } - - @Override - public Object newInstanceOfProperty(String name) { - try { - return this.getClass(name).newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - return null; - } - } - - @Override - public Object newInstanceOfNestedProperty(String name) { - try { - return this.getGenericTypeClass(name).newInstance(); - } catch (InstantiationException | IllegalAccessException e) { - return null; - } - } - - @Override - public boolean isComplexType(String name) { - String result = this.getType(name); - - if (result.contains("JSONObject")) { - return true; - } else { - return false; - } - - } - - @Override - public boolean isComplexGenericType(String name) { - String result = this.getGenericType(name); - - if (result.contains("JSONObject")) { - return true; - } else { - return false; - } - - } - - @Override - public boolean isListType(String name) { - String result = this.getType(name); - - if (result.contains("java.util.List")) { - return true; - } else { - return false; - } - - } - - @Override - public boolean isContainer() { - Set<String> props = this.getProperties(); - boolean result = false; - if (props.size() == 1 && this.isListType(props.iterator().next())) { - result = true; - } - - return result; - } - @Override - protected String findKey() { - return ""; - } - - @Override - public String getName() { - return this.namedType; - } - - @Override - public String getDbName() { - return this.getName(); - } - - @Override - public String getURI() { - - // use a UUID for now - return UUID.randomUUID().toString(); - } - - @Override - public String getGenericURI() { - - //there is none defined for this - return ""; - } - - @Override - public String preProcessKey (String key) { - - // don't do anything with it - return key; - - } - - @Override - public String marshal(MarshallerProperties properties) { - //TODO - return null; - } - - @Override - public Object clone() { - //TODO - return null; - } - - /*@Override - public String findEdgeName(String parent, String child) { - - // Always has for now - return "has"; - - }*/ - - @Override - public ModelType getModelType() { - return ModelType.JSON; - } - - @Override - public Set<String> getIndexedProperties() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getChildName() { - // TODO Auto-generated method stub - return null; - } - - @Override - public boolean hasChild(Introspector child) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isSimpleType(String name) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isSimpleGenericType(String name) { - // TODO Auto-generated method stub - return false; - } - - @Override - public Map<PropertyMetadata, String> getPropertyMetadata(String prop) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getMetadata(ObjectMetadata metadataName) { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getChildDBName() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getFullGenericURI() { - // TODO Auto-generated method stub - return null; - } - - @Override - protected Object get(String name) { - // TODO Auto-generated method stub - return null; - } - - @Override - protected void set(String name, Object value) { - // TODO Auto-generated method stub - - } - - @Override - public String getObjectId() throws UnsupportedEncodingException { - // TODO Auto-generated method stub - return null; - } - - @Override - public Version getVersion() { - // TODO Auto-generated method stub - return null; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Loader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Loader.java deleted file mode 100644 index b5a029ed..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Loader.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.introspection; - -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.restcore.MediaType; - -import java.util.Map; - -public abstract class Loader { - - private final Version version; - private final ModelType modelType; - - /** - * Instantiates a new loader. - * - * @param version the version - * @param modelType the model type - * @param llBuilder the ll builder - */ - public Loader (Version version, ModelType modelType) { - this.version = version; - this.modelType = modelType; - } - - /** - * Process. - * - * @param version the version - */ - protected abstract void process(Version version); - - /** - * Object from name. - * - * @param name the name - * @return the object - * @throws AAIUnknownObjectException - */ - public abstract Object objectFromName(String name) throws AAIUnknownObjectException; - - /** - * Introspector from name. - * - * @param name the name - * @return the introspector - * @throws AAIUnknownObjectException - */ - public abstract Introspector introspectorFromName(String name) throws AAIUnknownObjectException; - - /** - * Unmarshal. - * - * @param type the type - * @param json the json - * @param mediaType the media type - * @return the introspector - */ - public abstract Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException; - - /** - * Unmarshal. - * - * @param type the type - * @param json the json - * @return the introspector - */ - public Introspector unmarshal(String type, String json) throws AAIUnmarshallingException { - return unmarshal(type, json, MediaType.APPLICATION_JSON_TYPE); - } - - - /** - * Gets the model type. - * - * @return the model type - */ - public ModelType getModelType() { - return this.modelType; - } - - /** - * Gets the version. - * - * @return the version - */ - public Version getVersion() { - return this.version; - } - - public abstract Map<String, Introspector> getAllObjects(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/LoaderFactory.java b/aai-core/src/main/java/org/openecomp/aai/introspection/LoaderFactory.java deleted file mode 100644 index 23b762d5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/LoaderFactory.java +++ /dev/null @@ -1,44 +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.introspection; - -public class LoaderFactory { - - /** - * Creates a new Loader object. - * - * @param type the type - * @param version the version - * @param llBuilder the ll builder - * @return the loader - */ - public static Loader createLoaderForVersion(ModelType type, Version version) { - - if (type.equals(ModelType.MOXY)) { - return new MoxyLoader(version); - } else if (type.equals(ModelType.POJO)) { - return new PojoLoader(version); - } - - return null; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/MarshallerProperties.java b/aai-core/src/main/java/org/openecomp/aai/introspection/MarshallerProperties.java deleted file mode 100644 index 8b9ee2d7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/MarshallerProperties.java +++ /dev/null @@ -1,139 +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.introspection; - -import org.openecomp.aai.restcore.MediaType; - -public class MarshallerProperties { - - private final MediaType type; - private final boolean includeRoot; - private final boolean wrapperAsArrayName; - private final boolean formatted; - - /** - * Instantiates a new marshaller properties. - * - * @param builder the builder - */ - private MarshallerProperties(Builder builder) { - - this.type = builder.type; - this.includeRoot = builder.includeRoot; - this.wrapperAsArrayName = builder.wrapperAsArrayName; - this.formatted = builder.formatted; - } - - /** - * Gets the media type. - * - * @return the media type - */ - public MediaType getMediaType() { - return this.type; - } - - /** - * Gets the include root. - * - * @return the include root - */ - public boolean getIncludeRoot() { - return this.includeRoot; - } - - /** - * Gets the wrapper as array name. - * - * @return the wrapper as array name - */ - public boolean getWrapperAsArrayName() { - return this.wrapperAsArrayName; - } - - /** - * Gets the formatted. - * - * @return the formatted - */ - public boolean getFormatted() { - return this.formatted; - } - - public static class Builder { - - private final MediaType type; - private boolean includeRoot = false; - private boolean wrapperAsArrayName = true; - private boolean formatted = false; - - /** - * Instantiates a new builder. - * - * @param type the type - */ - public Builder(MediaType type) { - this.type = type; - } - - /** - * Include root. - * - * @param includeRoot the include root - * @return the builder - */ - public Builder includeRoot (boolean includeRoot) { - this.includeRoot = includeRoot; - return this; - } - - /** - * Wrapper as array name. - * - * @param wrapperAsArrayName the wrapper as array name - * @return the builder - */ - public Builder wrapperAsArrayName (boolean wrapperAsArrayName) { - this.wrapperAsArrayName = wrapperAsArrayName; - return this; - } - - /** - * Formatted. - * - * @param formatted the formatted - * @return the builder - */ - public Builder formatted (boolean formatted) { - this.formatted = formatted; - return this; - } - - /** - * Builds the properties. - * - * @return the marshaller properties - */ - public MarshallerProperties build() { - return new MarshallerProperties(this); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelInjestor.java b/aai-core/src/main/java/org/openecomp/aai/introspection/ModelInjestor.java deleted file mode 100644 index c6503a69..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelInjestor.java +++ /dev/null @@ -1,173 +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.introspection; - -import org.eclipse.persistence.dynamic.DynamicType; -import org.eclipse.persistence.jaxb.JAXBContextProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContextFactory; -import org.openecomp.aai.util.AAIConstants; - -import javax.xml.bind.JAXBException; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ModelInjestor { - - private Map<Version, DynamicJAXBContext> versionContextMap = new HashMap<>(); - private static final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\."); - private static final Pattern uriPattern = Pattern.compile("(v\\d+)\\/"); - - - /** - * Instantiates a new model injestor. - */ - private ModelInjestor() { - try { - injestModels(); - } catch (FileNotFoundException | JAXBException e) { - throw new RuntimeException(e); - } - } - - private static class Helper { - private static final ModelInjestor INSTANCE = new ModelInjestor(); - } - - /** - * Gets the single instance of ModelInjestor. - * - * @return single instance of ModelInjestor - */ - public synchronized static ModelInjestor getInstance() { - return Helper.INSTANCE; - } - - /** - * Injest models. - * - * @throws FileNotFoundException the file not found exception - * @throws JAXBException the JAXB exception - */ - private void injestModels() throws FileNotFoundException, JAXBException { - - for (Version version : Version.values()) { - this.injestModel(version); - } - } - - /** - * Injest model. - * - * @param version the version - * @throws JAXBException the JAXB exception - * @throws FileNotFoundException the file not found exception - */ - private void injestModel (Version version) throws JAXBException, FileNotFoundException { - String fileName = this.getOXMFileName(version); - InputStream iStream = new FileInputStream(new File(fileName)); - Map<String, Object> properties = new HashMap<String, Object>(); - properties.put(JAXBContextProperties.OXM_METADATA_SOURCE, iStream); - final DynamicJAXBContext jaxbContext = DynamicJAXBContextFactory.createContextFromOXM(this.getClass().getClassLoader(), properties); - versionContextMap.put(version, jaxbContext); - } - - /** - * Gets the version from class name. - * - * @param classname the classname - * @return the version from class name - */ - public Version getVersionFromClassName (String classname) { - Matcher m = classNamePattern.matcher(classname); - String version = "v2"; //for the OXM, only the v2 ones don't include a model name, hence this default - if (m.find()) { - version = m.group(1); - } - - return Version.valueOf(version); - } - - /** - * Gets the context for URI. - * - * @param uri the uri - * @return the context for URI - */ - public DynamicJAXBContext getContextForURI(String uri) { - DynamicJAXBContext result = null; - Matcher m = uriPattern.matcher(uri); - Version version = null; - if (m.find()) { - version = Version.valueOf(m.group(1)); - result = versionContextMap.get(version); - } - - return result; - } - - /** - * Gets the context for version. - * - * @param version the version - * @return the context for version - */ - public DynamicJAXBContext getContextForVersion(Version version) { - DynamicJAXBContext result = null; - - result = versionContextMap.get(version); - - - return result; - } - - /** - * Gets the dynamic type for class name. - * - * @param classname the classname - * @return the dynamic type for class name - */ - public DynamicType getDynamicTypeForClassName(String classname) { - DynamicType result = null; - DynamicJAXBContext context = null; - - Version version = this.getVersionFromClassName(classname); - - context = versionContextMap.get(version); - - if (context != null) { - result = context.getDynamicType(classname); - } - - return result; - } - - public String getOXMFileName(Version v) { - return AAIConstants.AAI_HOME_ETC_OXM + "aai_oxm_" + v.toString() + ".xml"; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelType.java b/aai-core/src/main/java/org/openecomp/aai/introspection/ModelType.java deleted file mode 100644 index 132b754b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/ModelType.java +++ /dev/null @@ -1,25 +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.introspection; - -public enum ModelType { - MOXY, POJO, JSON -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java deleted file mode 100644 index 80b05aee..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyLoader.java +++ /dev/null @@ -1,195 +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.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import com.google.common.collect.ImmutableMap; -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.workarounds.NamingExceptions; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.stream.StreamSource; -import java.io.IOException; -import java.io.StringReader; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -public class MoxyLoader extends Loader { - - private DynamicJAXBContext jaxbContext = null; - private EELFLogger LOGGER = EELFManager.getInstance().getLogger(MoxyLoader.class); - private Map<String, Introspector> allObjs = null; - - /** - * Instantiates a new moxy loader. - * - * @param version the version - * @param llBuilder the ll builder - */ - protected MoxyLoader(Version version) { - super(version, ModelType.MOXY); - process(version); - } - - /** - * {@inheritDoc} - * @throws AAIUnknownObjectException - */ - @Override - public Introspector introspectorFromName(String name) throws AAIUnknownObjectException { - - return IntrospectorFactory.newInstance(ModelType.MOXY, objectFromName(name)); - } - - /** - * {@inheritDoc} - */ - @Override - public Object objectFromName(String name) throws AAIUnknownObjectException { - - if (name == null) { - throw new AAIUnknownObjectException("null name passed in"); - } - final String sanitizedName = NamingExceptions.getInstance().getObjectName(name); - final String upperCamel; - - //Contains any uppercase, then assume it's upper camel - if (name.matches(".*[A-Z].*")) { - upperCamel = sanitizedName; - } else { - upperCamel = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName); - } - - try { - final DynamicEntity result = jaxbContext.newDynamicEntity(upperCamel); - - if (result == null) throw new AAIUnknownObjectException("Unrecognized AAI object " + name); - - return result; - } catch (IllegalArgumentException e) { - //entity does not exist - throw new AAIUnknownObjectException("Unrecognized AAI object " + name, e); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected void process(Version version) { - ModelInjestor injestor = ModelInjestor.getInstance(); - jaxbContext = injestor.getContextForVersion(version); - - } - - /** - * {@inheritDoc} - */ - @Override - public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException { - try { - final Object clazz = objectFromName(type); - final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); - - if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) { - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - } - - final DynamicEntity entity = (DynamicEntity) unmarshaller.unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue(); - return IntrospectorFactory.newInstance(ModelType.MOXY, entity); - } catch (JAXBException e) { - AAIException ex = new AAIException("AAI_4007", e); - ErrorLogHelper.logException(ex); - throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), ex); - } catch (AAIUnknownObjectException e) { - throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e); - } - } - - @Override - public Map<String, Introspector> getAllObjects() { - if (this.allObjs != null) { - return allObjs; - } else { - ImmutableMap.Builder<String, Introspector> map = new ImmutableMap.Builder<String, Introspector>(); - Set<String> objs = objectsInVersion(); - for (String objName : objs) { - try { - Introspector introspector = this.introspectorFromName(objName); - map.put(introspector.getDbName(), introspector); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Unexpected AAIUnknownObjectException while running getAllObjects()", e); - } - } - allObjs = map.build(); - return allObjs; - } - } - - private Set<String> objectsInVersion() { - final Set<String> result = new HashSet<>(); - - try { - final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); - final String fileName = ModelInjestor.getInstance().getOXMFileName(getVersion()); - - docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - - final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); - final Document doc = docBuilder.parse(fileName); - final NodeList list = doc.getElementsByTagName("java-type"); - - for (int i = 0; i < list.getLength(); i++) { - result.add(list.item(i).getAttributes().getNamedItem("name").getNodeValue()); - } - } catch (ParserConfigurationException | SAXException | IOException e) { - LOGGER.warn("Exception while enumerating objects for API version " + getVersion() + " (returning partial results)", e); - } - - //result.remove("EdgePropNames"); - return result; - } - - public DynamicJAXBContext getJAXBContext() { - return this.jaxbContext; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyStrategy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyStrategy.java deleted file mode 100644 index b3cda8d3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/MoxyStrategy.java +++ /dev/null @@ -1,385 +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.introspection; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Joiner; -import org.eclipse.persistence.descriptors.ClassDescriptor; -import org.eclipse.persistence.dynamic.DynamicEntity; -import org.eclipse.persistence.dynamic.DynamicType; -import org.eclipse.persistence.exceptions.DynamicException; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; -import org.eclipse.persistence.mappings.DatabaseMapping; -import org.eclipse.persistence.oxm.XMLField; -import org.eclipse.persistence.oxm.mappings.XMLCompositeCollectionMapping; -import org.eclipse.persistence.oxm.mappings.XMLCompositeDirectCollectionMapping; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.springframework.web.util.UriUtils; - -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.util.*; -import java.util.Map.Entry; - -public class MoxyStrategy extends Introspector { - - private DynamicEntity internalObject = null; - private DynamicType internalType = null; - private DynamicJAXBContext jaxbContext = null; - private ClassDescriptor cd = null; - private Marshaller marshaller = null; - private Unmarshaller unmarshaller = null; - private Version version = null; - private Set<String> properties = null; - private Set<String> keys = null; - private Set<String> requiredProperties = null; - - private boolean isInitialized = false; - - protected MoxyStrategy(Object obj) { - super(obj); - /* must look up the correct jaxbcontext for this object */ - className = MoxyStrategy.class.getSimpleName(); - internalObject = (DynamicEntity)obj; - ModelInjestor injestor = ModelInjestor.getInstance(); - version = injestor.getVersionFromClassName(internalObject.getClass().getName()); - jaxbContext = injestor.getContextForVersion(version); - super.loader = LoaderFactory.createLoaderForVersion(getModelType(), version); - String simpleName = internalObject.getClass().getName(); - internalType = jaxbContext.getDynamicType(simpleName); - cd = internalType.getDescriptor(); - try { - marshaller = jaxbContext.createMarshaller(); - unmarshaller = jaxbContext.createUnmarshaller(); - } catch (JAXBException e) { - - } - - } - - private void init() { - isInitialized = true; - - Set<String> props = new LinkedHashSet<>(); - for (String s : internalType.getPropertiesNames()) { - props.add(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, s)); - - } - props = Collections.unmodifiableSet(props); - this.properties = props; - - Set<String> requiredProps = new LinkedHashSet<>(); - requiredProps = new LinkedHashSet<>(); - for (DatabaseMapping dm : cd.getMappings()) { - if (dm.getField() instanceof XMLField) { - XMLField x = (XMLField)dm.getField(); - if (x != null) { - if (x.isRequired()) { - requiredProps.add(this.removeXPathDescriptor(x.getName())); - } - } - } - } - requiredProps = Collections.unmodifiableSet(requiredProps); - this.requiredProperties = requiredProps; - - Set<String> keys = new LinkedHashSet<>(); - - for (String name : internalType.getDescriptor().getPrimaryKeyFieldNames()) { - keys.add(this.removeXPathDescriptor(name)); - } - keys = Collections.unmodifiableSet(keys); - this.keys = keys; - - - } - - @Override - public boolean hasProperty(String name) { - String convertedName = convertPropertyName(name); - - return internalType.containsProperty(convertedName); - } - - @Override - public Object get(String name) { - return internalObject.get(name); - } - - @Override - public void set(String name, Object obj) throws IllegalArgumentException { - - internalObject.set(name, obj); - } - - @Override - public Set<String> getProperties() { - - if(!isInitialized){ - init(); - } - - return this.properties; - - } - - @Override - public Set<String> getRequiredProperties() { - - if(!isInitialized){ - init(); - } - - return this.requiredProperties; - } - - @Override - public Set<String> getKeys() { - - if(!isInitialized){ - init(); - } - - return this.keys; - } - - @Override - public Map<PropertyMetadata, String> getPropertyMetadata(String prop) { - String propName = this.convertPropertyName(prop); - DatabaseMapping mapping = cd.getMappingForAttributeName(propName); - Map<PropertyMetadata, String> result = new HashMap<>(); - if (mapping != null) { - Set<Entry> entrySet = mapping.getProperties().entrySet(); - for (Entry<?,?> entry : entrySet) { - result.put( - PropertyMetadata.valueOf(CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, (String)entry.getKey())), (String)entry.getValue()); - } - } - - return result; - } - - @Override - public String getJavaClassName() { - return internalObject.getClass().getName(); - } - - - - @Override - public Class<?> getClass(String name) { - name = convertPropertyName(name); - Class<?> resultClass = null; - try { - if (internalType.getPropertyType(name) == null) { - if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) { - resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass(); - - } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) { - resultClass = cd.getMappingForAttributeName(name).getContainerPolicy().getContainerClass(); - } else { - ClassDescriptor referenceDiscriptor = cd.getMappingForAttributeName(name).getReferenceDescriptor(); - if (referenceDiscriptor != null) { - resultClass = referenceDiscriptor.getJavaClass(); - } else { - resultClass = Object.class; - } - } - } else { - resultClass = internalType.getPropertyType(name); - } - } catch (DynamicException e) { - //property doesn't exist - } - return resultClass; - } - - @Override - public Class<?> getGenericTypeClass(String name) { - name = convertPropertyName(name); - Class<?> resultClass = null; - if (internalType.getPropertyType(name) == null) { - if (cd.getMappingForAttributeName(name) instanceof XMLCompositeDirectCollectionMapping) { - resultClass = cd.getMappingForAttributeName(name).getFields().get(0).getType(); - - } else if (cd.getMappingForAttributeName(name) instanceof XMLCompositeCollectionMapping) { - resultClass = cd.getMappingForAttributeName(name).getReferenceDescriptor().getJavaClass(); - } - } - - return resultClass; - } - - @Override - public Object getUnderlyingObject() { - return this.internalObject; - } - - @Override - public String getChildName() { - - String className = internalObject.getClass().getSimpleName(); - String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - - if (this.isContainer()) { - lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName()); - } - - return lowerHyphen; - } - - @Override - public String getName() { - String className = internalObject.getClass().getSimpleName(); - String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - /* - if (this.isContainer()) { - lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().get(0)).getSimpleName()); - }*/ - - - return lowerHyphen; - } - - @Override - public String getObjectId() throws UnsupportedEncodingException { - String result = ""; - String container = this.getMetadata(ObjectMetadata.CONTAINER); - if (this.isContainer()) { - result += "/" + this.getName(); - } else { - - if (container != null) { - result += "/" + container; - } - result += "/" + this.getDbName() + "/" + this.findKey(); - - } - - return result; - } - - @Override - protected String findKey() throws UnsupportedEncodingException { - Set<String> keys = null; - keys = this.getKeys(); - List<String> results = new ArrayList<>(); - for (String key : keys) { - if (this.getType(key).toLowerCase().contains("long")) { - key = ((Long)this.getValue(key)).toString(); - } else { - key = (String)this.getValue(key); - } - key = UriUtils.encode(key, "UTF-8"); - - results.add(key); - } - - return Joiner.on("/").join(results); - } - - @Override - public String preProcessKey (String key) { - String result = ""; - //String trimmedRestURI = restURI.replaceAll("/[\\w\\-]+?/[\\w\\-]+?$", ""); - String[] split = key.split("/"); - int i = 0; - for (i = split.length-1; i >= 0; i--) { - - if (jaxbContext.getDynamicType(split[i]) != null) { - break; - - } - - } - result = Joiner.on("/").join(Arrays.copyOfRange(split, 0, i)); - - return result; - - } - - @Override - public String marshal(MarshallerProperties properties) { - StringWriter result = new StringWriter(); - try { - if (properties.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) { - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json"); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, properties.getIncludeRoot()); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, properties.getWrapperAsArrayName()); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_MARSHAL_EMPTY_COLLECTIONS, false); - } - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, properties.getFormatted()); - marshaller.marshal(this.internalObject, result); - } catch (JAXBException e) { - //e.printStackTrace(); - } - - return result.toString(); - } - - @Override - public Object clone() { - Object result = null; - try { - unmarshaller = jaxbContext.createUnmarshaller(); - - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - - result = unmarshaller.unmarshal(new StreamSource(new StringReader(this.marshal(true))), this.internalObject.getClass()).getValue(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - //e.printStackTrace(); - } - result = IntrospectorFactory.newInstance(getModelType(), result); - return result; - } - @Override - public ModelType getModelType() { - return ModelType.MOXY; - } - - private String removeXPathDescriptor(String name) { - - return name.replaceAll("/text\\(\\)", ""); - } - - @Override - public String getMetadata(ObjectMetadata name) { - - return (String)cd.getProperty(name.toString()); - } - - @Override - public Version getVersion() { - - return this.version; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoInjestor.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoInjestor.java deleted file mode 100644 index 3eea2420..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoInjestor.java +++ /dev/null @@ -1,67 +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.introspection; - -import org.eclipse.persistence.jaxb.JAXBContextFactory; -import org.openecomp.aai.db.props.AAIProperties; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class PojoInjestor { - - private String POJO_CLASSPATH = "org.openecomp.aai.domain.yang"; - private final Pattern classNamePattern = Pattern.compile("\\.(v\\d+)\\."); - - public PojoInjestor() { - } - - public JAXBContext getContextForVersion(Version v) { - JAXBContext context = null; - try { - if (!v.equals(AAIProperties.LATEST)) { - POJO_CLASSPATH += "." + v; - } - context = JAXBContextFactory.createContext(POJO_CLASSPATH, this.getClass().getClassLoader()); - } catch (JAXBException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return context; - } - public Version getVersion (String classname) { - Matcher m = classNamePattern.matcher(classname); - String version; - if (m.find()) { - version = m.group(1); - } else { - //only POJOs of old versions have the version number in their classnames - //so if we can't find a version, default to the latest - version = AAIProperties.LATEST.toString(); - } - - return Version.valueOf(version); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java deleted file mode 100644 index 927ac4bc..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoLoader.java +++ /dev/null @@ -1,137 +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.introspection; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import org.eclipse.persistence.jaxb.JAXBContextFactory; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.workarounds.NamingExceptions; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.util.Map; - -public class PojoLoader extends Loader { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(PojoLoader.class); - private static final String POJO_BASE_PACKAGE_NAME = "org.openecomp.aai.domain.yang"; - - protected JAXBContext context; - private final String pojoPackageName; - - protected PojoLoader(Version version) { - super(version, ModelType.POJO); - - if (!version.equals(AAIProperties.LATEST)) { - pojoPackageName = POJO_BASE_PACKAGE_NAME + "." + version; - } else { - pojoPackageName = POJO_BASE_PACKAGE_NAME; - } - - try { - context = JAXBContextFactory.createContext(pojoPackageName, this.getClass().getClassLoader()); - } catch (JAXBException e) { - LOGGER.error("JAXBException while instantiation contect for PojoLoader", e); - } - } - - @Override - public Introspector introspectorFromName(String name) throws AAIUnknownObjectException { - return IntrospectorFactory.newInstance(ModelType.POJO, objectFromName(name)); - } - - @Override - public Object objectFromName(String name) throws AAIUnknownObjectException { - - if (name == null) { - throw new AAIUnknownObjectException("null name passed in"); - } - final String sanitizedName = NamingExceptions.getInstance().getObjectName(name); - final String upperCamel; - - //Contains any uppercase, then assume it's upper camel - if (sanitizedName.matches(".*[A-Z].*")) { - upperCamel = sanitizedName; - } else { - upperCamel = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, sanitizedName); - } - - final String objectClassName; - - if (!upperCamel.contains(pojoPackageName)) { - objectClassName = pojoPackageName + "." + upperCamel; - } else { - objectClassName = upperCamel; - } - - try { - return Class.forName(objectClassName).newInstance(); - } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { - throw new AAIUnknownObjectException("Unrecognized AAI object " + name); - } - } - - @Override - protected void process(Version version) { - LOGGER.warn("PojoLoader.process(Version) has not been implemented"); - } - - @Override - public Introspector unmarshal(String type, String json, MediaType mediaType) throws AAIUnmarshallingException { - - try { - final Unmarshaller unmarshaller = context.createUnmarshaller(); - - if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) { - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - } - - final Object clazz = objectFromName(type); - final Object obj = unmarshaller.unmarshal(new StreamSource(new StringReader(json)), clazz.getClass()).getValue(); - - return IntrospectorFactory.newInstance(ModelType.POJO, obj); - } catch (JAXBException e) { - ErrorLogHelper.logError("AAI_4007", "Could not unmarshall: " + e.getMessage()); - throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage()); - } catch (AAIUnknownObjectException e) { - throw new AAIUnmarshallingException("Could not unmarshall: " + e.getMessage(), e); - } - } - - @Override - public Map<String, Introspector> getAllObjects() { - //TODO - return null; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoStrategy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PojoStrategy.java deleted file mode 100644 index 7f114bd3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PojoStrategy.java +++ /dev/null @@ -1,376 +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.introspection; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Joiner; -import com.google.common.collect.Multimap; -import org.eclipse.persistence.jaxb.UnmarshallerProperties; -import org.openecomp.aai.annotations.Metadata; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.restcore.MediaType; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.transform.stream.StreamSource; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.*; -import java.util.*; - -public class PojoStrategy extends Introspector { - - private Object internalObject = null; - private PojoInjestor injestor = null; - private Multimap<String, String> keyProps = null; - private Metadata classLevelMetadata = null; - private Version version; - private JAXBContext jaxbContext; - private Marshaller marshaller; - private Unmarshaller unmarshaller; - private Set<String> properties = null; - private Set<String> keys = null; - private Set<String> requiredProperties = null; - - private boolean isInitialized = false; - - protected PojoStrategy(Object obj) { - super(obj); - className = PojoStrategy.class.getSimpleName(); - this.internalObject = obj; - injestor = new PojoInjestor(); - classLevelMetadata = obj.getClass().getAnnotation(Metadata.class); - - version = injestor.getVersion(obj.getClass().getName()); - jaxbContext = injestor.getContextForVersion(version); - super.loader = LoaderFactory.createLoaderForVersion(getModelType(), version); - try { - marshaller = jaxbContext.createMarshaller(); - unmarshaller = jaxbContext.createUnmarshaller(); - } catch (JAXBException e) { - - } - - } - - private void init() { - - isInitialized = true; - - Set<String> properties = new LinkedHashSet<>(); - Set<String> keys = new LinkedHashSet<>(); - Set<String> required = new LinkedHashSet<>(); - - Field[] fields = this.internalObject.getClass().getDeclaredFields(); - - for (Field field : fields) { - if (!field.getName().equals("any")) { - properties.add(covertFieldToOutputFormat(field.getName())); - Metadata annotation = field.getAnnotation(Metadata.class); - XmlElement xmlAnnotation = field.getAnnotation(XmlElement.class); - if (annotation != null) { - if (annotation.isKey()) { - keys.add(covertFieldToOutputFormat(field.getName())); - } - } - if (xmlAnnotation != null) { - if (xmlAnnotation.required()) { - required.add(covertFieldToOutputFormat(field.getName())); - } - } - } - } - properties = Collections.unmodifiableSet(properties); - this.properties = properties; - - keys = Collections.unmodifiableSet(keys); - this.keys = keys; - - required = Collections.unmodifiableSet(required); - this.requiredProperties = required; - - } - private String covertFieldToOutputFormat(String propName) { - return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propName); - } - - @Override - public boolean hasProperty(String name) { - //TODO - return true; - } - - @Override - /** - * Gets the value of the property via reflection - */ - public Object get(String name) { - String getMethodName = "get" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name); - try { - return this.internalObject.getClass().getDeclaredMethod(getMethodName).invoke(this.internalObject); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - return null; - } - } - - @Override - public void set(String name, Object value) { - String setMethodName = "set" + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, name); - try { - this.internalObject.getClass().getDeclaredMethod(setMethodName, value.getClass()).invoke(this.internalObject, value); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { - ErrorLogHelper.logError("AAI_4017", "Error setting name/value pair on POJO: " + e.getMessage()); - } - } - - @Override - public Set<String> getProperties() { - - if(!isInitialized){ - this.init(); - } - return this.properties; - } - - - @Override - public Set<String> getRequiredProperties() { - - if(!isInitialized) { - this.init(); - } - return this.requiredProperties; - } - - @Override - public Set<String> getKeys() { - - if(!isInitialized){ - this.init(); - } - return this.keys; - } - - public Class<?> getClass(String name) { - - Field field = null; - try { - field = this.internalObject.getClass().getDeclaredField(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, name)); - } catch (NoSuchFieldException | SecurityException e) { - - return null; - } - - return field.getType(); - } - - public Class<?> getGenericTypeClass(String name) { - - try { - String getMethodName = "get" + CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name); - Method method = internalObject.getClass().getDeclaredMethod(getMethodName); - Type t = method.getGenericReturnType(); - if(t instanceof ParameterizedType) { - ParameterizedType pt = (ParameterizedType)t; - return ((Class<?>)pt.getActualTypeArguments()[0]); - } else { - return null; - } - - } catch (Exception e) { - return null; - } - } - - @Override - public String getJavaClassName() { - return internalObject.getClass().getName(); - } - - @Override - public Object getUnderlyingObject() { - return this.internalObject; - } - - @Override - public String getName() { - String className = internalObject.getClass().getSimpleName(); - - return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - } - - @Override - protected String findKey() { - Set<String> keys = null; - keys = this.getKeys(); - List<String> results = new ArrayList<>(); - for (String key : keys) { - if (this.getType(key).toLowerCase().contains("long")) { - key = ((Long)this.getValue(key)).toString(); - } else { - key = (String)this.getValue(key); - } - results.add(key); - } - - return Joiner.on("/").join(results); - } - - @Override - public String marshal(MarshallerProperties properties) { - StringWriter result = new StringWriter(); - try { - if (properties.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) { - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json"); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, properties.getIncludeRoot()); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, properties.getWrapperAsArrayName()); - } - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, properties.getFormatted()); - marshaller.marshal(this.internalObject, result); - } catch (JAXBException e) { - //e.printStackTrace(); - } - - return result.toString(); - } - - @Override - public Object clone() { - Object result = null; - try { - unmarshaller = jaxbContext.createUnmarshaller(); - - unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); - unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); - unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); - - result = unmarshaller.unmarshal(new StreamSource(new StringReader(this.marshal(true))), this.internalObject.getClass()).getValue(); - } catch (JAXBException e) { - // TODO Auto-generated catch block - //e.printStackTrace(); - } - result = IntrospectorFactory.newInstance(getModelType(), result); - return result; - } - - @Override - public String preProcessKey (String key) { - String result = ""; - //String trimmedRestURI = restURI.replaceAll("/[\\w\\-]+?/[\\w\\-]+?$", ""); - String[] split = key.split("/"); - int i = 0; - for (i = split.length-1; i >= 0; i--) { - - if (keyProps.containsKey(split[i])) { - break; - - } - - } - result = Joiner.on("/").join(Arrays.copyOfRange(split, 0, i)); - - return result; - - } - - @Override - public ModelType getModelType() { - return ModelType.POJO; - } - - @Override - public String getChildName() { - String className = internalObject.getClass().getSimpleName(); - String lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, className); - - if (this.isContainer()) { - lowerHyphen = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN,this.getGenericTypeClass(this.getProperties().iterator().next()).getSimpleName()); - } - - return lowerHyphen; - } - - @Override - public Map<PropertyMetadata, String> getPropertyMetadata(String prop) { - Field f; - Map<PropertyMetadata, String> result = new HashMap<>(); - try { - f = internalObject.getClass().getField(prop); - Metadata m = f.getAnnotation(Metadata.class); - if (m != null) { - Field[] fields = m.getClass().getFields(); - String fieldName; - for (Field field : fields) { - fieldName = field.getName(); - if (fieldName.equals("isAbstract")) { - fieldName = "abstract"; - } else if (fieldName.equals("extendsFrom")) { - fieldName = "extends"; - } - fieldName = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, fieldName); - result.put(PropertyMetadata.valueOf(fieldName), (String)field.get(m)); - } - } - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - // TODO Auto-generated catch block - } - - return result; - } - - @Override - public String getObjectId() { - // TODO Auto-generated method stub - return null; - } - - @Override - public String getMetadata(ObjectMetadata metadataName) { - String value = null; - String methodName; - if (ObjectMetadata.ABSTRACT.equals(metadataName)) { - methodName = "isAbstract"; - } else if (ObjectMetadata.EXTENDS.equals(metadataName)) { - methodName = "extendsFrom"; - } else { - methodName = metadataName.toString(); - } - - try { - value = (String)this.classLevelMetadata.getClass().getMethod(methodName).invoke(classLevelMetadata); - } catch (IllegalArgumentException | IllegalAccessException | SecurityException | InvocationTargetException | NoSuchMethodException e) { - //TODO - } - - return value; - } - - @Override - public Version getVersion() { - // TODO Auto-generated method stub - return null; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicate.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicate.java deleted file mode 100644 index 38bdf82c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicate.java +++ /dev/null @@ -1,27 +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.introspection; - -import java.util.function.BiPredicate; - -public interface PropertyPredicate<T, U> extends BiPredicate<T, U> { - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicates.java b/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicates.java deleted file mode 100644 index c7bbb0c0..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/PropertyPredicates.java +++ /dev/null @@ -1,77 +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.introspection; - -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.util.Map; -import java.util.Set; - -public final class PropertyPredicates { - - private PropertyPredicates() { - - } - - public static PropertyPredicate<Introspector, String> includeInTestGeneration() { - return (obj, prop) -> { - final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop); - if (map.containsKey(PropertyMetadata.VISIBILITY)) { - return !(Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))) - || Visibility.deployment.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY)))); - } - if (map.containsKey("dataLocation")) { - return false; - } - return true; - }; - } - - public static PropertyPredicate<Introspector, String> isVisible() { - return (obj, prop) -> { - final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop); - if (map.containsKey(PropertyMetadata.VISIBILITY)) { - return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))); - } - return true; - }; - } - - public static PropertyPredicate<Introspector, String> includeInExamples() { - return (obj, prop) -> { - final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop); - if (map.containsKey(PropertyMetadata.VISIBILITY)) { - return !Visibility.internal.equals(Visibility.valueOf(map.get(PropertyMetadata.VISIBILITY))); - } - if (map.containsKey("dataLocation")) { - return false; - } - return true; - }; - } - - public static PropertyPredicate<Introspector, String> isIndexed() { - return (obj, prop) -> { - Set<String> indexed = obj.getIndexedProperties(); - return indexed.contains(prop); - }; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Version.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Version.java deleted file mode 100644 index 9e1fab2a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Version.java +++ /dev/null @@ -1,36 +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.introspection; - -public enum Version { - v8, - v9, - v10, - v11; - - public static boolean isLatest(Version v) { - return (Version.v11.equals(v)); //TODO update when we increment the version, or find a better way of doing this - } - - public static Version getLatest(){ - return Version.v11; //TODO update when we increment the version, or find a better way of doing this - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Visibility.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Visibility.java deleted file mode 100644 index 4c467a50..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Visibility.java +++ /dev/null @@ -1,29 +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.introspection; - -public enum Visibility { - - internal, - external, - deployment, - all -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/Wanderer.java b/aai-core/src/main/java/org/openecomp/aai/introspection/Wanderer.java deleted file mode 100644 index 5429d999..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/Wanderer.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.openecomp.aai - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.aai.introspection; - -import org.openecomp.aai.exceptions.AAIException; - -import java.util.List; - -public interface Wanderer { - - /** - * Process primitive. - * - * @param propName the prop name - * @param obj the obj - */ - public void processPrimitive(String propName, Introspector obj); - - /** - * Process primitive list. - * - * @param propName the prop name - * @param obj the obj - */ - public void processPrimitiveList(String propName, Introspector obj); - - /** - * Process complex obj. - * - * @param obj the obj - * @throws AAIException - */ - public void processComplexObj(Introspector obj) throws AAIException; - - /** - * Modify complex list. - * - * @param list the list - * @param listReference TODO - * @param parent the parent - * @param child the child - */ - public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent, Introspector child); - - /** - * Creates the complex obj if null. - * - * @return true, if successful - */ - public default boolean createComplexObjIfNull() { - return false; - } - - /** - * Creates the complex list size. - * - * @param parent the parent - * @param child the child - * @return the int - */ - public default int createComplexListSize(Introspector parent, Introspector child) { - return 0; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnknownObjectException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnknownObjectException.java deleted file mode 100644 index e8ed4e8a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnknownObjectException.java +++ /dev/null @@ -1,42 +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.introspection.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIUnknownObjectException extends AAIException { - - private static final long serialVersionUID = -504200228742133774L; - - public AAIUnknownObjectException() {} - - public AAIUnknownObjectException(String message) { - super("AAI_3000", message); - } - - public AAIUnknownObjectException(Throwable cause) { - super("AAI_3000", cause); - } - - public AAIUnknownObjectException(String message, Throwable cause) { - super("AAI_3000", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnmarshallingException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnmarshallingException.java deleted file mode 100644 index bbbcdd67..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/exceptions/AAIUnmarshallingException.java +++ /dev/null @@ -1,42 +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.introspection.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIUnmarshallingException extends AAIException { - - private static final long serialVersionUID = -5615651557821878103L; - - public AAIUnmarshallingException() {} - - public AAIUnmarshallingException(String message) { - super("AAI_3000", message); - } - - public AAIUnmarshallingException(Throwable cause) { - super("AAI_3000",cause); - } - - public AAIUnmarshallingException(String message, Throwable cause) { - super("AAI_3000", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/generator/CreateExample.java b/aai-core/src/main/java/org/openecomp/aai/introspection/generator/CreateExample.java deleted file mode 100644 index 1b3444fd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/generator/CreateExample.java +++ /dev/null @@ -1,166 +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.introspection.generator; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; - -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.List; - -public class CreateExample implements Wanderer { - - private SecureRandom rand = new SecureRandom(); - private final long range = 100000000L; - private Loader loader = null; - private Introspector result = null; - private String objectName = null; - private List<String> blacklist = null; - - /** - * Instantiates a new creates the example. - * - * @param loader the loader - * @param objectName the object name - */ - public CreateExample(Loader loader, String objectName) { - - this.loader = loader; - this.objectName = objectName; - this.blacklist = new ArrayList<>(); - - } - - /** - * Gets the example object. - * - * @return the example object - * @throws AAIException - */ - public Introspector getExampleObject() throws AAIException { - result = loader.introspectorFromName(objectName); - blacklist = new ArrayList<>(); - blacklist.add("any"); - blacklist.add("relationship-list"); - if (!result.isContainer()) { - blacklist.add("resource-version"); - } - IntrospectorWalker walker = new IntrospectorWalker(this, PropertyPredicates.includeInExamples()); - - walker.preventCycles(true); - walker.setBlacklist(blacklist); - walker.walk(result); - //this.getExampleObject(result); - - return result; - } - - /** - * Gets the value. - * - * @param property the property - * @param type the type - * @param suffix the suffix - * @return the value - */ - private Object getValue(String property, String type, String suffix) { - long randLong = (long)(rand.nextDouble()*range); - Integer randInt = rand.nextInt(100000); - Integer randShrt = rand.nextInt(20000); - short randShort = randShrt.shortValue(); - - Object newObj = null; - if (type.contains("java.lang.String")) { - newObj = "example-" + property + "-val-" + randInt + suffix; - } else if ( type.toLowerCase().equals("long") ||type.contains("java.lang.Long")) { - newObj = randLong; - } else if(type.toLowerCase().equals("boolean") || type.contains("java.lang.Boolean")){ - newObj = Boolean.TRUE; - } else if ( type.toLowerCase().equals("int") || type.contains("java.lang.Integer")){ - newObj = randInt; - } else if ( type.toLowerCase().equals("short") || type.contains("java.lang.Short")){ - newObj = randShort; - } - - return newObj; - } - - /** - * {@inheritDoc} - */ - @Override - public void processPrimitive(String propName, Introspector obj) { - String propType = obj.getType(propName); - - Object val = this.getValue(propName, propType, ""); - obj.setValue(propName, val); - } - - /** - * {@inheritDoc} - */ - @Override - public void processPrimitiveList(String propName, Introspector obj) { - int listSize = 2; - String propType = ""; - List<Object> list = new ArrayList<>(); - for (int i = 0; i < listSize; i++) { - propType = obj.getGenericType(propName); - Object val = this.getValue(propName, propType, "-" + (i + 1)); - list.add(val); - } - obj.setValue(propName, list); - } - - /** - * {@inheritDoc} - */ - @Override - public void processComplexObj(Introspector obj) { - - } - - /** - * {@inheritDoc} - */ - @Override - public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent, Introspector child) { - // TODO Auto-generated method stub - - } - - /** - * {@inheritDoc} - */ - @Override - public boolean createComplexObjIfNull() { - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public int createComplexListSize(Introspector parent, Introspector child) { - return 1; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataCopy.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataCopy.java deleted file mode 100644 index 53c85013..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataCopy.java +++ /dev/null @@ -1,89 +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.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMultiplePropertiesException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collections; -import java.util.List; -import java.util.Map.Entry; -import java.util.Objects; -import java.util.Optional; - - -public class DataCopy extends SideEffect { - - - public DataCopy(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) { - super(obj, self, dbEngine, serializer); - } - - @Override - protected void processURI(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException, UnsupportedEncodingException, AAIException { - if (completeUri.isPresent()) { - URI uri = new URI(completeUri.get()); - MultivaluedMap<String, String> map = URITools.getQueryMap(uri); - QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); - List<Vertex> results = uriQuery.getQueryBuilder().toList(); - Introspector resultObj = this.latestLoader.introspectorFromName(uriQuery.getResultType()); - if (results.size() == 1) { - serializer.dbToObject(Collections.singletonList(results.get(0)), resultObj, 0, true, "false"); - try { - obj.setValue(entry.getKey(), Objects.requireNonNull(resultObj.getValue(uri.getFragment()), uri.getFragment() + " was null")); - } catch (NullPointerException e) { - throw new AAIMissingRequiredPropertyException("property " + uri.getFragment() + " not found at " + uri); - } - } else { - if (results.isEmpty()) { - throw new AAIException("AAI_6114", "object located at " + uri + " not found"); - } else if (results.size() > 1) { - throw new AAIMultiplePropertiesException("multiple values of " + entry.getKey() + " found when searching " + uri); - } - } - } else { - //skip processing because no required properties were specified - } - } - - @Override - protected PropertyMetadata getPropertyMetadata() { - return PropertyMetadata.DATA_COPY; - } - - @Override - protected boolean replaceWithWildcard() { - return false; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkReader.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkReader.java deleted file mode 100644 index 89b03eab..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkReader.java +++ /dev/null @@ -1,97 +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.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.regex.Matcher; - -public class DataLinkReader extends SideEffect { - - public DataLinkReader(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) { - super(obj, self, dbEngine, serializer); - } - - @Override - protected boolean replaceWithWildcard() { - return true; - } - - @Override - protected PropertyMetadata getPropertyMetadata() { - return PropertyMetadata.DATA_LINK; - } - - @Override - protected void processURI(Optional<String> completeUri, Entry<String, String> entry) - throws URISyntaxException, UnsupportedEncodingException, AAIException { - - if (completeUri.isPresent()) { - URI uri = new URI(completeUri.get()); - MultivaluedMap<String, String> map = URITools.getQueryMap(uri); - QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); - List<Vertex> results = uriQuery.getQueryBuilder().getVerticesByProperty(AAIProperties.LINKED, true).toList(); - if (results.size() == 1) { - if (results.get(0).<Boolean>property(AAIProperties.LINKED).orElse(false) && obj.getValue(entry.getKey()) == null) { - obj.setValue(entry.getKey(), results.get(0).property(entry.getKey()).orElse(null)); - } - } else { - //log something about not being able to return any values because there was more than one - } - } - } - - /** - * always fuzzy search on reads - */ - @Override - protected Map<String, String> findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { - - final Map<String, String> result = new HashMap<>(); - Matcher m = template.matcher(uriString); - while (m.find()) { - String propName = m.group(1); - if (replaceWithWildcard()) { - result.put(propName, "*"); - } - } - return result; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkWriter.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkWriter.java deleted file mode 100644 index 6e93098d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/DataLinkWriter.java +++ /dev/null @@ -1,109 +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.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMultiplePropertiesException; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.uri.URIToObject; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Map.Entry; -import java.util.Optional; - -public class DataLinkWriter extends SideEffect { - - public DataLinkWriter(Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) { - super(obj, self, dbEngine, serializer); - } - - @Override - protected PropertyMetadata getPropertyMetadata() { - return PropertyMetadata.DATA_LINK; - } - - @Override - protected void processURI(Optional<String> completeUri, Entry<String, String> entry) - throws URISyntaxException, UnsupportedEncodingException, AAIException { - if (completeUri.isPresent()) { - URI uri = new URI(completeUri.get()); - MultivaluedMap<String, String> map = URITools.getQueryMap(uri); - QueryParser uriQuery = dbEngine.getQueryBuilder(this.latestLoader).createQueryFromURI(uri, map); - List<Vertex> results = uriQuery.getQueryBuilder().toList(); - if (results.size() == 1) { - if (results.get(0).<Boolean>property(AAIProperties.LINKED).orElse(false) && obj.getValue(entry.getKey()) == null) { - //delete vertex because property was removed - serializer.delete(results.get(0), "", false); - } else { - //link vertex that already exists - this.addLinkedProperty(results.get(0)); - } - } else { - if (results.isEmpty()) { - //locate previously linked vertex - List<Vertex> linkedVertices = uriQuery.getQueryBuilder().getContainerQuery().getVerticesByProperty(AAIProperties.LINKED, true).toList(); - if (!linkedVertices.isEmpty()) { - if (linkedVertices.size() > 1) { - throw new AAIMultiplePropertiesException("multiple vertices found for single cardinality propery found when searching " + uri); - } else { - //found one, remove the linked property because it didn't match the uri - linkedVertices.get(0).property(AAIProperties.LINKED).remove(); - } - } - if (obj.getValue(entry.getKey()) != null) { - //add new vertex to database if we have values - URIToObject parser = new URIToObject(this.latestLoader, uri); - Introspector resultObj = parser.getEntity(); - Vertex newV = serializer.createNewVertex(resultObj); - serializer.serializeToDb(resultObj, newV, uriQuery, completeUri.get(), this.latestLoader.getVersion().toString()); - this.addLinkedProperty(newV); - } - } else if (results.size() > 1) { - throw new AAIMultiplePropertiesException("multiple values of " + entry.getKey() + " found when searching " + uri); - } - } - } else { - //skip processing because no required properties were specified - } - } - - @Override - protected boolean replaceWithWildcard() { - return true; - } - - private void addLinkedProperty(Vertex v) { - v.property(AAIProperties.LINKED, true); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffect.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffect.java deleted file mode 100644 index 95da72f3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffect.java +++ /dev/null @@ -1,128 +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.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.UnsupportedEncodingException; -import java.net.URISyntaxException; -import java.util.*; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public abstract class SideEffect { - - protected static final Pattern template = Pattern.compile("\\{(.*?)\\}"); - protected final Introspector obj; - protected final TransactionalGraphEngine dbEngine; - protected final DBSerializer serializer; - protected final Loader latestLoader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); - protected final Vertex self; - public SideEffect (Introspector obj, Vertex self, TransactionalGraphEngine dbEngine, DBSerializer serializer) { - this.obj = obj; - this.dbEngine = dbEngine; - this.serializer = serializer; - this.self = self; - } - - protected void execute() throws UnsupportedEncodingException, URISyntaxException, AAIException { - final Map<String, String> properties = this.findPopertiesWithMetadata(obj, this.getPropertyMetadata()); - for (Entry<String, String> entry : properties.entrySet()) { - Optional<String> populatedUri = this.replaceTemplates(obj, entry.getValue()); - Optional<String> completeUri = this.resolveRelativePath(populatedUri); - this.processURI(completeUri, entry); - } - } - - protected Map<String, String> findPopertiesWithMetadata(Introspector obj, PropertyMetadata metadata) { - final Map<String, String> result = new HashMap<>(); - for (String prop : obj.getProperties()) { - final Map<PropertyMetadata, String> map = obj.getPropertyMetadata(prop); - if (map.containsKey(metadata)) { - result.put(prop, map.get(metadata)); - } - } - return result; - } - - protected Map<String, String> findProperties(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { - - final Map<String, String> result = new HashMap<>(); - final Set<String> missing = new LinkedHashSet<>(); - Matcher m = template.matcher(uriString); - int properties = 0; - while (m.find()) { - String propName = m.group(1); - String value = obj.getValue(propName); - properties++; - if (value != null) { - result.put(propName, value); - } else { - if (replaceWithWildcard()) { - result.put(propName, "*"); - } - missing.add(propName); - } - } - - if (!missing.isEmpty() && (properties != missing.size())) { - throw new AAIMissingRequiredPropertyException("Cannot complete " + this.getPropertyMetadata().toString() + " uri. Missing properties " + missing); - } - return result; - } - - private Optional<String> replaceTemplates(Introspector obj, String uriString) throws AAIMissingRequiredPropertyException { - String result = uriString; - final Map<String, String> propMap = this.findProperties(obj, uriString); - if (propMap.isEmpty()) { - return Optional.empty(); - } - for (Entry<String, String> entry : propMap.entrySet()) { - result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue()); - } - //drop out wildcards if they exist - result = result.replaceFirst("/[^/]+?(?:/\\*)+", ""); - return Optional.of(result); - } - - private Optional<String> resolveRelativePath(Optional<String> populatedUri) throws UnsupportedEncodingException { - if (!populatedUri.isPresent()) { - return Optional.empty(); - } else { - return Optional.of(populatedUri.get().replaceFirst("\\./", this.serializer.getURIForVertex(self) + "/")); - } - } - - protected abstract boolean replaceWithWildcard(); - protected abstract PropertyMetadata getPropertyMetadata(); - protected abstract void processURI(Optional<String> completeUri, Entry<String, String> entry) throws URISyntaxException, UnsupportedEncodingException, AAIException; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunner.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunner.java deleted file mode 100644 index 3b33be1f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunner.java +++ /dev/null @@ -1,99 +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.introspection.sideeffect; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.URISyntaxException; -import java.util.LinkedHashSet; -import java.util.Set; - -public class SideEffectRunner { - - protected final TransactionalGraphEngine dbEngine; - protected final DBSerializer serializer; - protected final Set<Class<? extends SideEffect>> sideEffects; - protected SideEffectRunner(Builder builder) { - this.dbEngine = builder.getDbEngine(); - this.serializer = builder.getSerializer(); - this.sideEffects = builder.getSideEffects(); - } - - public void execute(Introspector obj, Vertex self) throws AAIException { - - for (Class<? extends SideEffect> se : sideEffects) { - try { - se.getConstructor(Introspector.class, Vertex.class, TransactionalGraphEngine.class, DBSerializer.class) - .newInstance(obj, self, dbEngine, serializer).execute(); - } catch (UnsupportedEncodingException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException - | URISyntaxException e) { - throw new AAIException("strange exception", e); - } - } - } - - public static class Builder { - - private final TransactionalGraphEngine dbEngine; - private final DBSerializer serializer; - private final Set<Class<? extends SideEffect>> sideEffects; - - public Builder(final TransactionalGraphEngine dbEngine, final DBSerializer serializer) { - this.dbEngine = dbEngine; - this.serializer = serializer; - this.sideEffects = new LinkedHashSet<>(); - } - - public Builder addSideEffect(Class<? extends SideEffect> se) { - sideEffects.add(se); - return this; - } - - public Builder addSideEffects(Class<? extends SideEffect>... sideEffects) { - for (Class<? extends SideEffect> se : sideEffects) { - this.addSideEffect(se); - } - return this; - } - - public SideEffectRunner build() { - return new SideEffectRunner(this); - } - protected TransactionalGraphEngine getDbEngine() { - return dbEngine; - } - - protected DBSerializer getSerializer() { - return serializer; - } - - protected Set<Class<? extends SideEffect>> getSideEffects() { - return sideEffects; - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunnerHelper.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunnerHelper.java deleted file mode 100644 index d94cd4a1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/SideEffectRunnerHelper.java +++ /dev/null @@ -1,85 +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.introspection.sideeffect; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Wanderer; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Set; - -class SideEffectRunnerHelper implements Wanderer { - - - protected final TransactionalGraphEngine dbEngine; - protected final DBSerializer serializer; - protected final Set<Class<? extends SideEffect>> sideEffects; - protected SideEffectRunnerHelper(final TransactionalGraphEngine dbEngine, final DBSerializer serializer, final Set<Class<? extends SideEffect>> sideEffects) { - this.dbEngine = dbEngine; - this.serializer = serializer; - this.sideEffects = sideEffects; - } - - private void runSideEffects(Introspector obj) throws AAIException { - for (Class<? extends SideEffect> se : sideEffects) { - try { - se.getConstructor(Introspector.class, TransactionalGraphEngine.class, DBSerializer.class) - .newInstance(obj, dbEngine, serializer).execute(); - } catch (UnsupportedEncodingException | InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException - | URISyntaxException e) { - throw new AAIException("strange exception", e); - } - } - } - @Override - public void processPrimitive(String propName, Introspector obj) { - // TODO Auto-generated method stub - - } - - @Override - public void processPrimitiveList(String propName, Introspector obj) { - // TODO Auto-generated method stub - - } - - @Override - public void processComplexObj(Introspector obj) throws AAIException { - - runSideEffects(obj); - - } - - @Override - public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent, - Introspector child) { - // TODO Auto-generated method stub - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java deleted file mode 100644 index aca299c7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMissingRequiredPropertyException.java +++ /dev/null @@ -1,45 +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.introspection.sideeffect.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIMissingRequiredPropertyException extends AAIException { - - - private static final long serialVersionUID = -8907079650472014019L; - - public AAIMissingRequiredPropertyException() {} - - public AAIMissingRequiredPropertyException(String message) { - super("AAI_5107", message); - } - - public AAIMissingRequiredPropertyException(Throwable cause) { - super("AAI_5107",cause); - } - - public AAIMissingRequiredPropertyException(String message, Throwable cause) { - super("AAI_5107", cause, message); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java b/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java deleted file mode 100644 index 91bb8168..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/sideeffect/exceptions/AAIMultiplePropertiesException.java +++ /dev/null @@ -1,44 +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.introspection.sideeffect.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIMultiplePropertiesException extends AAIException { - - private static final long serialVersionUID = 2098371383166008345L; - - public AAIMultiplePropertiesException() {} - - public AAIMultiplePropertiesException(String message) { - super("AAI_6136", message); - } - - public AAIMultiplePropertiesException(Throwable cause) { - super("AAI_6136",cause); - } - - public AAIMultiplePropertiesException(String message, Throwable cause) { - super("AAI_6136", cause, message); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/CreateUUID.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/CreateUUID.java deleted file mode 100644 index f88a099c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/CreateUUID.java +++ /dev/null @@ -1,49 +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.introspection.tools; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.util.Map; -import java.util.UUID; - -public class CreateUUID implements IssueResolver { - - /** - * {@inheritDoc} - */ - @Override - public boolean resolveIssue(Issue issue) { - - Introspector obj = issue.getIntrospector(); - if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) { - Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(issue.getPropName()); - if (metadata.containsKey(PropertyMetadata.AUTO_GENERATE_UUID) && metadata.get(PropertyMetadata.AUTO_GENERATE_UUID).equals("true")) { - obj.setValue(issue.getPropName(), UUID.randomUUID().toString()); - return true; - } - } - - return false; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/DefaultFields.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/DefaultFields.java deleted file mode 100644 index c242d983..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/DefaultFields.java +++ /dev/null @@ -1,48 +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.introspection.tools; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.util.Map; - -public class DefaultFields implements IssueResolver { - - /** - * {@inheritDoc} - */ - @Override - public boolean resolveIssue(Issue issue) { - - Introspector obj = issue.getIntrospector(); - if (issue.getType().equals(IssueType.MISSING_REQUIRED_PROP)) { - Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(issue.getPropName()); - if (metadata.containsKey(PropertyMetadata.DEFAULT_VALUE)) { - obj.setValue(issue.getPropName(), metadata.get(PropertyMetadata.DEFAULT_VALUE)); - return true; - } - } - - return false; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/InjectKeysFromURI.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/InjectKeysFromURI.java deleted file mode 100644 index d9aea008..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/InjectKeysFromURI.java +++ /dev/null @@ -1,69 +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.introspection.tools; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.uri.URIToObject; - -import java.net.URI; - -public class InjectKeysFromURI implements IssueResolver { - - private URI uri = null; - private Loader loader = null; - - /** - * Instantiates a new inject keys from URI. - * - * @param loader the loader - * @param uri the uri - */ - public InjectKeysFromURI(Loader loader, URI uri) { - this.loader = loader; - this.uri = uri; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean resolveIssue(Issue issue) { - boolean result = false; - Introspector obj = issue.getIntrospector(); - if (issue.getType().equals(IssueType.MISSING_KEY_PROP)) { - try { - URIToObject toObject = new URIToObject(loader, uri); - Introspector minimumObj = toObject.getEntity(); - if (toObject.getEntityName().equals(obj.getDbName())) { - obj.setValue(issue.getPropName(), minimumObj.getValue(issue.getPropName())); - result = true; - } - } catch (Exception e) { - //log something probably - result = false; - } - } - - return result; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IntrospectorValidator.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IntrospectorValidator.java deleted file mode 100644 index cf77a3be..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IntrospectorValidator.java +++ /dev/null @@ -1,318 +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.introspection.tools; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.IntrospectorWalker; -import org.openecomp.aai.introspection.Visibility; -import org.openecomp.aai.introspection.Wanderer; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -import java.util.*; - -public class IntrospectorValidator implements Wanderer { - - - private List<Issue> issues = null; - private List<IssueResolver> issueResolvers = null; - private boolean validateRequired = true; - private final int maximumDepth; - private int currentDepth = 0; - - private final Set<String> relationshipChain; - /** - * Instantiates a new introspector validator. - * - * @param builder the builder - */ - private IntrospectorValidator(Builder builder) { - this.validateRequired = builder.getValidateRequired(); - this.issueResolvers = builder.getResolvers(); - this.maximumDepth = builder.getMaximumDepth(); - issues = new ArrayList<>(); - - relationshipChain = new HashSet<>(); - - relationshipChain.add("relationship-list"); - relationshipChain.add("relationship"); - relationshipChain.add("relationship-data"); - relationshipChain.add("related-to-property"); - - - } - - /** - * Validate. - * - * @param obj the obj - * @return true, if successful - * @throws AAIException - */ - public boolean validate(Introspector obj) throws AAIException { - IntrospectorWalker walker = new IntrospectorWalker(this); - this.currentDepth = 0; - walker.walk(obj); - - for (Issue m : issues) { - if (!m.getSeverity().equals(Severity.WARNING)) { - return false; - } - } - - return true; - } - - /** - * Gets the issues. - * - * @return the issues - */ - public List<Issue> getIssues() { - return this.issues; - } - - /** - * Sets the issue resolvers. - * - * @param resolvers the new issue resolvers - */ - public void setIssueResolvers(List<IssueResolver> resolvers) { - issueResolvers = new ArrayList<>(); - for (IssueResolver resolver : resolvers) { - issueResolvers.add(resolver); - } - } - - /** - * Resolve issues. - * - * @return true, if successful - */ - public boolean resolveIssues() { - boolean result = true; - for (Issue issue : issues) { - for (IssueResolver resolver : issueResolvers) { - if (resolver.resolveIssue(issue)) { - issue.setResolved(true); - } - } - if (!issue.isResolved()) { - result = false; - } - } - - return result; - } - - /** - * {@inheritDoc} - */ - @Override - public void processComplexObj(Introspector obj) { - - if (this.currentDepth > this.maximumDepth && !relationshipChain.contains(obj.getDbName())) { - Issue message = - this.buildMessage(Severity.CRITICAL, IssueType.EXCEEDED_ALLOWED_DEPTH, "Maximum allowed depth of this object has been exceeded on: " + obj.getDbName()); - message.setIntrospector(obj); - issues.add(message); - } - Set<String> requiredProps = obj.getRequiredProperties(); - Set<String> keys = obj.getKeys(); - Set<String> props = obj.getProperties(); - - for (String prop : props) { - Object value = obj.getValue(prop); - if (keys.contains(prop)) { - if (value == null) { - Issue message = - this.buildMessage(Severity.CRITICAL, IssueType.MISSING_KEY_PROP, "Missing key property: " + prop); - message.setIntrospector(obj); - message.setPropName(prop); - issues.add(message); - } - } else if (requiredProps.contains(prop)) { - if (value == null && validateRequired) { - Issue message = - this.buildMessage(Severity.CRITICAL, IssueType.MISSING_REQUIRED_PROP, "Missing required property: " + prop); - message.setIntrospector(obj); - message.setPropName(prop); - issues.add(message); - } - } - - final Optional<String> visibility = obj.getPropertyMetadata(prop, PropertyMetadata.VISIBILITY); - if(visibility.isPresent() && Visibility.internal.equals(Visibility.valueOf(visibility.get())) && obj.getValue(prop) != null) { - Issue message = - this.buildMessage(Severity.ERROR, IssueType.PROPERTY_NOT_VISIBLE, "client attemptted to set property not visible: " + prop); - message.setIntrospector(obj); - message.setPropName(prop); - issues.add(message); - - } - final Optional<String> requires = obj.getPropertyMetadata(prop, PropertyMetadata.REQUIRES); - if (requires.isPresent() && (obj.getValue(prop) != null && obj.getValue(requires.get()) == null)) { - Issue message = - this.buildMessage(Severity.CRITICAL, IssueType.DEPENDENT_PROP_NOT_FOUND, prop + " requires " + requires.get() + " to also be popluated."); - message.setIntrospector(obj); - message.setPropName(prop); - issues.add(message); - } - } - - if (!relationshipChain.contains(obj.getDbName())) { - this.currentDepth++; - } - - } - - /** - * {@inheritDoc} - */ - @Override - public void processPrimitive(String propName, Introspector obj) { - //NO OP - } - - /** - * {@inheritDoc} - */ - @Override - public void processPrimitiveList(String propName, Introspector obj) { - //NO OP - } - - /** - * {@inheritDoc} - */ - @Override - public void modifyComplexList(List<Introspector> list, List<Object> listReference, Introspector parent, Introspector child) { - //NO OP - } - - - /** - * Builds the message. - * - * @param severity the severity - * @param error the error - * @param detail the detail - * @return the issue - */ - private Issue buildMessage(Severity severity, IssueType error, String detail) { - Issue message = new Issue(); - message.setSeverity(severity); - message.setType(error); - message.setDetail(detail); - - return message; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean createComplexObjIfNull() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public int createComplexListSize(Introspector parent, Introspector child) { - return 0; - } - - public static class Builder { - - private boolean validateRequired = true; - private List<IssueResolver> issueResolvers = null; - private int maximumDepth = AAIProperties.MAXIMUM_DEPTH; - /** - * Instantiates a new builder. - * - * @param llBuilder the ll builder - */ - public Builder() { - issueResolvers = new ArrayList<IssueResolver>(); - } - - /** - * Validate required. - * - * @param validateRequired the validate required - * @return the builder - */ - public Builder validateRequired(boolean validateRequired) { - this.validateRequired = validateRequired; - return this; - } - - public Builder restrictDepth(int depth) { - this.maximumDepth = depth; - return this; - } - /** - * Adds the resolver. - * - * @param resolver the resolver - * @return the builder - */ - public Builder addResolver(IssueResolver resolver) { - issueResolvers.add(resolver); - return this; - } - - /** - * Builds the. - * - * @return the introspector validator - */ - public IntrospectorValidator build() { - return new IntrospectorValidator(this); - } - - /** - * Gets the validate required. - * - * @return the validate required - */ - public boolean getValidateRequired() { - return this.validateRequired; - } - - /** - * Gets the resolvers. - * - * @return the resolvers - */ - public List<IssueResolver> getResolvers() { - return this.issueResolvers; - } - - public int getMaximumDepth() { - return this.maximumDepth; - } - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Issue.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Issue.java deleted file mode 100644 index 173d1f77..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Issue.java +++ /dev/null @@ -1,144 +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.introspection.tools; - -import org.openecomp.aai.introspection.Introspector; - -public class Issue { - - private Severity severity; - private IssueType error; - private String detail; - private Introspector obj; - private String propName; - private boolean resolved = false; - - /** - * Sets the severity. - * - * @param severity the new severity - */ - public void setSeverity(Severity severity) { - - this.severity = severity; - } - - /** - * Sets the error. - * - * @param error the new error - */ - public void setType(IssueType error) { - this.error = error; - } - - /** - * Sets the detail. - * - * @param detail the new detail - */ - public void setDetail(String detail) { - this.detail = detail; - } - - /** - * Gets the severity. - * - * @return the severity - */ - public Object getSeverity() { - return this.severity; - } - - /** - * Sets the introspector. - * - * @param obj the new introspector - */ - public void setIntrospector(Introspector obj) { - this.obj = obj; - } - - /** - * Gets the introspector. - * - * @return the introspector - */ - public Introspector getIntrospector() { - return this.obj; - } - - /** - * Gets the detail. - * - * @return the detail - */ - public String getDetail() { - return this.detail; - } - - /** - * Gets the error. - * - * @return the error - */ - public IssueType getType() { - return this.error; - } - - /** - * Sets the prop name. - * - * @param prop the new prop name - */ - public void setPropName(String prop) { - this.propName= prop; - } - - /** - * Gets the prop name. - * - * @return the prop name - */ - public String getPropName() { - return this.propName; - } - - /** - * Checks if is resolved. - * - * @return true, if is resolved - */ - public boolean isResolved() { - return resolved; - } - - /** - * Sets the resolved. - * - * @param resolved the new resolved - */ - public void setResolved(boolean resolved) { - this.resolved = resolved; - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueResolver.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueResolver.java deleted file mode 100644 index e62e9b72..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueResolver.java +++ /dev/null @@ -1,33 +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.introspection.tools; - -public interface IssueResolver { - - - /** - * Resolve issue. - * - * @param issue the issue - * @return true, if successful - */ - public boolean resolveIssue(Issue issue); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueType.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueType.java deleted file mode 100644 index 5606926c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/IssueType.java +++ /dev/null @@ -1,25 +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.introspection.tools; - -public enum IssueType { - MISSING_REQUIRED_PROP, MISSING_KEY_PROP, EXCEEDED_ALLOWED_DEPTH, PROPERTY_NOT_VISIBLE, DEPENDENT_PROP_NOT_FOUND -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/RemoveNonVisibleProperty.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/RemoveNonVisibleProperty.java deleted file mode 100644 index 4de0fa60..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/RemoveNonVisibleProperty.java +++ /dev/null @@ -1,36 +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.introspection.tools; - -public class RemoveNonVisibleProperty implements IssueResolver { - - @Override - public boolean resolveIssue(Issue issue) { - - if (IssueType.PROPERTY_NOT_VISIBLE.equals(issue.getType())) { - //remove property value - issue.getIntrospector().setValue(issue.getPropName(), null); - return true; - } - return false; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Severity.java b/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Severity.java deleted file mode 100644 index 14501794..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/introspection/tools/Severity.java +++ /dev/null @@ -1,27 +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.introspection.tools; - -public enum Severity { - WARNING, - ERROR, - CRITICAL -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/CNName.java b/aai-core/src/main/java/org/openecomp/aai/logging/CNName.java deleted file mode 100644 index 4c152e3c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/CNName.java +++ /dev/null @@ -1,93 +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.logging; - -import ch.qos.logback.access.pattern.AccessConverter; -import ch.qos.logback.access.spi.IAccessEvent; - -import javax.security.auth.x500.X500Principal; -import javax.servlet.http.HttpServletRequest; -import java.security.cert.X509Certificate; - -import static java.util.Base64.getDecoder; - -public class CNName extends AccessConverter { - - /** - * Converts access events to String response codes - * - * @param accessEvent the IAccessEvent - */ - public String convert(IAccessEvent accessEvent) { - if (!isStarted()) { - return "INACTIVE_HEADER_CONV"; - } - - String cipherSuite = (String) accessEvent.getRequest().getAttribute("javax.servlet.request.cipher_suite"); - String authUser = null; - if (cipherSuite != null) { - try { - X509Certificate certChain[] = (X509Certificate[]) accessEvent.getRequest() - .getAttribute("javax.servlet.request.X509Certificate"); - if(certChain == null || certChain.length == 0){ - - HttpServletRequest request = accessEvent.getRequest(); - - String authorization = request.getHeader("Authorization"); - - // Set the auth user to "-" so if the authorization header is not found - // Or if the decoded basic auth credentials are not found in the format required - // it should return "-" - // If the decoded string is in the right format, find the index of ":" - // Then get the substring of the starting point to the colon not including the colon - - authUser = "-"; - - if(authorization != null && authorization.startsWith("Basic ")){ - String credentials = authorization.replace("Basic ", ""); - byte[] userCredentials = getDecoder().decode(credentials.getBytes("utf-8")); - credentials = new String(userCredentials); - - int codePoint = credentials.indexOf(':'); - - if(codePoint != -1){ - authUser = credentials.substring(0, codePoint); - } - - } - - return authUser; - - } else { - X509Certificate clientCert = certChain[0]; - X500Principal subjectDN = clientCert.getSubjectX500Principal(); - authUser = subjectDN.toString(); - return authUser; - } - } catch(Exception ex){ - return "-"; - } - } else { - return "-"; - } - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayout.java b/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayout.java deleted file mode 100644 index 7a8bbd92..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayout.java +++ /dev/null @@ -1,28 +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.logging; - -public class CustomLogPatternLayout extends ch.qos.logback.access.PatternLayout { - static { - defaultConverterMap.put("z", CNName.class.getName()); - defaultConverterMap.put("y", DME2RestFlag.class.getName()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayoutEncoder.java b/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayoutEncoder.java deleted file mode 100644 index a34c6cc6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/CustomLogPatternLayoutEncoder.java +++ /dev/null @@ -1,40 +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.logging; - -import ch.qos.logback.access.PatternLayout; - -public class CustomLogPatternLayoutEncoder extends ch.qos.logback.access.PatternLayoutEncoder { - -/** - * @{inheritDoc} - */ - @Override - public void start(){ - PatternLayout patternLayout = new CustomLogPatternLayout(); - patternLayout.setContext(context); - patternLayout.setPattern(getPattern()); - patternLayout.start(); - this.layout = patternLayout; - super.start(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/DME2RestFlag.java b/aai-core/src/main/java/org/openecomp/aai/logging/DME2RestFlag.java deleted file mode 100644 index f97f1843..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/DME2RestFlag.java +++ /dev/null @@ -1,55 +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.logging; - -import ch.qos.logback.access.pattern.AccessConverter; -import ch.qos.logback.access.spi.IAccessEvent; - -public class DME2RestFlag extends AccessConverter { - - /** - * @{inheritDoc} - */ - @Override - public String convert(IAccessEvent accessEvent) { - if (!isStarted()) { - return "INACTIVE_HEADER_CONV"; - } - - String flag = "-"; - - if (accessEvent.getRequestParameter("envContext").length > 0 - && !accessEvent.getRequestParameter("envContext")[0].isEmpty() - && !accessEvent.getRequestParameter("envContext")[0].equals("-") - && accessEvent.getRequestParameter("routeOffer").length > 0 - && !accessEvent.getRequestParameter("routeOffer")[0].isEmpty() - && !accessEvent.getRequestParameter("routeOffer")[0].equals("-") - && accessEvent.getRequestParameter("version").length > 0 - && !accessEvent.getRequestParameter("version")[0].isEmpty() - && !accessEvent.getRequestParameter("version")[0].equals("-")) { - flag = "DME2"; - } else { - flag = "REST"; - } - - return flag; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompElapsedTime.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompElapsedTime.java deleted file mode 100644 index f56a6fe5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompElapsedTime.java +++ /dev/null @@ -1,67 +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.logging; - -import org.openecomp.aai.logging.LoggingContext.LoggingField; - -import ch.qos.logback.classic.pattern.ClassicConverter; -import ch.qos.logback.classic.spi.ILoggingEvent; - -public class EcompElapsedTime extends ClassicConverter { - - private static final String DEFAULT_ELAPSED_TIME_FORMAT = "%d"; - - private String ELAPSED_TIME_FORMAT; - - @Override - public void start() { - ELAPSED_TIME_FORMAT = getFirstOption(); - } - - @Override - public String convert(ILoggingEvent event) { - final long end = event.getTimeStamp(); - - if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) { - return format(0); - } else if (event.getMDCPropertyMap().containsKey(LoggingField.ELAPSED_TIME.toString())) { - return format( - Integer.parseInt(event.getMDCPropertyMap().get(LoggingField.ELAPSED_TIME.toString())) - ); - } - - final long start = LogFormatTools.toTimestamp(event.getMDCPropertyMap().get(LoggingField.START_TIME.toString())); - - return format(end - start); - } - - private String format(long elapsedTime) { - if (ELAPSED_TIME_FORMAT == null) { - return format(DEFAULT_ELAPSED_TIME_FORMAT, elapsedTime); - } - - return format (ELAPSED_TIME_FORMAT, elapsedTime); - } - - private String format(String format, long elapsedTime) { - return String.format(format, elapsedTime); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompEncoder.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompEncoder.java deleted file mode 100644 index 396e51c3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompEncoder.java +++ /dev/null @@ -1,38 +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.logging; - -import ch.qos.logback.classic.PatternLayout; -import ch.qos.logback.classic.encoder.PatternLayoutEncoder; - -public class EcompEncoder extends PatternLayoutEncoder { - - @Override - public void start() { - PatternLayout patternLayout = new EcompPatternLayout(); - patternLayout.setContext(context); - patternLayout.setPattern(getPattern()); - patternLayout.setOutputPatternAsHeader(outputPatternAsHeader); - patternLayout.start(); - this.layout = patternLayout; - super.start(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompPatternLayout.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompPatternLayout.java deleted file mode 100644 index bbf32793..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompPatternLayout.java +++ /dev/null @@ -1,31 +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.logging; - -import ch.qos.logback.classic.PatternLayout; - -public class EcompPatternLayout extends PatternLayout { - static { - PatternLayout.defaultConverterMap.put("ecompStartTime", EcompStartTime.class.getName()); - PatternLayout.defaultConverterMap.put("ecompElapsedTime", EcompElapsedTime.class.getName()); - PatternLayout.defaultConverterMap.put("eelfClassOfCaller", EelfClassOfCaller.class.getName()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EcompStartTime.java b/aai-core/src/main/java/org/openecomp/aai/logging/EcompStartTime.java deleted file mode 100644 index c08b273a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EcompStartTime.java +++ /dev/null @@ -1,39 +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.logging; - -import org.openecomp.aai.logging.LoggingContext.LoggingField; - -import ch.qos.logback.classic.pattern.ClassicConverter; -import ch.qos.logback.classic.spi.ILoggingEvent; - -public class EcompStartTime extends ClassicConverter { - - @Override - public String convert(ILoggingEvent event) { - - if (!event.getMDCPropertyMap().containsKey(LoggingField.START_TIME.toString())) { - return LogFormatTools.toDate(event.getTimeStamp()); - } - - return event.getMDCPropertyMap().get(LoggingField.START_TIME.toString()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/EelfClassOfCaller.java b/aai-core/src/main/java/org/openecomp/aai/logging/EelfClassOfCaller.java deleted file mode 100644 index bc745d38..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/EelfClassOfCaller.java +++ /dev/null @@ -1,43 +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.logging; - -import ch.qos.logback.classic.pattern.NamedConverter; -import ch.qos.logback.classic.spi.CallerData; -import ch.qos.logback.classic.spi.ILoggingEvent; - -public class EelfClassOfCaller extends NamedConverter { - protected String getFullyQualifiedName(ILoggingEvent event) { - - StackTraceElement[] cda = event.getCallerData(); - - //If using the EELFLogger, it "hides" the calling class because it wraps the logging calls - //Without this, you'd only ever see "com.att.eelf.configuration.SLF4jWrapper" when using the - // %C pattern converter - if (cda != null && cda.length > 2) { - return cda[2].getClassName(); - } else if (cda != null && cda.length > 0) { - return cda[0].getClassName(); - } else { - return CallerData.NA; - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java deleted file mode 100644 index 23e4f606..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorLogHelper.java +++ /dev/null @@ -1,605 +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.logging; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; - -import javax.ws.rs.core.MediaType; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.MDC; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.LoggingContext.StatusCode; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.util.MapperUtil; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * - * This classes loads the application error properties file - * and provides a method that returns an ErrorObject - * - */ - -public class ErrorLogHelper { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(ErrorLogHelper.class); - private static final HashMap<String, ErrorObject> ERROR_OBJECTS = new HashMap<String, ErrorObject> (); - - static { - try { - loadProperties(); - } catch (IOException e) { - throw new RuntimeException("Failed to load error.properties file", e); - } catch (ErrorObjectFormatException e) { - throw new RuntimeException("Failed to parse error.properties file", e); - } - } - - /** - * Load properties. - * @throws ErrorObjectFormatException - * @throws Exception the exception - */ - public static void loadProperties() throws IOException, ErrorObjectFormatException { - final String filePath = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + "error.properties"; - final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath); - final Properties properties = new Properties(); - - if (is != null) { - properties.load(is); - } else { - try (final FileInputStream fis = new FileInputStream(filePath)) { - properties.load(fis); - } - } - - for (Entry<Object, Object> entry : properties.entrySet()) { - final String key = (String) entry.getKey(); - final String value = (String) entry.getValue(); - final String[] errorProperties = value.split(":"); - - if (errorProperties.length != 7) throw new ErrorObjectFormatException(); - - final ErrorObject errorObject = new ErrorObject(); - - errorObject.setDisposition(errorProperties[0].trim()); - errorObject.setCategory(errorProperties[1].trim()); - errorObject.setSeverity(errorProperties[2].trim()); - errorObject.setErrorCode(errorProperties[3].trim()); - errorObject.setHTTPResponseCode(errorProperties[4].trim()); - errorObject.setRESTErrorCode(errorProperties[5].trim()); - errorObject.setErrorText(errorProperties[6].trim()); - - ERROR_OBJECTS.put(key, errorObject); - } - } - - /** - * Logs a known A&AI exception (i.e. one that can be found in error.properties) - * - * @param key The key for the error in the error.properties file - * @throws IOException - * @throws ErrorObjectNotFoundException - * @throws ErrorObjectFormatException - */ - public static ErrorObject getErrorObject(String code) throws ErrorObjectNotFoundException { - - if (code == null) throw new IllegalArgumentException("Key cannot be null"); - - final ErrorObject errorObject = ERROR_OBJECTS.get(code); - - if (errorObject == null) { - LOGGER.warn("Unknown AAIException with code=" + code + ". Using default AAIException"); - return ERROR_OBJECTS.get(AAIException.DEFAULT_EXCEPTION_CODE); - } - - return errorObject; - } - - /** - * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error. - * The AAIRESTException may contain a different ErrorObject than that created with the REST error key. - * This allows lower level exception detail to be returned to the client to help troubleshoot the problem. - * If no error object is embedded in the AAIException, one will be created using the error object from the AAIException. - * @param are must have a restError value whose numeric value must match what should be returned in the REST API - * @param variables optional list of variables to flesh out text in error string - * @return appropriately formatted JSON response per the REST API spec. - * @throws ErrorObjectFormatException - * @throws ErrorObjectNotFoundException - * @throws IOException - * @deprecated - */ - public static String getRESTAPIErrorResponse(AAIException are, ArrayList<String> variables) { - List<MediaType> acceptHeaders = new ArrayList<MediaType>(); - acceptHeaders.add(MediaType.APPLICATION_JSON_TYPE); - - return getRESTAPIErrorResponse(acceptHeaders, are, variables); - } - - /** - * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error. - * The AAIRESTException may contain a different ErrorObject than that created with the REST error key. - * This allows lower level exception detail to be returned to the client to help troubleshoot the problem. - * If no error object is embedded in the AAIException, one will be created using the error object from the AAIException. - * - * @param acceptHeadersOrig the accept headers orig - * @param are must have a restError value whose numeric value must match what should be returned in the REST API - * @param variables optional list of variables to flesh out text in error string - * @return appropriately formatted JSON response per the REST API spec. - * @throws ErrorObjectFormatException - * @throws ErrorObjectNotFoundException - * @throws IOException - */ - public static String getRESTAPIErrorResponse(List<MediaType> acceptHeadersOrig, AAIException are, ArrayList<String> variables) { - - - StringBuilder text = new StringBuilder(); - String response = null; - - List<MediaType> acceptHeaders = new ArrayList<MediaType>(); - // we might have an exception but no accept header, so we'll set default to JSON - boolean foundValidAcceptHeader = false; - for (MediaType mt : acceptHeadersOrig) { - if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt) || - MediaType.APPLICATION_JSON_TYPE.isCompatible(mt)) { - acceptHeaders.add(mt); - foundValidAcceptHeader = true; - } - } - if (foundValidAcceptHeader == false) { - // override the exception, client needs to set an appropriate Accept header - are = new AAIException("AAI_4014"); - acceptHeaders.add(MediaType.APPLICATION_JSON_TYPE); - } - - final ErrorObject eo = are.getErrorObject(); - - int restErrorCode = Integer.parseInt(eo.getRESTErrorCode()); - - ErrorObject restErrorObject; - - try { - restErrorObject = ErrorLogHelper.getErrorObject("AAI_"+restErrorCode); - } catch (ErrorObjectNotFoundException e) { - LOGGER.warn("Failed to find related error object AAI_" + restErrorCode + " for error object " + eo.getErrorCode() + "; using AAI_" + restErrorCode); - restErrorObject = eo; - } - - text.append(restErrorObject.getErrorText()); - - // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n - // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the - // error, are ordered based on the error string. - int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%"); - text.append(" (msg=%").append(localDataIndex+1).append(") (ec=%").append(localDataIndex+2).append(")"); - - if (variables == null) - { - variables = new ArrayList<String>(); - } - - if (variables.size() < localDataIndex) { - ErrorLogHelper.logError("AAI_4011", "data missing for rest error"); - while (variables.size() < localDataIndex) { - variables.add("null"); - } - } - - // This will put the error code and error text into the right positions - if (are.getMessage() == null || are.getMessage().length() == 0) { - variables.add(localDataIndex++, eo.getErrorText()); - } - else { - variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage()); - } - variables.add(localDataIndex, eo.getErrorCodeString()); - - for (MediaType mediaType : acceptHeaders) { - if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) { - JAXBContext context = null; - try { - if(eo.getCategory().equals("1")) { - - context = JAXBContext.newInstance(org.openecomp.aai.domain.restPolicyException.Fault.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - - org.openecomp.aai.domain.restPolicyException.ObjectFactory factory = new org.openecomp.aai.domain.restPolicyException.ObjectFactory(); - org.openecomp.aai.domain.restPolicyException.Fault fault = factory.createFault(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError requestError = factory.createFaultRequestError(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException = factory.createFaultRequestErrorPolicyException(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables = factory.createFaultRequestErrorPolicyExceptionVariables(); - - policyException.setMessageId("POL" + eo.getRESTErrorCode()); - policyException.setText(text.toString()); - for (int i=0;i<variables.size();i++) - { - polvariables.getVariable().add(variables.get(i)); - } - policyException.setVariables(polvariables); - requestError.setPolicyException(policyException); - fault.setRequestError(requestError); - - StringWriter sw = new StringWriter(); - m.marshal(fault, sw); - - response = sw.toString(); - - } else { - - context = JAXBContext.newInstance(org.openecomp.aai.domain.restServiceException.Fault.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - - org.openecomp.aai.domain.restServiceException.ObjectFactory factory = new org.openecomp.aai.domain.restServiceException.ObjectFactory(); - org.openecomp.aai.domain.restServiceException.Fault fault = factory.createFault(); - org.openecomp.aai.domain.restServiceException.Fault.RequestError requestError = factory.createFaultRequestError(); - org.openecomp.aai.domain.restServiceException.Fault.RequestError.ServiceException serviceException = factory.createFaultRequestErrorServiceException(); - org.openecomp.aai.domain.restServiceException.Fault.RequestError.ServiceException.Variables svcvariables = factory.createFaultRequestErrorServiceExceptionVariables(); - serviceException.setMessageId("SVC" + eo.getRESTErrorCode()); - serviceException.setText(text.toString()); - for (int i=0;i<variables.size();i++) - { - svcvariables.getVariable().add(variables.get(i)); - } - serviceException.setVariables(svcvariables); - requestError.setServiceException(serviceException); - fault.setRequestError(requestError); - - StringWriter sw = new StringWriter(); - m.marshal(fault, sw); - - response = sw.toString(); - - } - } catch (Exception ex) { - LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error", ex); - } - } - else { - try { - if(eo.getCategory().equals("1")) { - org.openecomp.aai.domain.restPolicyException.RESTResponse restresp = new org.openecomp.aai.domain.restPolicyException.RESTResponse(); - org.openecomp.aai.domain.restPolicyException.RequestError reqerr = new org.openecomp.aai.domain.restPolicyException.RequestError(); - org.openecomp.aai.domain.restPolicyException.PolicyException polexc = new org.openecomp.aai.domain.restPolicyException.PolicyException(); - polexc.setMessageId("POL" + eo.getRESTErrorCode()); - polexc.setText(text.toString()); - polexc.setVariables(variables); - reqerr.setPolicyException(polexc); - restresp.setRequestError(reqerr); - response = (MapperUtil.writeAsJSONString((Object) restresp)); - - } else { - org.openecomp.aai.domain.restServiceException.RESTResponse restresp = new org.openecomp.aai.domain.restServiceException.RESTResponse(); - org.openecomp.aai.domain.restServiceException.RequestError reqerr = new org.openecomp.aai.domain.restServiceException.RequestError(); - org.openecomp.aai.domain.restServiceException.ServiceException svcexc = new org.openecomp.aai.domain.restServiceException.ServiceException(); - svcexc.setMessageId("SVC" + eo.getRESTErrorCode()); - svcexc.setText(text.toString()); - svcexc.setVariables(variables); - reqerr.setServiceException(svcexc); - restresp.setRequestError(reqerr); - response = (MapperUtil.writeAsJSONString((Object) restresp)); - } - } catch (AAIException ex) { - LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error", ex); - } - } - } - - - return response; - } - - /** - * Gets the RESTAPI error response with logging. - * - * @param acceptHeadersOrig the accept headers orig - * @param are the are - * @param variables the variables - * @param logline the logline - * @return the RESTAPI error response with logging - * @throws ErrorObjectFormatException - * @throws ErrorObjectNotFoundException - * @throws IOException - */ - public static String getRESTAPIErrorResponseWithLogging(List<MediaType> acceptHeadersOrig, AAIException are, ArrayList<String> variables) { - String response = ErrorLogHelper.getRESTAPIErrorResponse(acceptHeadersOrig, are, variables); - - LOGGER.error(are.getMessage(), are); - - return response; - } - - /** - * Gets the RESTAPI info response. - * - * @param acceptHeaders the accept headers - * @param areList the are list - * @return the RESTAPI info response - * @throws ErrorObjectFormatException - * @throws ErrorObjectNotFoundException - * @throws IOException - */ - public static Object getRESTAPIInfoResponse(List<MediaType> acceptHeaders, HashMap<AAIException,ArrayList<String>> areList) { - - Object respObj = null; - - org.openecomp.aai.domain.restResponseInfo.ObjectFactory factory = new org.openecomp.aai.domain.restResponseInfo.ObjectFactory(); - org.openecomp.aai.domain.restResponseInfo.Info info = factory.createInfo(); - org.openecomp.aai.domain.restResponseInfo.Info.ResponseMessages responseMessages = factory.createInfoResponseMessages(); - Iterator<Map.Entry<AAIException, ArrayList<String>>> it = areList.entrySet().iterator(); - - while (it.hasNext()) { - Map.Entry<AAIException,ArrayList<String>> pair = (Map.Entry<AAIException, ArrayList<String>>)it.next(); - AAIException are = pair.getKey(); - ArrayList<String> variables = pair.getValue(); - - StringBuilder text = new StringBuilder(); - - ErrorObject eo = are.getErrorObject(); - - int restErrorCode = Integer.parseInt(eo.getRESTErrorCode()); - ErrorObject restErrorObject; - try { - restErrorObject = ErrorLogHelper.getErrorObject("AAI_"+String.format("%04d", restErrorCode)); - } catch (ErrorObjectNotFoundException e) { - restErrorObject = eo; - } - text.append(restErrorObject.getErrorText()); - - // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n - // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the - // error, are ordered based on the error string. - int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%"); - text.append(" (msg=%").append(localDataIndex+1).append(") (rc=%").append(localDataIndex+2).append(")"); - - if (variables == null) - { - variables = new ArrayList<String>(); - } - - if (variables.size() < localDataIndex) { - ErrorLogHelper.logError("AAI_4011", "data missing for rest error"); - while (variables.size() < localDataIndex) { - variables.add("null"); - } - } - - // This will put the error code and error text into the right positions - if (are.getMessage() == null) { - variables.add(localDataIndex++, eo.getErrorText()); - } - else { - variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage()); - } - variables.add(localDataIndex, eo.getErrorCodeString()); - - try { - org.openecomp.aai.domain.restResponseInfo.Info.ResponseMessages.ResponseMessage responseMessage = factory.createInfoResponseMessagesResponseMessage(); - org.openecomp.aai.domain.restResponseInfo.Info.ResponseMessages.ResponseMessage.Variables infovariables = factory.createInfoResponseMessagesResponseMessageVariables(); - - responseMessage.setMessageId("INF" + eo.getRESTErrorCode()); - responseMessage.setText(text.toString()); - for (int i=0;i<variables.size();i++) - { - infovariables.getVariable().add(variables.get(i)); - } - - responseMessage.setVariables(infovariables); - responseMessages.getResponseMessage().add(responseMessage); - - } catch (Exception ex) { - LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error", ex); - } - } - - info.setResponseMessages(responseMessages); - respObj = (Object) info; - - return respObj; - } - - - /** - * Determines whether category is policy or not. If policy (1), this is a POL error, else it's a SVC error. - * The AAIRESTException may contain a different ErrorObject than that created with the REST error key. - * This allows lower level exception detail to be returned to the client to help troubleshoot the problem. - * If no error object is embedded in the AAIException, one will be created using the error object from the AAIException. - * @param are must have a restError value whose numeric value must match what should be returned in the REST API - * @param variables optional list of variables to flesh out text in error string - * @return appropriately formatted JSON response per the REST API spec. - * @throws ErrorObjectFormatException - * @throws ErrorObjectNotFoundException - * @throws IOException - */ - public static String getRESTAPIPolicyErrorResponseXML(AAIException are, ArrayList<String> variables) { - - StringBuilder text = new StringBuilder(); - String response = null; - JAXBContext context = null; - - ErrorObject eo = are.getErrorObject(); - - int restErrorCode = Integer.parseInt(eo.getRESTErrorCode()); - ErrorObject restErrorObject; - try { - restErrorObject = ErrorLogHelper.getErrorObject("AAI_"+restErrorCode); - } catch (ErrorObjectNotFoundException e) { - restErrorObject = eo; - } - - text.append(restErrorObject.getErrorText()); - - // We want to always append the (msg=%n) (ec=%n+1) to the text, but have to find value of n - // This assumes that the variables in the ArrayList, which might be more than are needed to flesh out the - // error, are ordered based on the error string. - int localDataIndex = StringUtils.countMatches(restErrorObject.getErrorText(), "%"); - text.append(" (msg=%").append(localDataIndex+1).append(") (ec=%").append(localDataIndex+2).append(")"); - - if (variables == null) - { - variables = new ArrayList<String>(); - } - - if (variables.size() < localDataIndex) { - ErrorLogHelper.logError("AAI_4011", "data missing for rest error"); - while (variables.size() < localDataIndex) { - variables.add("null"); - } - } - - // This will put the error code and error text into the right positions - if (are.getMessage() == null) { - variables.add(localDataIndex++, eo.getErrorText()); - } - else { - variables.add(localDataIndex++, eo.getErrorText() + ":" + are.getMessage()); - } - variables.add(localDataIndex, eo.getErrorCodeString()); - - try { - if(eo.getCategory().equals("1")) { - - context = JAXBContext.newInstance(org.openecomp.aai.domain.restPolicyException.Fault.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - - org.openecomp.aai.domain.restPolicyException.ObjectFactory factory = new org.openecomp.aai.domain.restPolicyException.ObjectFactory(); - org.openecomp.aai.domain.restPolicyException.Fault fault = factory.createFault(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError requestError = factory.createFaultRequestError(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException policyException = factory.createFaultRequestErrorPolicyException(); - org.openecomp.aai.domain.restPolicyException.Fault.RequestError.PolicyException.Variables polvariables = factory.createFaultRequestErrorPolicyExceptionVariables(); - - policyException.setMessageId("POL" + eo.getRESTErrorCode()); - policyException.setText(text.toString()); - for (int i=0;i<variables.size();i++) - { - polvariables.getVariable().add(variables.get(i)); - } - policyException.setVariables(polvariables); - requestError.setPolicyException(policyException); - fault.setRequestError(requestError); - - StringWriter sw = new StringWriter(); - m.marshal(fault, sw); - - response = sw.toString(); - - } else { - - context = JAXBContext.newInstance(org.openecomp.aai.domain.restServiceException.Fault.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); - - org.openecomp.aai.domain.restServiceException.ObjectFactory factory = new org.openecomp.aai.domain.restServiceException.ObjectFactory(); - org.openecomp.aai.domain.restServiceException.Fault fault = factory.createFault(); - org.openecomp.aai.domain.restServiceException.Fault.RequestError requestError = factory.createFaultRequestError(); - org.openecomp.aai.domain.restServiceException.Fault.RequestError.ServiceException serviceException = factory.createFaultRequestErrorServiceException(); - org.openecomp.aai.domain.restServiceException.Fault.RequestError.ServiceException.Variables svcvariables = factory.createFaultRequestErrorServiceExceptionVariables(); - serviceException.setMessageId("POL" + eo.getRESTErrorCode()); - serviceException.setText(text.toString()); - for (int i=0;i<variables.size();i++) - { - svcvariables.getVariable().add(variables.get(i)); - } - serviceException.setVariables(svcvariables); - requestError.setServiceException(serviceException); - fault.setRequestError(requestError); - - StringWriter sw = new StringWriter(); - m.marshal(fault, sw); - - response = sw.toString(); - - } - } catch (Exception ex) { - LOGGER.error("We were unable to create a rest exception to return on an API because of a parsing error", ex); - } - return response; - } - - public static void logException(AAIException e) { - final ErrorObject errorObject = e.getErrorObject(); - -// MDC.put("severity", errorObject.getSeverity()); //TODO Use LoggingContext.severity(int severity) - String severityCode = errorObject.getSeverityCode(errorObject.getSeverity()); - - if (!AAIConfig.isEmpty(severityCode)) { - int sevCode = Integer.parseInt(severityCode); - if (sevCode > 0 && sevCode <= 3 ) - { - LoggingContext.severity(sevCode); - } - } - - final String errorMessage = new StringBuilder() - .append(errorObject.getErrorText()) - .append(":") - .append(errorObject.getRESTErrorCode()) - .append(":") - .append(errorObject.getHTTPResponseCode()) - .append(":") - .append(e.getMessage()) - .toString(); - - LoggingContext.responseCode(Integer.toString(errorObject.getHTTPResponseCode().getStatusCode())); - LoggingContext.responseDescription(errorMessage); - LoggingContext.statusCode(StatusCode.ERROR); - - if (errorObject.getSeverity().equalsIgnoreCase("WARN")) - LOGGER.warn(errorMessage, e); - else if (errorObject.getSeverity().equalsIgnoreCase("ERROR")) - LOGGER.error(errorMessage, e); - else if (errorObject.getSeverity().equalsIgnoreCase("FATAL")) - LOGGER.error(errorMessage, e); - else if (errorObject.getSeverity().equals("INFO")) - LOGGER.info(errorMessage + ", " + e.getMessage()); - } - - public static void logError(String code) { - logError(code, ""); - } - - public static void logError(String code, String message) { - logException(new AAIException(code, message)); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java deleted file mode 100644 index 50822f68..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObject.java +++ /dev/null @@ -1,331 +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.logging; - -import javax.ws.rs.core.Response.Status; - -/** - * - * Contains the definition of all error message fields to be mapped from the Error - * properties file - * - */ -public class ErrorObject { - - private String disposition; - private String category; - private String severity; - private Status httpResponseCode = Status.INTERNAL_SERVER_ERROR; // default - private String restErrorCode = "3002"; - private String errorCode; - private String errorText; - - /** - * Instantiates a new error object. - */ - public ErrorObject() { - super(); - } - - /** - * Creates an error object with the default HTTP Error Code (Status.INTERNAL_SERVER_ERROR) - * - * @param disposition the disposition - * @param category the category - * @param severity the severity - * @param httpResponseCode the http response code - * @param restErrorCode the rest error code - * @param errorCode the error code - * @param errorText the error text - */ - public ErrorObject(String disposition, String category, String severity, Integer httpResponseCode, String restErrorCode, String errorCode, String errorText) { - super(); - this.setDisposition(disposition); - this.setCategory(category); - this.severity = severity; - this.setHTTPResponseCode(httpResponseCode); - this.setRESTErrorCode(restErrorCode); - this.setErrorCode(errorCode); - this.setErrorText(errorText); - } - - // OLD STARTS HERE - - /** - * Instantiates a new error object. - * - * @param severity the severity - * @param errorCode the error code - * @param errorText the error text - * @param disposition the disposition - * @param category the category - */ - public ErrorObject(String severity, String errorCode, String errorText, String disposition, String category) { - this(severity, Status.INTERNAL_SERVER_ERROR, errorCode, errorText, disposition, category); - } - - /** - * Instantiates a new error object. - * - * @param severity the severity - * @param httpResponseCode the http response code - * @param errorCode the error code - * @param errorText the error text - * @param disposition the disposition - * @param category the category - */ - public ErrorObject(String severity, Integer httpResponseCode, String errorCode, String errorText, String disposition, String category) { - super(); - this.severity = severity; - this.setHTTPResponseCode(httpResponseCode); - this.setErrorCode(errorCode); - this.setErrorText(errorText); - this.setDisposition(disposition); - this.setCategory(category); - } - - /** - * Instantiates a new error object. - * - * @param severity the severity - * @param httpResponseCode the http response code - * @param errorCode the error code - * @param errorText the error text - * @param disposition the disposition - * @param category the category - */ - public ErrorObject(String severity, Status httpResponseCode, String errorCode, String errorText, String disposition, String category) { - super(); - this.severity = severity; - this.setHTTPResponseCode(httpResponseCode); - this.setErrorCode(errorCode); - this.setErrorText(errorText); - this.setDisposition(disposition); - this.setCategory(category); - } - - /** - * Gets the disposition. - * - * @return the disposition - */ - public String getDisposition() { - return disposition; - } - - /** - * Sets the disposition. - * - * @param disposition the new disposition - */ - public void setDisposition(String disposition) { - this.disposition = disposition; - } - - /** - * Gets the category. - * - * @return the category - */ - public String getCategory() { - return category; - } - - /** - * Sets the category. - * - * @param category the new category - */ - public void setCategory(String category) { - this.category = category; - } - - /** - * Gets the severity. - * - * @return the severity - */ - public String getSeverity() { - return severity; - } - - /** - * Sets the severity. - * - * @param severity the new severity - */ - public void setSeverity(String severity) { - this.severity = severity; - } - - /** - * Gets the error code. - * - * @return the error code - */ - public String getErrorCode() { - return errorCode; - } - - /** - * Sets the error code. - * - * @param errorCode the new error code - */ - public void setErrorCode(String errorCode) { - this.errorCode = errorCode; - } - - /** - * Gets the HTTP response code. - * - * @return the HTTP response code - */ - public Status getHTTPResponseCode() { - return httpResponseCode; - } - - /** - * Sets the HTTP response code. - * - * @param httpResponseCode the new HTTP response code - */ - public void setHTTPResponseCode(Integer httpResponseCode) { - this.httpResponseCode = Status.fromStatusCode(httpResponseCode); - if (this.httpResponseCode == null) { - throw new IllegalArgumentException("setHTTPResponseCode was passed an invalid Integer value, fix error.properties or your code "+httpResponseCode); - } - } - - /** - * Sets the HTTP response code. - * - * @param httpResponseCode the new HTTP response code - */ - public void setHTTPResponseCode(String httpResponseCode) { - this.httpResponseCode = Status.fromStatusCode(Integer.valueOf(httpResponseCode)); - if (this.httpResponseCode == null) { - throw new IllegalArgumentException("setHTTPResponseCode was passed an invalid String value, fix error.properties or your code "+httpResponseCode); - } - } - - /** - * Sets the REST error code. - * - * @param restErrorCode the new REST error code - */ - public void setRESTErrorCode(String restErrorCode) { - this.restErrorCode = restErrorCode; - } - - /** - * Gets the REST error code. - * - * @return the REST error code - */ - public String getRESTErrorCode() { - return this.restErrorCode; - } - - /** - * Sets the HTTP response code. - * - * @param httpResponseCode the new HTTP response code - */ - public void setHTTPResponseCode(Status httpResponseCode) { - this.httpResponseCode = httpResponseCode; - if (this.httpResponseCode == null) { - throw new IllegalArgumentException("setHTTPResponseCode was passed an invalid String value, fix error.properties or your code "+httpResponseCode); - } - } - - /** - * Gets the error text. - * - * @return the error text - */ - public String getErrorText() { - return errorText; - } - - /** - * Sets the error text. - * - * @param errorText the new error text - */ - public void setErrorText(String errorText) { - this.errorText = errorText; - } - - /** - * Gets the error code string. This is also the string - * configured in Nagios to alert on - * - * @return the error code string - */ - // Get the X.Y.Z representation of the error code - public String getErrorCodeString() { - String prefix = null; - switch (disposition) { - default: - prefix = ""; - break; - case "5": - prefix = "ERR."; - break; - } - return prefix + disposition + "." + category + "." + errorCode; - } - - /** - * Gets the severity Code. This is also the string - * configured in Nagios to alert on - * - * @return the severity - */ - // Get the numerical value of severity - public String getSeverityCode(String severity) { - String severityCode = ""; - switch (severity) { - case "WARN": - severityCode = "1"; - break; - case "ERROR": - severityCode = "2"; - break; - case "FATAL": - severityCode = "3"; - break; - } - return severityCode; - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - return "ErrorObject [errorCode="+ errorCode + ", errorText=" + errorText - + ", restErrorCode=" + restErrorCode + ", httpResponseCode="+ httpResponseCode - + ", severity=" + severity + ", disposition=" + disposition + ", category=" + category +"]"; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectFormatException.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectFormatException.java deleted file mode 100644 index 5e3e7464..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectFormatException.java +++ /dev/null @@ -1,30 +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.logging; - -public class ErrorObjectFormatException extends Exception { - - private static final long serialVersionUID = 3732705544448553685L; - - public ErrorObjectFormatException() { - super(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectNotFoundException.java b/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectNotFoundException.java deleted file mode 100644 index fcf72039..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/ErrorObjectNotFoundException.java +++ /dev/null @@ -1,51 +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.logging; - -public class ErrorObjectNotFoundException extends Exception { - - private static final long serialVersionUID = 4115316781400786740L; - - public ErrorObjectNotFoundException() { - // TODO Auto-generated constructor stub - } - - public ErrorObjectNotFoundException(String message) { - super(message); - // TODO Auto-generated constructor stub - } - - public ErrorObjectNotFoundException(Throwable cause) { - super(cause); - // TODO Auto-generated constructor stub - } - - public ErrorObjectNotFoundException(String message, Throwable cause) { - super(message, cause); - // TODO Auto-generated constructor stub - } - - public ErrorObjectNotFoundException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - // TODO Auto-generated constructor stub - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/LogFormatTools.java b/aai-core/src/main/java/org/openecomp/aai/logging/LogFormatTools.java deleted file mode 100644 index a07fdc73..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/LogFormatTools.java +++ /dev/null @@ -1,45 +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.logging; - -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; - -public class LogFormatTools { - - private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern(DATE_FORMAT) - .withZone(ZoneOffset.UTC); - - public static String getCurrentDateTime() { - return DTF.format(ZonedDateTime.now()); - } - - public static String toDate(long timestamp) { - return DTF.format(Instant.ofEpochMilli(timestamp)); - } - - public static long toTimestamp(String date) { - return ZonedDateTime.parse(date, DTF).toInstant().toEpochMilli(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java b/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java deleted file mode 100644 index 9a2d5914..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContext.java +++ /dev/null @@ -1,374 +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.logging; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.MDC; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class LoggingContext { - - public enum StatusCode { - COMPLETE, - ERROR - } - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LoggingContext.class); - - private static final String PREVIOUS_CONTEXTS_KEY = "_PREVIOUS_CONTEXTS"; - - //ECOMP Specific Log Event Fields - public static enum LoggingField { - START_TIME("startTime"), - REQUEST_ID("requestId"), - SERVICE_INSTANCE_ID("serviceInstanceId"), - SERVER_NAME("serverName"), - SERVICE_NAME("serviceName"), - PARTNER_NAME("partnerName"), - STATUS_CODE("statusCode"), - RESPONSE_CODE("responseCode"), - RESPONSE_DESCRIPTION("responseDescription"), - INSTANCE_UUID("instanceUUID"), - SEVERITY("severity"), - SERVER_IP_ADDRESS("serverIpAddress"), - ELAPSED_TIME("elapsedTime"), - SERVER("server"), - CLIENT_IP_ADDRESS("clientIpAddress"), - UNUSED("unused"), - PROCESS_KEY("processKey"), - CUSTOM_FIELD_1("customField1"), - CUSTOM_FIELD_2("customField2"), - CUSTOM_FIELD_3("customField3"), - CUSTOM_FIELD_4("customField4"), - - //ECOMP Specific Metric Log Event Fields - TARGET_ENTITY("targetEntity"), - - //A&AI Specific Log Event Fields - COMPONENT("component"), - STOP_WATCH_START("stopWatchStart"); - - private final String text; - - private LoggingField(final String text) { - this.text = text; - } - - public String toString() { - return text; - } - } - - - public static void init() { - LoggingContext.clear(); - LoggingContext.startTime(); - LoggingContext.server(); - LoggingContext.serverIpAddress(); - } - - private static void startTime() { - MDC.put(LoggingField.START_TIME.toString(), LogFormatTools.getCurrentDateTime()); - } - - public static UUID requestId() { - final String sUuid = MDC.get(LoggingField.REQUEST_ID.toString()); - - if (sUuid == null) return null; - - return UUID.fromString(sUuid); - } - - public static void requestId(UUID requestId) { - MDC.put(LoggingField.REQUEST_ID.toString(), requestId.toString()); - } - - public static void requestId(String requestId) { - try { - if (requestId.contains(":")) { - String[] uuidParts = requestId.split(":"); - requestId = uuidParts[0]; - } - MDC.put(LoggingField.REQUEST_ID.toString(), UUID.fromString(requestId).toString()); - } catch (IllegalArgumentException e) { - final UUID generatedRequestUuid = UUID.randomUUID(); - MDC.put(LoggingField.REQUEST_ID.toString(), generatedRequestUuid.toString()); - LOGGER.warn("Unable to use UUID " + requestId + " (Not formatted properly). Using generated UUID=" + generatedRequestUuid); - } - } - - public static void serviceInstanceId(String serviceInstanceId) { - MDC.put(LoggingField.SERVICE_INSTANCE_ID.toString(), serviceInstanceId); - } - - public static void serverName(String serverName) { - MDC.put(LoggingField.SERVER_NAME.toString(), serverName); - } - - public static void serviceName(String serviceName) { - MDC.put(LoggingField.SERVICE_NAME.toString(), serviceName); - } - - public static void partnerName(String partnerName) { - MDC.put(LoggingField.PARTNER_NAME.toString(), partnerName); - } - - public static void statusCode(LoggingContext.StatusCode statusCode) { - MDC.put(LoggingField.STATUS_CODE.toString(), statusCode.toString()); - } - - public static String responseCode() { - return (String) MDC.get(LoggingField.RESPONSE_CODE.toString()); - } - - public static void responseCode(String responseCode) { - MDC.put(LoggingField.RESPONSE_CODE.toString(), responseCode); - } - - public static void responseDescription(String responseDescription) { - MDC.put(LoggingField.RESPONSE_DESCRIPTION.toString(), responseDescription); - } - - public static Object instanceUuid() { - return UUID.fromString(MDC.get(LoggingField.INSTANCE_UUID.toString())); - } - - public static void instanceUuid(UUID instanceUuid) { - MDC.put(LoggingField.INSTANCE_UUID.toString(), instanceUuid.toString()); - } - - public static void severity(int severity) { - MDC.put(LoggingField.SEVERITY.toString(), String.valueOf(severity)); - } - - private static void serverIpAddress() { - try { - MDC.put(LoggingField.SERVER_IP_ADDRESS.toString(), InetAddress.getLocalHost().getHostAddress()); - } catch (UnknownHostException e) { - LOGGER.warn("Unable to resolve server IP address - will not be displayed in logged events"); - } - } - - public static void elapsedTime(long elapsedTime, TimeUnit timeUnit) { - MDC.put(LoggingField.ELAPSED_TIME.toString(), String.valueOf(TimeUnit.MILLISECONDS.convert(elapsedTime, timeUnit))); - } - - private static void server() { - try { - MDC.put(LoggingField.SERVER.toString(), InetAddress.getLocalHost().getCanonicalHostName()); - } catch (UnknownHostException e) { - LOGGER.warn("Unable to resolve server IP address - hostname will not be displayed in logged events"); - } - } - - public static void clientIpAddress(InetAddress clientIpAddress) { - MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), clientIpAddress.getHostAddress()); - } - - public static void clientIpAddress(String clientIpAddress) { - try { - MDC.put(LoggingField.CLIENT_IP_ADDRESS.toString(), InetAddress.getByName(clientIpAddress).getHostAddress()); - } catch (UnknownHostException e) { - //Ignore, will not be thrown since InetAddress.getByName(String) only - //checks the validity of the passed in string - } - } - - public static void unused(String unused) { - LOGGER.warn("Using field '" + LoggingField.UNUSED + "' (seems like this should go unused...)"); - MDC.put(LoggingField.UNUSED.toString(), unused); - } - - public static void processKey(String processKey) { - MDC.put(LoggingField.PROCESS_KEY.toString(), processKey); - } - - public static String customField1() { - return MDC.get(LoggingField.CUSTOM_FIELD_1.toString()); - } - - public static void customField1(String customField1) { - MDC.put(LoggingField.CUSTOM_FIELD_1.toString(), customField1); - } - - public static void customField2(String customField2) { - MDC.put(LoggingField.CUSTOM_FIELD_2.toString(), customField2); - } - - public static void customField3(String customField3) { - MDC.put(LoggingField.CUSTOM_FIELD_3.toString(), customField3); - } - - public static void customField4(String customField4) { - MDC.put(LoggingField.CUSTOM_FIELD_4.toString(), customField4); - } - - public static void component(String component) { - MDC.put(LoggingField.COMPONENT.toString(), component); - } - - public static void targetEntity(String targetEntity) { - MDC.put(LoggingField.TARGET_ENTITY.toString(), targetEntity); - } - - public static void stopWatchStart() { - MDC.put(LoggingField.STOP_WATCH_START.toString(), String.valueOf(System.nanoTime())); - } - - public static double stopWatchStop() { - final long stopWatchEnd = System.nanoTime(); - final String rawStopWatchStart = MDC.get(LoggingField.STOP_WATCH_START.toString()); - - if (rawStopWatchStart == null) throw new StopWatchNotStartedException(); - - final Long stopWatchStart = Long.valueOf(rawStopWatchStart); - - MDC.remove(LoggingField.STOP_WATCH_START.toString()); - - final double elapsedTimeMillis = (stopWatchEnd - stopWatchStart) / 1000.0 / 1000.0; - - LoggingContext.elapsedTime((long) elapsedTimeMillis, TimeUnit.MILLISECONDS); - - return elapsedTimeMillis; - } - - public static void put(String key, String value) { - MDC.put(key, value); - } - - public static void clear() { - MDC.clear(); - } - - public static void remove(String key) { - MDC.remove(key); - } - - public static void save() { - final JSONObject context = new JSONObject(); - - for (LoggingField field : LoggingField.values()) { - if (field == LoggingField.ELAPSED_TIME) continue; - - try { - context.put(field.toString(), MDC.get(field.toString())); - } catch (JSONException e) { - //Ignore - only occurs when the key is null (which can't happen) - // or the value is invalid (everything is converted to a string - // before it get put() to the MDC) - } - } - - final String rawJsonArray = MDC.get(PREVIOUS_CONTEXTS_KEY); - - if (rawJsonArray == null) { - final JSONArray stack = new JSONArray() - .put(context); - - MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString()); - } else { - try { - final JSONArray stack = new JSONArray(rawJsonArray) - .put(context); - - MDC.put(PREVIOUS_CONTEXTS_KEY, stack.toString()); - } catch (JSONException e) { - //Ignore - } - } - } - - public static void restore() { - - final String rawPreviousContexts = MDC.get(PREVIOUS_CONTEXTS_KEY); - - if (rawPreviousContexts == null) { - throw new LoggingContextNotExistsException(); - } - - try { - final JSONArray previousContexts = new JSONArray(rawPreviousContexts); - final JSONObject previousContext = previousContexts.getJSONObject(previousContexts.length() - 1); - - @SuppressWarnings("unchecked") - final Iterator<String> keys = previousContext.keys(); - - while (keys.hasNext()) { - final String key = keys.next(); - - try { - MDC.put(key, previousContext.getString(key)); - } catch (JSONException e) { - //Ignore, only occurs when the key is null (cannot happen) - // or the value is invalid (they are all strings) - } - } - - MDC.put(PREVIOUS_CONTEXTS_KEY, removeLast(previousContexts).toString()); - } catch (JSONException e) { - //Ignore, the previousContext is serialized from a JSONObject - } - } - - /** - * AJSC declares an ancient version of org.json:json in one of the parent POMs of this project. - * I tried to update our version of that library in our POM, but it's ignored because of the way - * AJSC has organized their <dependencies>. Had they put it into the <dependencyManagement> section, - * this method would not be necessary. - */ - private static JSONArray removeLast(JSONArray previousContexts) { - final JSONArray result = new JSONArray(); - - for (int i = 0; i < previousContexts.length() - 1; i++) { - try { - result.put(previousContexts.getJSONObject(i)); - } catch (JSONException e) { - //Ignore - not possible - } - } - - return result; - } - - public static Map<String, String> getCopy() { - final Map<String, String> copy = new HashMap<String, String> (); - - for (LoggingField field : LoggingField.values()) { - final String value = MDC.get(field.toString()); - - if (value != null) copy.put(field.toString(), value); - } - - return copy; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContextNotExistsException.java b/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContextNotExistsException.java deleted file mode 100644 index d2149b49..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/LoggingContextNotExistsException.java +++ /dev/null @@ -1,26 +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.logging; - -public class LoggingContextNotExistsException extends RuntimeException { - - private static final long serialVersionUID = -4965807709525739623L; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatch.java b/aai-core/src/main/java/org/openecomp/aai/logging/StopWatch.java deleted file mode 100644 index 0aa6f0d1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatch.java +++ /dev/null @@ -1,41 +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.logging; - -import org.openecomp.aai.logging.LoggingContext.LoggingField; - -public final class StopWatch { - - private StopWatch() {} - - public static void start() { - LoggingContext.stopWatchStart(); - } - - public static double stop() { - return LoggingContext.stopWatchStop(); - } - - public static void clear() { - LoggingContext.remove(LoggingField.STOP_WATCH_START.toString()); - LoggingContext.remove(LoggingField.ELAPSED_TIME.toString()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatchNotStartedException.java b/aai-core/src/main/java/org/openecomp/aai/logging/StopWatchNotStartedException.java deleted file mode 100644 index 89c59924..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/logging/StopWatchNotStartedException.java +++ /dev/null @@ -1,42 +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.logging; - -public class StopWatchNotStartedException extends RuntimeException { - - private static final long serialVersionUID = -4540164295822859408L; - - public StopWatchNotStartedException() { - super(); - } - - public StopWatchNotStartedException(String message) { - super(message); - } - - public StopWatchNotStartedException(Throwable cause) { - super(cause); - } - - public StopWatchNotStartedException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AAIIdentityMapParseException.java b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AAIIdentityMapParseException.java deleted file mode 100644 index bfc35406..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AAIIdentityMapParseException.java +++ /dev/null @@ -1,41 +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.parsers.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIIdentityMapParseException extends AAIException { - - private static final long serialVersionUID = -888876613879411865L; - - public AAIIdentityMapParseException(String message) { - super("AAI_3000", message); - } - - public AAIIdentityMapParseException(Throwable cause) { - super("AAI_3000",cause); - } - - public AAIIdentityMapParseException(String message, Throwable cause) { - super("AAI_3000", cause, message); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AmbiguousMapAAIException.java b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AmbiguousMapAAIException.java deleted file mode 100644 index 4917c14f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/AmbiguousMapAAIException.java +++ /dev/null @@ -1,41 +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.parsers.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class AmbiguousMapAAIException extends AAIException { - - private static final long serialVersionUID = -878581771971431246L; - - public AmbiguousMapAAIException(String message) { - super("AAI_6146", message); - } - - public AmbiguousMapAAIException(Throwable cause) { - super("AAI_6146",cause); - } - - public AmbiguousMapAAIException(String message, Throwable cause) { - super("AAI_6146", cause, message); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java b/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java deleted file mode 100644 index 8911f944..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/exceptions/DoesNotStartWithValidNamespaceException.java +++ /dev/null @@ -1,42 +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.parsers.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class DoesNotStartWithValidNamespaceException extends AAIException { - - private static final long serialVersionUID = -888876613879411865L; - - public DoesNotStartWithValidNamespaceException(String message) { - super("AAI_3000", message); - } - - public DoesNotStartWithValidNamespaceException(Throwable cause) { - super("AAI_3000",cause); - } - - public DoesNotStartWithValidNamespaceException(String message, Throwable cause) { - super("AAI_3000", cause, message); - } - -} - diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/LegacyQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/LegacyQueryParser.java deleted file mode 100644 index 5679fc90..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/LegacyQueryParser.java +++ /dev/null @@ -1,227 +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.parsers.query; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.parsers.uri.Parsable; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.parsers.uri.URIToObject; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.restcore.util.URITools; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.Map.Entry; - -/** - * The Class LegacyQueryParser. - */ -public class LegacyQueryParser extends QueryParser implements Parsable { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(LegacyQueryParser.class); - - private Introspector previous = null; - - /** - * Instantiates a new legacy query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - * @param uri the uri - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri) throws UnsupportedEncodingException, AAIException { - super(loader, queryBuilder, uri); - URIParser parser = new URIParser(loader, uri); - parser.parse(this); - } - - /** - * Instantiates a new legacy query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - * @param uri the uri - * @param queryParams the query params - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri, MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException { - super(loader, queryBuilder, uri); - URIParser parser = new URIParser(loader, uri, queryParams); - parser.parse(this); - } - - /** - * Instantiates a new legacy query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - */ - public LegacyQueryParser(Loader loader, QueryBuilder queryBuilder) { - super(loader, queryBuilder); - } - - /** - * @throws AAIException - * @{inheritDoc} - */ - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) throws AAIException { - if (previous != null) { - this.parentResourceType = previous.getDbName(); - queryBuilder.createEdgeTraversal(type, previous, obj); - } - if (previous == null) { - queryBuilder.createDBQuery(obj); - this.handleUriKeys(obj, uriKeys); - } else { - queryBuilder.createKeyQuery(obj); - this.handleUriKeys(obj, uriKeys); - } - previous = obj; - this.resultResource = obj.getDbName(); - } - - /** - * @{inheritDoc} - */ - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, boolean isFinalContainer) throws AAIException { - if (isFinalContainer) { - if (previous != null) { - this.parentResourceType = previous.getDbName(); - queryBuilder.createEdgeTraversal(type, previous, obj); - } - - if (previous == null) { - queryBuilder.createContainerQuery(obj); - queryBuilder.markParentBoundary(); - } - if (!uriKeys.isEmpty()) { - - try { - Introspector child = obj.newIntrospectorInstanceOfNestedProperty(obj.getChildName()); - this.handleUriKeys(child, uriKeys); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Skipping container child " + obj.getChildName() + " (Unknown Object)", e); - } - } - - this.resultResource = obj.getChildDBName(); - this.containerResource = obj.getName(); - } - } - private void handleUriKeys(Introspector obj, MultivaluedMap<String, String> uriKeys) throws AAIException { - for (String key : uriKeys.keySet()) { - //to validate whether this property exists - if (!obj.hasProperty(key)) { - throw new AAIException("AAI_3000", "property: " + key + " not found on " + obj.getDbName()); - } - - List<String> values = uriKeys.get(key); - String dbPropertyName = key; - Map<String, String> linkedProperties = new HashMap<>(); - final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(key); - if (metadata.containsKey(PropertyMetadata.DATA_LINK)) { - linkedProperties.put(key, metadata.get(PropertyMetadata.DATA_LINK)); - } - if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) { - dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS); - } - - if (!linkedProperties.containsKey(key)) { - if (values.size() > 1) { - queryBuilder.getVerticesByIndexedProperty(dbPropertyName, obj.castValueAccordingToSchema(key, values)); - } else { - queryBuilder.getVerticesByIndexedProperty(dbPropertyName, obj.castValueAccordingToSchema(key, values.get(0))); - } - } - handleLinkedProperties(obj, uriKeys, linkedProperties); - } - } - private void handleLinkedProperties(Introspector obj, MultivaluedMap<String, String> uriKeys, Map<String, String> linkedProperties) throws AAIException { - - QueryBuilder[] builders = new QueryBuilder[linkedProperties.keySet().size()]; - Set<Entry<String, String>> entrySet = linkedProperties.entrySet(); - int i = 0; - Iterator<Entry<String, String>> itr = entrySet.iterator(); - - while (itr.hasNext()) { - Entry<String, String> entry = itr.next(); - Introspector child; - try { - child = new URIToObject(this.latestLoader, new URI(URITools.replaceTemplates(obj, entry.getValue(), PropertyMetadata.DATA_LINK, true).orElse(""))).getEntity(); - } catch (IllegalArgumentException | UnsupportedEncodingException | URISyntaxException e) { - throw new AAIException("AAI_4000", e); - } - List<String> values = uriKeys.get(entry.getKey()); - QueryBuilder builder = queryBuilder.newInstance(); - builder.createEdgeTraversal(EdgeType.TREE, obj, child); - if (values.size() > 1) { - builder.getVerticesByIndexedProperty(entry.getKey(), obj.castValueAccordingToSchema(entry.getKey(), values)); - } else { - builder.getVerticesByIndexedProperty(entry.getKey(), obj.castValueAccordingToSchema(entry.getKey(), values.get(0))); - } - - builders[i] = builder; - i++; - } - - queryBuilder.where(builders); - - } - - /** - * @{inheritDoc} - */ - @Override - public void processNamespace(Introspector obj) { - - } - - /** - * @{inheritDoc} - */ - @Override - public String getCloudRegionTransform() { - return "add"; - } - - /** - * @{inheritDoc} - */ - @Override - public boolean useOriginalLoader() { - return false; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/ObjectNameQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/ObjectNameQueryParser.java deleted file mode 100644 index a1d8f740..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/ObjectNameQueryParser.java +++ /dev/null @@ -1,36 +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.parsers.query; - -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.query.builder.QueryBuilder; - -public class ObjectNameQueryParser extends QueryParser { - - public ObjectNameQueryParser(Loader loader, QueryBuilder queryBuilder, String objName) { - super(loader, queryBuilder); - this.resultResource = objName; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParser.java deleted file mode 100644 index ee4e3941..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParser.java +++ /dev/null @@ -1,146 +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.parsers.query; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.query.builder.QueryBuilder; - -import java.net.URI; - -/** - * The Class QueryParser. - */ -public abstract class QueryParser { - - protected Loader loader = null; - protected Loader latestLoader = null; - protected QueryBuilder<Vertex> queryBuilder = null; - - protected QueryBuilder<Vertex> parentQueryBuilder = null; - - protected URI uri = null; - - protected String resultResource = ""; - - protected String parentResourceType = ""; - - protected String containerResource = ""; - - /** - * Instantiates a new query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - * @param uri the uri - */ - protected QueryParser(Loader loader, QueryBuilder<Vertex> queryBuilder, URI uri) { - this.uri = uri; - this.queryBuilder = queryBuilder; - this.loader = loader; - this.latestLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); - } - - /** - * Instantiates a new query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - */ - protected QueryParser(Loader loader, QueryBuilder<Vertex> queryBuilder) { - this.queryBuilder = queryBuilder; - this.loader = loader; - this.latestLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); - } - - /** - * Gets the container type. - * - * @return the container type - */ - public String getContainerType() { - - return this.containerResource; - } - - /** - * Gets the parent result type. - * - * @return the parent result type - */ - public String getParentResultType() { - return this.parentResourceType; - } - - /** - * Gets the result type. - * - * @return the result type - */ - public String getResultType() { - return this.resultResource; - } - - /** - * Gets the query builder. - * - * @return the query builder - */ - public QueryBuilder<Vertex> getQueryBuilder() { - return this.queryBuilder; - } - - /** - * Gets the uri. - * - * @return the uri - */ - public URI getUri() { - return this.uri; - } - - /** - * Gets the parent query builder. - * - * @return the parent query builder - */ - public QueryBuilder<Vertex> getParentQueryBuilder() { - if (this.parentQueryBuilder != null) { - return this.parentQueryBuilder; - } else { - return this.queryBuilder; - } - } - - /** - * Checks if is dependent. - * - * @return true, if is dependent - */ - public boolean isDependent() { - return !this.queryBuilder.getQuery().toString().equals(this.queryBuilder.getParentQuery().getQuery().toString()); - } - -} - - diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParserStrategy.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParserStrategy.java deleted file mode 100644 index b0e6cc23..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/QueryParserStrategy.java +++ /dev/null @@ -1,91 +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.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.query.builder.QueryBuilder; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -/** - * The Class QueryParserStrategy. - */ -public abstract class QueryParserStrategy { - - protected Loader loader = null; - - protected QueryBuilder builder = null; - - /** - * Instantiates a new query parser strategy. - * - * @param loader the loader - * @param builder the builder - */ - public QueryParserStrategy(Loader loader, QueryBuilder builder) { - - this.loader = loader; - this.builder = builder; - } - - /** - * Builds the URI parser. - * - * @param uri the uri - * @return the query parser - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public abstract QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, AAIException; - - /** - * Builds the URI parser. - * - * @param uri the uri - * @param queryParams the query params - * @return the query parser - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public abstract QueryParser buildURIParser(URI uri,MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException; - - /** - * Builds the relationship parser. - * - * @param obj the obj - * @return the query parser - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public abstract QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException; - - /** - * Builds an ObjectNameQueryParser. - * - * @param objName - the name of the object type as used in the database - * @return - */ - public abstract QueryParser buildObjectNameParser(String objName); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/RelationshipQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/RelationshipQueryParser.java deleted file mode 100644 index fb4200e5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/RelationshipQueryParser.java +++ /dev/null @@ -1,65 +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.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.parsers.relationship.RelationshipToURI; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.serialization.db.EdgeRules; - -import java.io.UnsupportedEncodingException; - -/** - * The Class RelationshipQueryParser. - */ -public class RelationshipQueryParser extends LegacyQueryParser { - - private Introspector relationship = null; - - private ModelType modelType = null; - - private EdgeRules edgeRules = null; - - /** - * Instantiates a new relationship query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - * @param obj the obj - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public RelationshipQueryParser(Loader loader, QueryBuilder queryBuilder, Introspector obj) throws UnsupportedEncodingException, AAIException { - super(loader, queryBuilder); - this.relationship = obj; - this.modelType = obj.getModelType(); - this.edgeRules = EdgeRules.getInstance(); - RelationshipToURI rToUri = new RelationshipToURI(loader, obj); - this.uri = rToUri.getUri(); - URIParser parser = new URIParser(loader, uri); - parser.parse(this); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/TraversalStrategy.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/TraversalStrategy.java deleted file mode 100644 index 41064597..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/TraversalStrategy.java +++ /dev/null @@ -1,82 +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.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.query.builder.QueryBuilder; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -/** - * The Class TraversalStrategy. - */ -public class TraversalStrategy extends QueryParserStrategy { - - - /** - * Instantiates a new traversal strategy. - * - * @param loader the loader - * @param builder the builder - */ - public TraversalStrategy(Loader loader, QueryBuilder builder) { - super(loader, builder); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, AAIException { - return new LegacyQueryParser(loader, builder, uri); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException { - return new RelationshipQueryParser(loader, builder, obj); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildURIParser(URI uri, MultivaluedMap<String, String> queryParams) - throws UnsupportedEncodingException, AAIException { - return new LegacyQueryParser(loader, builder, uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildObjectNameParser(String objName) { - return new ObjectNameQueryParser(loader, builder, objName); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryParser.java deleted file mode 100644 index 4739aa47..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryParser.java +++ /dev/null @@ -1,57 +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.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.relationship.RelationshipToURI; -import org.openecomp.aai.query.builder.QueryBuilder; - -import java.io.UnsupportedEncodingException; - -/** - * The Class UniqueRelationshipQueryParser. - */ -public class UniqueRelationshipQueryParser extends UniqueURIQueryParser { - - - /** - * Instantiates a new unique relationship query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - * @param obj the obj - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - */ - public UniqueRelationshipQueryParser(Loader loader, QueryBuilder queryBuilder, Introspector obj) throws UnsupportedEncodingException, IllegalArgumentException, AAIException { - super(loader, queryBuilder); - RelationshipToURI rToUri = new RelationshipToURI(loader, obj); - UniqueURIQueryParser parser = new UniqueURIQueryParser(loader, queryBuilder, rToUri.getUri()); - this.containerResource = parser.getContainerType(); - this.resultResource = parser.getResultType(); - this.queryBuilder = parser.getQueryBuilder(); - this.parentQueryBuilder = parser.getParentQueryBuilder(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueStrategy.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueStrategy.java deleted file mode 100644 index 5668036f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueStrategy.java +++ /dev/null @@ -1,81 +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.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.query.builder.QueryBuilder; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; - -/** - * The Class UniqueStrategy. - */ -public class UniqueStrategy extends QueryParserStrategy { - - - - /** - * Instantiates a new unique strategy. - * - * @param loader the loader - * @param builder the builder - */ - public UniqueStrategy(Loader loader, QueryBuilder builder) { - super(loader, builder); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildURIParser(URI uri) throws UnsupportedEncodingException, IllegalArgumentException, AAIException { - return new UniqueURIQueryParser(loader, builder, uri); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildRelationshipParser(Introspector obj) throws UnsupportedEncodingException, AAIException { - return new UniqueRelationshipQueryParser(loader, builder, obj); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildURIParser(URI uri, MultivaluedMap<String, String> queryParams) - throws UnsupportedEncodingException, AAIException { - return new LegacyQueryParser(loader, builder, uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser buildObjectNameParser(String objName) { - return new ObjectNameQueryParser(loader, builder, objName); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueURIQueryParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueURIQueryParser.java deleted file mode 100644 index 64fc3df2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/query/UniqueURIQueryParser.java +++ /dev/null @@ -1,164 +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.parsers.query; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.uri.Parsable; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.parsers.uri.URIToDBKey; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriBuilder; -import java.io.UnsupportedEncodingException; -import java.net.URI; - - -/** - * The Class UniqueURIQueryParser. - */ -public class UniqueURIQueryParser extends QueryParser implements Parsable { - - - private URIToDBKey dbKeyParser = null; - - private Introspector previous = null; - - private boolean endsInContainer = false; - - private Introspector finalContainer = null; - - private String parentName = ""; - - /** - * Instantiates a new unique URI query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - * @param uri the uri - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - */ - public UniqueURIQueryParser(Loader loader, QueryBuilder queryBuilder, URI uri) throws UnsupportedEncodingException, IllegalArgumentException, AAIException { - super(loader, queryBuilder, uri); - URIParser parser = new URIParser(loader, uri); - parser.parse(this); - - if (!endsInContainer) { - this.dbKeyParser = new URIToDBKey(loader, uri); - String dbKey = (String)dbKeyParser.getResult(); - queryBuilder.getVerticesByIndexedProperty("aai-unique-key", dbKey); - queryBuilder.markParentBoundary(); - - if (!(parentName.equals("") || parentName.equals(this.resultResource))) { - URI parentUri = UriBuilder.fromPath(uri.getRawPath().substring(0, uri.getRawPath().indexOf(containerResource))).build(); - this.dbKeyParser = new URIToDBKey(loader, parentUri); - this.parentQueryBuilder = queryBuilder.newInstance().getVerticesByIndexedProperty("aai-unique-key", (String)dbKeyParser.getResult()); - this.parentResourceType = parentName; - } - this.containerResource = ""; - } else { - URI parentUri = UriBuilder.fromPath(uri.getRawPath().substring(0, uri.getRawPath().indexOf(this.finalContainer.getDbName()))).build(); - this.dbKeyParser = new URIToDBKey(loader, parentUri); - String dbKey = (String)dbKeyParser.getResult(); - this.parentResourceType = parentName; - - if (!dbKey.equals("")) { - queryBuilder.getVerticesByIndexedProperty("aai-unique-key", dbKey); - queryBuilder.markParentBoundary(); - queryBuilder.createEdgeTraversal(EdgeType.TREE, previous, finalContainer); - - } - - queryBuilder.createContainerQuery(finalContainer); - - - } - } - - - /** - * Instantiates a new unique URI query parser. - * - * @param loader the loader - * @param queryBuilder the query builder - */ - public UniqueURIQueryParser(Loader loader, QueryBuilder queryBuilder) { - super(loader, queryBuilder); - } - - /** - * @{inheritDoc} - */ - @Override - public void processNamespace(Introspector obj) { - - } - - /** - * @{inheritDoc} - */ - @Override - public String getCloudRegionTransform() { - return "add"; - } - - /** - * @{inheritDoc} - */ - @Override - public boolean useOriginalLoader() { - return false; - } - - - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) - throws AAIException { - this.resultResource = obj.getDbName(); - if (previous != null) { - this.parentName = previous.getDbName(); - } - this.previous = obj; - - } - - - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, - boolean isFinalContainer) throws AAIException { - this.containerResource = obj.getName(); - if (previous != null) { - this.parentName = previous.getDbName(); - } - if (isFinalContainer) { - this.endsInContainer = true; - this.resultResource = obj.getChildDBName(); - - this.finalContainer = obj; - } - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java b/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java deleted file mode 100644 index 873f7211..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/relationship/RelationshipToURI.java +++ /dev/null @@ -1,281 +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.parsers.relationship; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.parsers.exceptions.AAIIdentityMapParseException; -import org.openecomp.aai.parsers.exceptions.AmbiguousMapAAIException; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.AAIDirection; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.workarounds.LegacyURITransformer; - -import javax.ws.rs.core.UriBuilder; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; - -/** - * The Class RelationshipToURI. - */ -public class RelationshipToURI { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RelationshipToURI.class); - - private Introspector relationship = null; - - private Loader loader = null; - - private ModelType modelType = null; - - private EdgeRules edgeRules = null; - - private URI uri = null; - - private LegacyURITransformer urlTransform = null; - - /** - * Instantiates a new relationship to URI. - * - * @param loader the loader - * @param relationship the relationship - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public RelationshipToURI(Loader loader, Introspector relationship) throws UnsupportedEncodingException, AAIException { - this.relationship = relationship; - this.modelType = relationship.getModelType(); - this.edgeRules = EdgeRules.getInstance(); - this.loader = loader; - this.urlTransform = LegacyURITransformer.getInstance(); - - this.parse(); - - } - - /** - * Parses the. - * @throws - * - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - protected void parse() throws AAIException { - String relatedLink = (String)relationship.getValue("related-link"); - Optional<URI> result; - try { - if (loader.getVersion().compareTo(Version.v10) >= 0) { - result = processRelatedLink(relatedLink); - if (!result.isPresent()) { - result = processRelationshipData(); - } - } else { - result = processRelationshipData(); - if (!result.isPresent()) { - result = processRelatedLink(relatedLink); - } - } - if (result.isPresent()) { - this.uri = result.get(); - } else { - throw new AAIIdentityMapParseException("nothing to parse"); - } - } catch (AAIException e) { - throw e; - } catch (Exception e) { - throw new AAIIdentityMapParseException("Could not parse relationship-list object: " + e.getMessage(), e); - } - - } - - private Optional<URI> processRelationshipData() throws AAIException, UnsupportedEncodingException { - Optional<URI> result = Optional.empty(); - StringBuilder uriBuilder = new StringBuilder(); - List<Object> data = (List<Object>)relationship.getValue("relationship-data"); - Introspector wrapper; - String key; - String value; - String objectType; - String propertyName; - String topLevelType = null; - String[] split; - HashMap<String, Introspector> map = new HashMap<>(); - for (Object datum : data) { - wrapper = IntrospectorFactory.newInstance(modelType, datum); - key = (String)wrapper.getValue("relationship-key"); - value = (String)wrapper.getValue("relationship-value"); - split = key.split("\\."); - if (split == null || split.length != 2) { - throw new AAIIdentityMapParseException("incorrect format for key must be of the form {node-type}.{property-name}"); - } - //check node name ok - //check prop name ok - objectType = split[0]; - propertyName = split[1]; - - try { - Introspector wrappedObj = loader.introspectorFromName(objectType); - - if (!wrappedObj.hasProperty(propertyName)) { - throw new AAIIdentityMapParseException("invalid property name in map: " + propertyName); - } - if (map.containsKey(objectType)) { - wrappedObj = map.get(objectType); - } else { - map.put(objectType, wrappedObj); - } - if (wrappedObj.getValue(propertyName) == null) { - wrappedObj.setValue(propertyName, value); - } else { - throw new AmbiguousMapAAIException("cannot determine where key/value goes: " + propertyName + "/" + value); - } - - if (wrappedObj.getMetadata(ObjectMetadata.NAMESPACE) != null) { - if (topLevelType == null) { - topLevelType = objectType; - } else if (!topLevelType.equals(objectType)){ - throw new AmbiguousMapAAIException("found two top level nodes of different types: " + topLevelType + " and " + objectType); - } - } - } catch (AAIUnknownObjectException e) { - throw new AAIIdentityMapParseException("invalid object name in map: " + objectType, e); - } - - } - if (!map.isEmpty()) { - String startType = (String)relationship.getValue("related-to"); - List<String> nodeTypes = new ArrayList<>(); - nodeTypes.addAll(map.keySet()); - - String displacedType; - for (int i = 0; i < nodeTypes.size(); i++) { - if (nodeTypes.get(i).equals(startType)) { - displacedType = nodeTypes.set(nodeTypes.size() - 1, startType); - nodeTypes.set(i, displacedType); - break; - } - } - sortRelationships(nodeTypes, startType, 1); - int startTypeIndex = nodeTypes.indexOf(startType); - int topLevelIndex = 0; - if (topLevelType != null) { - topLevelIndex = nodeTypes.indexOf(topLevelType); - } - //remove additional types not needed if they are there - List<String> nodeTypesSubList = nodeTypes; - if (topLevelIndex != 0) { - nodeTypesSubList = nodeTypes.subList(topLevelIndex, startTypeIndex+1); - } - for (String type : nodeTypesSubList) { - uriBuilder.append(map.get(type).getURI()); - } - if (!nodeTypesSubList.isEmpty()) { - result = Optional.of(UriBuilder.fromPath(uriBuilder.toString()).build()); - } - } - return result; - } - - private Optional<URI> processRelatedLink(String relatedLink) throws URISyntaxException, UnsupportedEncodingException, AAIIdentityMapParseException { - Optional<URI> result = Optional.empty(); - if (relatedLink != null) { - URI resultUri = new URI(relatedLink); - String path = resultUri.toString(); - resultUri = UriBuilder.fromPath(resultUri.getRawPath()).build(); - URIParser uriParser = new URIParser(this.loader, resultUri); - try { - uriParser.validate(); - } catch (AAIException e) { - throw new AAIIdentityMapParseException("related link is invalid: " + relatedLink, e); - } - result = Optional.of(resultUri); - } - - return result; - } - - /** - * Sort relationships. - * - * @param data the data - * @param startType the start type - * @param i the i - * @return true, if successful - * @throws AAIException - */ - private boolean sortRelationships(List<String> data, String startType, int i) throws AAIException { - - if (i == data.size()) { - return true; - } - int j; - String objectType; - String displacedObject; - EdgeRule rule; - Direction direction; - for (j = (data.size() - i) - 1; j >= 0; j--) { - objectType = data.get(j); - try { - rule = edgeRules.getEdgeRule(EdgeType.TREE, startType, objectType); - direction = rule.getDirection(); - if (direction != null) { - if ((rule.getContains().equals(AAIDirection.OUT.toString()) && direction.equals(Direction.IN)) || (rule.getContains().equals(AAIDirection.IN.toString()) && direction.equals(Direction.OUT))) { - displacedObject = data.set((data.size() - i) - 1, data.get(j)); - data.set(j, displacedObject); - if (sortRelationships(data, objectType, i+1)) { - return true; - } else { - //continue to process - } - } - } - } catch (AAIException e) { - //ignore exceptions generated - continue; - } - } - - - return false; - } - - /** - * Gets the uri. - * - * @return the uri - */ - public URI getUri() { - return uri; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/Parsable.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/Parsable.java deleted file mode 100644 index 2488980e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/Parsable.java +++ /dev/null @@ -1,72 +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.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; - -/** - * The Interface Parsable. - */ -public interface Parsable { - - /** - * - * @param obj - * @param type - * @param uriKeys - * @throws AAIException - */ - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) throws AAIException; - /** - * Process container. - * - * @param obj the obj - * @param uriKeys the uri keys - * @param isFinalContainer the is final container - * @throws AAIException the AAI exception - */ - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, boolean isFinalContainer) throws AAIException; - - /** - * Process namespace. - * - * @param obj the obj - */ - public void processNamespace(Introspector obj); - - /** - * Gets the cloud region transform. - * - * @return the cloud region transform - */ - public String getCloudRegionTransform(); - - /** - * Use original loader. - * - * @return true, if successful - */ - public boolean useOriginalLoader(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java deleted file mode 100644 index 4df650de..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIParser.java +++ /dev/null @@ -1,278 +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.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.parsers.exceptions.DoesNotStartWithValidNamespaceException; -import org.openecomp.aai.rest.RestTokens; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.util.AAIConfig; -import org.springframework.web.util.UriUtils; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.UriBuilder; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.Set; - - -/** - * The Class URIParser. - */ -public class URIParser { - - private URI uri = null; - - protected Loader loader = null; - - protected Loader originalLoader = null; - - private URI originalURI = null; - - private MultivaluedMap<String, String> queryParams = null; - - - /** - * Instantiates a new URI parser. - * - * @param loader the loader - * @param uri the uri - */ - public URIParser(Loader loader, URI uri) { - this.uri = uri; - - String currentVersion = "v7"; - this.originalLoader = loader; - try { - currentVersion = AAIConfig.get("aai.default.api.version"); - } catch (AAIException e) { - ErrorLogHelper.logException(e); - } - - //Load the latest version because we need it for cloud region - - this.loader = loader; - } - - /** - * Instantiates a new URI parser. - * - * @param loader the loader - * @param uri the uri - * @param queryParams the query params - */ - public URIParser(Loader loader, URI uri, MultivaluedMap<String, String> queryParams) { - this(loader, uri); - this.queryParams = queryParams; - } - - public Loader getLoader() { - - return this.loader; - - } - - /** - * Gets the original URI. - * - * @return the original URI - */ - public URI getOriginalURI() { - return this.originalURI; - } - - /** - * Parses the. - * - * @param p the p - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public void parse(Parsable p) throws UnsupportedEncodingException, AAIException { - try { - boolean isRelative = false; - uri = this.trimURI(uri); - uri = handleCloudRegion(p.getCloudRegionTransform(), uri); - if (p.useOriginalLoader()) { - this.loader = this.originalLoader; - } - this.originalURI = UriBuilder.fromPath(uri.getRawPath()).build(); - if (uri.getRawPath().startsWith("./")) { - uri = new URI(uri.getRawPath().replaceFirst("\\./", "")); - isRelative = true; - } - String[] parts = uri.getRawPath().split("/"); - Introspector validNamespaces = loader.introspectorFromName("inventory"); - Set<String> keys = null; - String part = ""; - Introspector previousObj = null; - EdgeType type = EdgeType.TREE; - for (int i = 0; i < parts.length;) { - part = parts[i]; - Introspector introspector = null; - if (part.equals(RestTokens.COUSIN.toString())) { - if (i == parts.length-1) { - throw new AAIException("AAI_3000", uri + " not a valid path. Cannot end in " + RestTokens.COUSIN); - } - introspector = loader.introspectorFromName(parts[i+1]); - if(null == previousObj) { - throw new AAIException("AAI_3001"); - } - if (previousObj.isContainer() && introspector.isContainer()) { - throw new AAIException("AAI_3000", uri + " not a valid path. Cannot chain plurals together"); - } - MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>(); - if (i == parts.length-2 && queryParams != null) { - Set<String> queryKeys = queryParams.keySet(); - for (String key : queryKeys) { - uriKeys.put(key, queryParams.get(key)); - - } - } - if (introspector.isContainer()) { - boolean isFinalContainer = i == parts.length-2; - p.processContainer(introspector, EdgeType.COUSIN, uriKeys, isFinalContainer); - } - previousObj = introspector; - type = EdgeType.COUSIN; - i+=2; - continue; - } - introspector = loader.introspectorFromName(part); - if (introspector != null) { - - //previous has current as property - if (previousObj != null && !previousObj.hasChild(introspector) && !previousObj.getDbName().equals("nodes")) { - throw new AAIException("AAI_3001", uri + " not a valid path. " + part + " not valid"); - } else if (previousObj == null) { - String abstractType = introspector.getMetadata(ObjectMetadata.ABSTRACT); - if (abstractType == null) { - abstractType = ""; - } - //first time through, make sure it starts from a namespace - //ignore abstract types - if (!isRelative && !abstractType.equals("true") && !validNamespaces.hasChild(introspector)) { - throw new DoesNotStartWithValidNamespaceException( uri + " not a valid path. It does not start from a valid namespace"); - } - } - - keys = introspector.getKeys(); - if (keys.size() > 0) { - MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>(); - i++; - if (i == parts.length && queryParams != null) { - Set<String> queryKeys = queryParams.keySet(); - for (String key : queryKeys) { - uriKeys.put(key, queryParams.get(key)); - } - } else { - for (String key : keys) { - part = UriUtils.decode(parts[i], "UTF-8"); - - introspector.setValue(key, part); - - //skip this for further processing - i++; - } - } - - p.processObject(introspector, type, uriKeys); - type = EdgeType.TREE; - } else if (introspector.isContainer()) { - boolean isFinalContainer = i == parts.length-1; - MultivaluedMap<String, String> uriKeys = new MultivaluedHashMap<>(); - - if (isFinalContainer && queryParams != null) { - Set<String> queryKeys = queryParams.keySet(); - for (String key : queryKeys) { - uriKeys.put(key, queryParams.get(key)); - - } - } - p.processContainer(introspector, type, uriKeys, isFinalContainer); - - i++; - } else { - p.processNamespace(introspector); - //namespace case - i++; - } - previousObj = introspector; - } else { - //invalid item found should log - //original said bad path - throw new AAIException("AAI_3001", "invalid item found in path: " + part); - } - } - } catch (AAIException e) { - throw e; - } catch (Exception e) { - throw new AAIException("AAI_3001", e); - } - } - - public boolean validate() throws UnsupportedEncodingException, AAIException { - this.parse(new URIValidate()); - return true; - } - /** - * Handle cloud region. - * - * @param action the action - * @param uri the uri - * @return the uri - */ - protected URI handleCloudRegion(String action, URI uri) { - - return uri; - - } - - /** - * Trim URI. - * - * @param uri the uri - * @return the uri - */ - protected URI trimURI(URI uri) { - - String result = uri.getRawPath(); - if (result.startsWith("/")) { - result = result.substring(1, result.length()); - } - - if (result.endsWith("/")) { - result = result.substring(0, result.length() - 1); - } - - result = result.replaceFirst("aai/v\\d+/", ""); - - return UriBuilder.fromPath(result).build(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToDBKey.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToDBKey.java deleted file mode 100644 index 6aa28e27..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToDBKey.java +++ /dev/null @@ -1,122 +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.parsers.uri; - -import com.google.common.base.Joiner; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -/** - * Creates a Unique database key from a URI - * - * The key is of the form node-type/key(s). - */ -public class URIToDBKey implements Parsable { - - - private List<String> dbKeys = new ArrayList<>(); - - /** - * Instantiates a new URI to DB key. - * - * @param loader the loader - * @param uri the uri - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - public URIToDBKey(Loader loader, URI uri) throws IllegalArgumentException, AAIException, UnsupportedEncodingException { - - URIParser parser = new URIParser(loader, uri); - parser.parse(this); - } - /* - public URIToDBKey(Version version, String uri) throws IllegalArgumentException { - - super(version, uri); - try { - context = ModelInjestor.getInstance().getContextForVersion(version); - if (context == null) { - throw new IllegalArgumentException("could not find a context for version: " + version); - } - this.parse(); - } catch (Exception e) { - throw new IllegalArgumentException("uri not valid against our model: " + uri); - } - }*/ - - /** - * @{inheritDoc} - */ - @Override - public void processNamespace(Introspector obj) { - - } - - /** - * @{inheritDoc} - */ - @Override - public String getCloudRegionTransform() { - return "add"; - } - - /** - * Gets the result. - * - * @return the result - */ - public Object getResult() { - return Joiner.on("/").join(this.dbKeys); - } - - /** - * @{inheritDoc} - */ - @Override - public boolean useOriginalLoader() { - return false; - } - - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) - throws AAIException { - - dbKeys.add(obj.getDbName()); - - for (String key : uriKeys.keySet()) { - dbKeys.add(uriKeys.getFirst(key).toString()); - } - } - - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, - boolean isFinalContainer) throws AAIException { - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToExtensionInformation.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToExtensionInformation.java deleted file mode 100644 index d32facfa..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToExtensionInformation.java +++ /dev/null @@ -1,164 +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.parsers.uri; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Joiner; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.restcore.HttpMethod; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -/** - * The Class URIToExtensionInformation. - */ -public class URIToExtensionInformation implements Parsable { - - private String namespace = ""; - - private String methodName = ""; - - private String topObject = ""; - - private List<String> pieces = null; - - /** - * Instantiates a new URI to extension information. - * - * @param loader the loader - * @param uri the uri - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - public URIToExtensionInformation(Loader loader, URI uri) throws IllegalArgumentException, AAIException, UnsupportedEncodingException { - pieces = new ArrayList<>(); - URIParser parser = new URIParser(loader, uri); - parser.parse(this); - - this.methodName = Joiner.on("").join(this.pieces); - } - - /** - * @{inheritDoc} - */ - @Override - public void processNamespace(Introspector obj) { - this.namespace = CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, obj.getDbName()); - pieces.add(toUpperCamel(obj.getDbName())); - - } - - /** - * @{inheritDoc} - */ - @Override - public String getCloudRegionTransform() { - return "remove"; - } - - /** - * @{inheritDoc} - */ - @Override - public boolean useOriginalLoader() { - return true; - } - - /** - * Gets the namespace. - * - * @return the namespace - */ - public String getNamespace() { - return this.namespace; - } - - /** - * Gets the top object. - * - * @return the top object - */ - public String getTopObject() { - return this.topObject; - } - - /** - * Gets the method name. - * - * @param httpMethod the http method - * @param isPreprocess the is preprocess - * @return the method name - */ - public String getMethodName(HttpMethod httpMethod, boolean isPreprocess) { - String result = "Dynamic"; - if (httpMethod.equals(HttpMethod.PUT)) { - result += "Add"; - } else if (httpMethod.equals(HttpMethod.DELETE)) { - result += "Del"; - } else { - throw new IllegalArgumentException("http method not supported: " + httpMethod); - } - result += this.methodName; - - if (isPreprocess) { - result += "PreProc"; - } else { - result += "PostProc"; - } - return result; - } - - /** - * To upper camel. - * - * @param name the name - * @return the string - */ - private String toUpperCamel(String name) { - String result = ""; - result = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, name); - return result; - } - - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) - throws AAIException { - String upperCamel = toUpperCamel(obj.getDbName()); - if (topObject.equals("")) { - topObject = upperCamel; - } - pieces.add(upperCamel); - } - - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, - boolean isFinalContainer) throws AAIException { - pieces.add(toUpperCamel(obj.getName())); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java deleted file mode 100644 index decd803f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToObject.java +++ /dev/null @@ -1,220 +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.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.HashMap; -import java.util.List; - -/** - * Given a URI this class returns an object, or series of nested objects - * with their keys populated based off the values in the URI. - * - * It populates the keys in the order they are listed in the model. - * - - * - */ -public class URIToObject implements Parsable { - - - private Introspector topEntity = null; - - private String topEntityName = null; - - private String entityName = null; - - private Introspector entity = null; - - private Introspector previous = null; - - private List<Object> parentList = null; - - private Version version = null; - private Loader loader = null; - private final HashMap<String, Introspector> relatedObjects; - - /** - * Instantiates a new URI to object. - * - * @param loader the loader - * @param uri the uri - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - public URIToObject(Loader loader, URI uri) throws AAIException, UnsupportedEncodingException { - - URIParser parser = new URIParser(loader, uri); - this.relatedObjects = new HashMap<>(); - - parser.parse(this); - this.loader = parser.getLoader(); - this.version = loader.getVersion(); - } - public URIToObject(Loader loader, URI uri, HashMap<String, Introspector> relatedObjects) throws AAIException, UnsupportedEncodingException { - - URIParser parser = new URIParser(loader, uri); - this.relatedObjects = relatedObjects; - - parser.parse(this); - this.loader = parser.getLoader(); - this.version = loader.getVersion(); - - } - - /** - * @{inheritDoc} - */ - @Override - public void processNamespace(Introspector obj) { - - } - - /** - * @{inheritDoc} - */ - @Override - public String getCloudRegionTransform() { - return "add"; - } - - /** - * @{inheritDoc} - */ - @Override - public boolean useOriginalLoader() { - // TODO Auto-generated method stub - return false; - } - - /** - * Gets the top entity. - * - * @return the top entity - */ - public Introspector getTopEntity() { - return this.topEntity; - } - - /** - * Gets the entity. - * - * @return the entity - */ - public Introspector getEntity() { - return this.entity; - } - - /** - * Gets the parent list. - * - * @return the parent list - */ - public List<Object> getParentList() { - return this.parentList; - } - - /** - * Gets the entity name. - * - * @return the entity name - */ - public String getEntityName() { - return this.entityName; - } - - /** - * Gets the top entity name. - * - * @return the top entity name - */ - public String getTopEntityName() { - return this.topEntityName; - } - - /** - * Gets the object version. - * - * @return the object version - */ - public Version getObjectVersion() { - return this.loader.getVersion(); - } - public Loader getLoader() { - return this.loader; - } - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) - throws AAIException { - - if (this.entityName == null) { - this.topEntityName = obj.getDbName(); - this.topEntity = obj; - } - this.entityName = obj.getDbName(); - this.entity = obj; - this.parentList = (List<Object>)this.previous.getValue(obj.getName()); - this.parentList.add(entity.getUnderlyingObject()); - - for (String key : uriKeys.keySet()) { - entity.setValue(key, uriKeys.getFirst(key)); - } - try { - if (relatedObjects.containsKey(entity.getObjectId())) { - Introspector relatedObject = relatedObjects.get(entity.getObjectId()); - String nameProp = relatedObject.getMetadata(ObjectMetadata.NAME_PROPS); - if (nameProp == null) { - nameProp = ""; - } - if (nameProp != null && !nameProp.equals("")) { - String[] nameProps = nameProp.split(","); - for (String prop : nameProps) { - entity.setValue(prop, relatedObject.getValue(prop)); - } - } - } - } catch (UnsupportedEncodingException e) { - } - this.previous = entity; - } - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, - boolean isFinalContainer) throws AAIException { - this.previous = obj; - - if (this.entity != null) { - this.entity.setValue(obj.getName(), obj.getUnderlyingObject()); - } else { - this.entity = obj; - this.topEntity = obj; - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToRelationshipObject.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToRelationshipObject.java deleted file mode 100644 index a5429000..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIToRelationshipObject.java +++ /dev/null @@ -1,169 +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.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.util.AAIApiServerURLBase; -import org.openecomp.aai.workarounds.LegacyURITransformer; - -import javax.ws.rs.core.MultivaluedMap; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - -/** - * Given a URI a Relationship Object is returned. - * - * The relationship-data objects are created from the keys in the model. - * The keys are processed in the order they appear in the model. - - * - */ -public class URIToRelationshipObject implements Parsable { - - private Introspector result = null; - - private LegacyURITransformer uriTransformer = null; - - private Version originalVersion = null; - - private Introspector relationship = null; - - private Loader loader = null; - - private String baseURL; - - private final URI uri; - /** - * Instantiates a new URI to relationship object. - * - * @param loader the loader - * @param uri the uri - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws MalformedURLException the malformed URL exception - */ - public URIToRelationshipObject(Loader loader, URI uri) throws AAIException { - - this.loader = loader; - uriTransformer = LegacyURITransformer.getInstance(); - originalVersion = loader.getVersion(); - - try { - relationship = loader.introspectorFromName("relationship"); - } catch (AAIUnknownObjectException e1) { - throw new RuntimeException("Fatal error - could not load relationship object!", e1); - } - - this.baseURL = AAIApiServerURLBase.get(originalVersion); - this.uri = uri; - - } - - public URIToRelationshipObject(Loader loader, URI uri, String baseURL) throws AAIException { - this(loader, uri); - - if (baseURL != null) { - this.baseURL = baseURL; - } - } - - - /** - * @{inheritDoc} - */ - @Override - public String getCloudRegionTransform(){ - return "remove"; - } - - /** - * @{inheritDoc} - */ - @Override - public void processNamespace(Introspector obj) { - - } - - /** - * @{inheritDoc} - */ - @Override - public boolean useOriginalLoader() { - return true; - } - - /** - * Gets the result. - * - * @return the result - * @throws AAIException - * @throws UnsupportedEncodingException - * @throws URISyntaxException - */ - public Introspector getResult() throws UnsupportedEncodingException, AAIException, URISyntaxException { - URIParser parser = new URIParser(this.loader, this.uri); - parser.parse(this); - URI originalUri = parser.getOriginalURI(); - - URI relatedLink = new URI(this.baseURL + this.originalVersion + "/" + originalUri); - this.relationship.setValue("related-link", relatedLink); - if (this.originalVersion.compareTo(Version.v10) >= 0) { - //only return the path section of the URI past v10 - relatedLink = new URI(relatedLink.getRawPath()); - } - - this.relationship.setValue("related-link", relatedLink.toString()); - - this.result = relationship; - return this.result; - } - - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) - throws AAIException { - for (String key : obj.getKeys()) { - try { - Introspector data = loader.introspectorFromName("relationship-data"); - data.setValue("relationship-key", obj.getDbName() + "." + key); - data.setValue("relationship-value", obj.getValue(key)); - - ((List<Object>)relationship.getValue("relationship-data")).add(data.getUnderlyingObject()); - } catch (AAIUnknownObjectException e) { - throw new RuntimeException("Fatal error - relationship-data object not found!"); - } - } - relationship.setValue("related-to", obj.getDbName()); - } - - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, - boolean isFinalContainer) throws AAIException { - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIValidate.java b/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIValidate.java deleted file mode 100644 index b7c0958c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/parsers/uri/URIValidate.java +++ /dev/null @@ -1,63 +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.parsers.uri; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.serialization.db.EdgeType; - -import javax.ws.rs.core.MultivaluedMap; - -class URIValidate implements Parsable { - - @Override - public void processNamespace(Introspector obj) { - //NO-OP - //just want to make sure this URI has valid tokens - - } - - @Override - public String getCloudRegionTransform() { - return "none"; - } - - @Override - public boolean useOriginalLoader() { - - return true; - } - - @Override - public void processObject(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys) - throws AAIException { - //NO-OP - //just want to make sure this URI has valid tokens - } - - @Override - public void processContainer(Introspector obj, EdgeType type, MultivaluedMap<String, String> uriKeys, - boolean isFinalContainer) throws AAIException { - //NO-OP - //just want to make sure this URI has valid tokens - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/GraphTraversalBuilder.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GraphTraversalBuilder.java deleted file mode 100644 index ecaadba2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GraphTraversalBuilder.java +++ /dev/null @@ -1,655 +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.query.builder; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.process.traversal.P; -import org.apache.tinkerpop.gremlin.process.traversal.Traversal; -import org.apache.tinkerpop.gremlin.process.traversal.Traversal.Admin; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -/** - * The Class GraphTraversalBuilder. - */ -public abstract class GraphTraversalBuilder<E> extends QueryBuilder<E> { - - protected GraphTraversal<Vertex, E> traversal = null; - protected Admin<Vertex, E> completeTraversal = null; - private EdgeRules edgeRules = EdgeRules.getInstance(); - - protected int parentStepIndex = 0; - protected int containerStepIndex = 0; - protected int stepIndex = 0; - - /** - * Instantiates a new graph traversal builder. - * - * @param loader the loader - */ - public GraphTraversalBuilder(Loader loader, GraphTraversalSource source) { - super(loader, source); - - traversal = (GraphTraversal<Vertex, E>) __.<E>start(); - - } - - /** - * Instantiates a new graph traversal builder. - * - * @param loader the loader - * @param start the start - */ - public GraphTraversalBuilder(Loader loader, GraphTraversalSource source, Vertex start) { - super(loader, source, start); - - traversal = (GraphTraversal<Vertex, E>) __.__(start); - - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, Object value) { - - return this.getVerticesByProperty(key, value); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, List<?> values) { - return this.getVerticesByProperty(key, values); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByProperty(String key, Object value) { - - //this is because the index is registered as an Integer - value = this.correctObjectType(value); - - traversal.has(key, value); - - stepIndex++; - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByProperty(final String key, final List<?> values) { - - //this is because the index is registered as an Integer - List<Object> correctedValues = new ArrayList<>(); - for (Object item : values) { - correctedValues.add(this.correctObjectType(item)); - } - - traversal.has(key, P.within(correctedValues)); - - stepIndex++; - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) { - traversal.has(parentKey, parentValue).has(AAIProperties.NODE_TYPE, childType); - stepIndex++; - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getTypedVerticesByMap(String type, LinkedHashMap<String, String> map) { - - for (String key : map.keySet()) { - traversal.has(key, map.get(key)); - stepIndex++; - } - traversal.has(AAIProperties.NODE_TYPE, type); - stepIndex++; - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createDBQuery(Introspector obj) { - this.createKeyQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createKeyQuery(Introspector obj) { - Set<String> keys = obj.getKeys(); - Object val; - for (String key : keys) { - val = obj.getValue(key); - Optional<String> metadata = obj.getPropertyMetadata(key, PropertyMetadata.DB_ALIAS); - if (metadata.isPresent()) { - //use the db name for the field rather than the object model - key = metadata.get(); - } - if (val != null) { - //this is because the index is registered as an Integer - if (val.getClass().equals(Long.class)) { - traversal.has(key,new Integer(val.toString())); - } else { - traversal.has(key, val); - } - stepIndex++; - } - } - return (QueryBuilder<Vertex>) this; - } - - @Override - public QueryBuilder<Vertex> exactMatchQuery(Introspector obj) { - this.createKeyQuery(obj); - allPropertiesQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder<Vertex>) this; - } - - private void allPropertiesQuery(Introspector obj) { - Set<String> props = obj.getProperties(); - Set<String> keys = obj.getKeys(); - Object val; - for (String prop : props) { - if (obj.isSimpleType(prop) && !keys.contains(prop)) { - val = obj.getValue(prop); - if (val != null) { - Optional<String> metadata = obj.getPropertyMetadata(prop, PropertyMetadata.DB_ALIAS); - if (metadata.isPresent()) { - //use the db name for the field rather than the object model - prop = metadata.get(); - } - //this is because the index is registered as an Integer - if (val.getClass().equals(Long.class)) { - traversal.has(prop,new Integer(val.toString())); - } else { - traversal.has(prop, val); - } - stepIndex++; - } - } - } - } - - /** - * @{inheritDoc} - */ - @Override - - public QueryBuilder<Vertex> createContainerQuery(Introspector obj) { - String type = obj.getChildDBName(); - String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT); - if (abstractType != null) { - String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(","); - traversal.has(AAIProperties.NODE_TYPE, P.within(inheritors)); - } else { - traversal.has(AAIProperties.NODE_TYPE, type); - } - stepIndex++; - markContainer(); - return (QueryBuilder<Vertex>) this; - } - - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String isAbstractType = parent.getMetadata(ObjectMetadata.ABSTRACT); - if ("true".equals(isAbstractType)) { - markParentBoundary(); - traversal.union(handleAbstractEdge(type, parent, child)); - stepIndex += 1; - } else { - this.edgeQueryToVertex(type, parent, child); - } - return (QueryBuilder<Vertex>) this; - - } - - private Traversal<Vertex, Vertex>[] handleAbstractEdge(EdgeType type, Introspector abstractParent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String childName = child.getDbName(); - String inheritorMetadata = abstractParent.getMetadata(ObjectMetadata.INHERITORS); - String[] inheritors = inheritorMetadata.split(","); - Traversal<Vertex, Vertex>[] unionTraversals = new Traversal[inheritors.length]; - int traversalIndex = 0; - for (int i = 0; i < inheritors.length; i++) { - String inheritor = inheritors[i]; - if (edgeRules.hasEdgeRule(inheritor, childName) || edgeRules.hasEdgeRule(childName, inheritor)) { - EdgeRule rule = edgeRules.getEdgeRule(type, inheritor, childName); - GraphTraversal<Vertex, Vertex> innerTraversal = __.start(); - if (rule.getDirection().equals(Direction.OUT)) { - innerTraversal.out(rule.getLabel()); - } else { - innerTraversal.in(rule.getLabel()); - } - innerTraversal.has(AAIProperties.NODE_TYPE, childName); - unionTraversals[traversalIndex] = innerTraversal; - traversalIndex++; - } - } - if (traversalIndex < inheritors.length) { - Traversal<Vertex, Vertex>[] temp = Arrays.copyOfRange(unionTraversals, 0, traversalIndex); - unionTraversals = temp; - } - return unionTraversals; - } - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - - String nodeType = parent.<String>property(AAIProperties.NODE_TYPE).orElse(null); - Introspector parentObj = loader.introspectorFromName(nodeType); - this.edgeQueryToVertex(type, parentObj, child); - return (QueryBuilder<Vertex>) this; - - } - - @Override - public QueryBuilder<Edge> getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException { - Introspector outObj = loader.introspectorFromName(outNodeType); - Introspector inObj = loader.introspectorFromName(inNodeType); - this.edgeQuery(type, outObj, inObj); - - return (QueryBuilder<Edge>)this; - - } - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> union(QueryBuilder... builder) { - GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length]; - for (int i = 0; i < builder.length; i++) { - traversals[i] = (GraphTraversal<Vertex, Vertex>)builder[i].getQuery(); - } - this.traversal.union(traversals); - stepIndex++; - - return this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> where(QueryBuilder... builder) { - GraphTraversal<Vertex, Vertex>[] traversals = new GraphTraversal[builder.length]; - for (int i = 0; i < builder.length; i++) { - this.traversal.where((GraphTraversal<Vertex, Vertex>)builder[i].getQuery()); - stepIndex++; - } - - return this; - } - - @Override - public QueryBuilder<E> store(String name) { - - this.traversal.store(name); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> cap(String name) { - this.traversal.cap(name); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> unfold() { - this.traversal.unfold(); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> dedup() { - - this.traversal.dedup(); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> emit() { - - this.traversal.emit(); - stepIndex++; - - return this; - - } - - @Override - public QueryBuilder<E> repeat(QueryBuilder<E> builder) { - - this.traversal.repeat((GraphTraversal<Vertex, E>)builder.getQuery()); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> until(QueryBuilder<E> builder) { - this.traversal.until((GraphTraversal<Vertex,E>)builder.getQuery()); - stepIndex++; - - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public QueryBuilder<E> simplePath(){ - this.traversal.simplePath(); - stepIndex++; - return this; - } - - @Override - public QueryBuilder<Edge> outE() { - this.traversal.outE(); - stepIndex++; - return (QueryBuilder<Edge>)this; - } - - @Override - public QueryBuilder<Edge> inE() { - this.traversal.inE(); - stepIndex++; - return (QueryBuilder<Edge>)this; - } - - @Override - public QueryBuilder<Vertex> outV() { - this.traversal.outV(); - stepIndex++; - return (QueryBuilder<Vertex>)this; - } - - @Override - public QueryBuilder<Vertex> inV() { - this.traversal.inV(); - stepIndex++; - return (QueryBuilder<Vertex>)this; - } - - @Override - public QueryBuilder<E> as(String name) { - this.traversal.as(name); - - stepIndex++; - return this; - } - - @Override - public QueryBuilder<E> not(QueryBuilder<E> builder) { - this.traversal.not(builder.getQuery()); - - stepIndex++; - return this; - } - - @Override - public QueryBuilder<E> select(String name) { - this.traversal.select(name); - - stepIndex++; - - return this; - } - - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQueryToVertex(EdgeType type, Introspector outObj, Introspector inObj) throws AAIException, NoEdgeRuleFoundException { - String outType = outObj.getDbName(); - String inType = inObj.getDbName(); - - if (outObj.isContainer()) { - outType = outObj.getChildDBName(); - } - if (inObj.isContainer()) { - inType = inObj.getChildDBName(); - } - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - traversal.out(rule.getLabel()); - } else { - traversal.in(rule.getLabel()); - } - stepIndex++; - this.createContainerQuery(inObj); - - } - - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQuery(EdgeType type, Introspector outObj, Introspector inObj) throws AAIException, NoEdgeRuleFoundException { - String outType = outObj.getDbName(); - String inType = inObj.getDbName(); - - if (outObj.isContainer()) { - outType = outObj.getChildDBName(); - } - if (inObj.isContainer()) { - inType = inObj.getChildDBName(); - } - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - traversal.outE(rule.getLabel()); - } else { - traversal.inE(rule.getLabel()); - } - stepIndex++; - - } - - @Override - public QueryBuilder<E> limit(long amount) { - traversal.limit(amount); - return this; - } - - /** - * @{inheritDoc} - */ - @Override - public <E2> E2 getQuery() { - return (E2)this.traversal; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> getParentQuery() { - - return cloneQueryAtStep(parentStepIndex); - } - - @Override - public QueryBuilder<E> getContainerQuery() { - - if (this.parentStepIndex == 0) { - return removeQueryStepsBetween(0, containerStepIndex); - } else { - return cloneQueryAtStep(containerStepIndex); - } - } - - /** - * @{inheritDoc} - */ - @Override - public void markParentBoundary() { - parentStepIndex = stepIndex; - } - - @Override - public void markContainer() { - containerStepIndex = stepIndex; - } - - - /** - * @{inheritDoc} - */ - @Override - public Vertex getStart() { - return this.start; - } - - protected int getParentStepIndex() { - return parentStepIndex; - } - - protected int getContainerStepIndex() { - return containerStepIndex; - } - - protected int getStepIndex() { - return stepIndex; - } - - protected abstract QueryBuilder<E> cloneQueryAtStep(int index); - /** - * end is exclusive - * - * @param start - * @param end - * @return - */ - protected abstract QueryBuilder<E> removeQueryStepsBetween(int start, int end); - - private void executeQuery() { - - Admin admin; - if (start != null) { - this.completeTraversal = traversal.asAdmin(); - } else { - admin = source.V().asAdmin(); - TraversalHelper.insertTraversal(admin.getEndStep(), traversal.asAdmin(), admin); - - this.completeTraversal = (Admin<Vertex, E>) admin; - - } - - - } - - @Override - public boolean hasNext() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return this.completeTraversal.hasNext(); - } - - @Override - public E next() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return this.completeTraversal.next(); - } - - @Override - public List<E> toList() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return this.completeTraversal.toList(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinQueryBuilder.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinQueryBuilder.java deleted file mode 100644 index b151d9d8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinQueryBuilder.java +++ /dev/null @@ -1,567 +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.query.builder; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.restcore.search.GremlinGroovyShellSingleton; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.EdgeRule; -import org.openecomp.aai.serialization.db.EdgeRules; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -import com.google.common.base.Joiner; - -/** - * The Class GremlinQueryBuilder. - */ -public abstract class GremlinQueryBuilder<E> extends QueryBuilder<E> { - - private EdgeRules edgeRules = EdgeRules.getInstance(); - private GremlinGroovyShellSingleton gremlinGroovy = GremlinGroovyShellSingleton.getInstance(); - private GraphTraversal<?, ?> completeTraversal = null; - protected List<String> list = null; - - protected int parentStepIndex = 0; - protected int containerStepIndex = 0; - protected int stepIndex = 0; - - /** - * Instantiates a new gremlin query builder. - * - * @param loader the loader - */ - public GremlinQueryBuilder(Loader loader, GraphTraversalSource source) { - super(loader, source); - list = new ArrayList<String>(); - } - - /** - * Instantiates a new gremlin query builder. - * - * @param loader the loader - * @param start the start - */ - public GremlinQueryBuilder(Loader loader, GraphTraversalSource source, Vertex start) { - super(loader, source, start); - list = new ArrayList<String>(); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createDBQuery(Introspector obj) { - this.createKeyQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder<Vertex>) this; - } - - @Override - public QueryBuilder<Vertex> exactMatchQuery(Introspector obj) { - // TODO not implemented because this is implementation is no longer used - this.createKeyQuery(obj); - //allPropertiesQuery(obj); - this.createContainerQuery(obj); - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, Object value) { - return this.getVerticesByProperty(key, value); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, List<?> values) { - return this.getVerticesByProperty(key, values); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByProperty(String key, Object value) { - - String term = ""; - if (value != null && !value.getClass().getName().equals("java.lang.String")) { - term = value.toString(); - } else { - term = "'" + value + "'"; - } - list.add(".has('" + key + "', " + term + ")"); - stepIndex++; - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getVerticesByProperty(String key, List<?> values) { - - String term = ""; - String predicate = "P.within(#!#argument#!#)"; - List<String> arguments = new ArrayList<>(); - for (Object item : values) { - if (item != null && !item.getClass().getName().equals("java.lang.String")) { - arguments.add(item.toString()); - } else { - arguments.add("'" + item + "'"); - } - } - String argument = Joiner.on(",").join(arguments); - predicate = predicate.replace("#!#argument#!#", argument); - list.add(".has('" + key + "', " + predicate + ")"); - stepIndex++; - return (QueryBuilder<Vertex>) this; - } - - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType) { - /* - String query = ".has('aai-node-type', '" + childType + "')"; - - return this.processGremlinQuery(parentKey, parentValue, query); - */ - //TODO - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> getTypedVerticesByMap(String type, LinkedHashMap<String, String> map) { - - for (String key : map.keySet()) { - list.add(".has('" + key + "', '" + map.get(key) + "')"); - stepIndex++; - } - list.add(".has('aai-node-type', '" + type + "')"); - stepIndex++; - return (QueryBuilder<Vertex>) this; - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createKeyQuery(Introspector obj) { - Set<String> keys = obj.getKeys(); - - for (String key : keys) { - - this.getVerticesByProperty(key, obj.<Object>getValue(key)); - - } - return (QueryBuilder<Vertex>) this; - } - - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String parentName = parent.getDbName(); - String childName = child.getDbName(); - if (parent.isContainer()) { - parentName = parent.getChildDBName(); - } - if (child.isContainer()) { - childName = child.getChildDBName(); - } - this.edgeQueryToVertex(type, parentName, childName); - return this; - - } - - /** - * @throws NoEdgeRuleFoundException - * @throws AAIException - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException, NoEdgeRuleFoundException { - String nodeType = parent.<String>property(AAIProperties.NODE_TYPE).orElse(null); - this.edgeQueryToVertex(type, nodeType, child.getDbName()); - - return (QueryBuilder<Vertex>) this; - - } - - @Override - public QueryBuilder<Edge> getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException { - this.edgeQuery(type, outNodeType, inNodeType); - - return (QueryBuilder<Edge>)this; - - } - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQueryToVertex(EdgeType type, String outType, String inType) throws AAIException, NoEdgeRuleFoundException { - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - list.add(".out('" + rule.getLabel() + "')"); - } else { - list.add(".in('" + rule.getLabel() + "')"); - } - stepIndex++; - list.add(".has('" + AAIProperties.NODE_TYPE + "', '" + inType + "')"); - stepIndex++; - - } - - /** - * Edge query. - * - * @param outType the out type - * @param inType the in type - * @throws NoEdgeRuleFoundException - * @throws AAIException - */ - private void edgeQuery(EdgeType type, String outType, String inType) throws AAIException, NoEdgeRuleFoundException { - markParentBoundary(); - EdgeRule rule = edgeRules.getEdgeRule(type, outType, inType); - if (rule.getDirection().equals(Direction.OUT)) { - list.add(".outE('" + rule.getLabel() + "')"); - } else { - list.add(".inV('" + rule.getLabel() + "')"); - } - stepIndex++; - - } - @Override - public QueryBuilder<E> limit(long amount) { - list.add(".limit(" + amount + ")"); - return this; - } - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<Vertex> createContainerQuery(Introspector obj) { - String type = obj.getChildDBName(); - String abstractType = obj.getMetadata(ObjectMetadata.ABSTRACT); - if (abstractType != null) { - String[] inheritors = obj.getMetadata(ObjectMetadata.INHERITORS).split(","); - String[] wrapped = new String[inheritors.length]; - StringBuilder command = new StringBuilder(); - command.append("P.within("); - for (int i = 0; i < inheritors.length; i++) { - wrapped[i] = "'" + inheritors[i] + "'"; - } - command.append(Joiner.on(",").join(wrapped)); - command.append(")"); - list.add(".has('aai-node-type', " + command + ")"); - - } else { - list.add(".has('aai-node-type', '" + type + "')"); - } - stepIndex++; - this.markContainer(); - return (QueryBuilder<Vertex>) this; - } - - @Override - public QueryBuilder<E> union(QueryBuilder<E>... builder) { - markParentBoundary(); - String[] traversals = new String[builder.length]; - StringBuilder command = new StringBuilder(); - for (int i = 0; i < builder.length; i++) { - traversals[i] = "__" + (String)builder[i].getQuery(); - } - command.append(".union("); - command.append(Joiner.on(",").join(traversals)); - command.append(")"); - list.add(command.toString()); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> where(QueryBuilder<E>... builder) { - markParentBoundary(); - List<String> traversals = new ArrayList<>(); - for (int i = 0; i < builder.length; i++) { - traversals.add(".where(__" + (String)builder[i].getQuery() + ")"); - stepIndex++; - } - list.addAll(traversals); - - - return this; - } - - @Override - public QueryBuilder<E> store(String name) { - this.list.add(".store('"+ name + "')"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> cap(String name) { - this.list.add(".cap('"+ name + "')"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> unfold() { - this.list.add(".unfold()"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> dedup() { - this.list.add(".dedup()"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> emit() { - this.list.add(".emit()"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> repeat(QueryBuilder<E> builder) { - this.list.add(".repeat(__" + builder.getQuery() + ")"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> until(QueryBuilder<E> builder) { - this.list.add(".until(__" + builder.getQuery() + ")"); - stepIndex++; - - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public QueryBuilder<E> simplePath(){ - this.list.add(".simplePath()"); - stepIndex++; - return this; - } - - @Override - public QueryBuilder<Edge> outE() { - this.list.add(".outE()"); - stepIndex++; - - return (QueryBuilder<Edge>)this; - } - - @Override - public QueryBuilder<Edge> inE() { - this.list.add(".inE()"); - stepIndex++; - - return (QueryBuilder<Edge>)this; - } - - @Override - public QueryBuilder<Vertex> outV() { - this.list.add(".outV()"); - stepIndex++; - - return (QueryBuilder<Vertex>)this; - } - - @Override - public QueryBuilder<Vertex> inV() { - this.list.add(".inV()"); - stepIndex++; - - return (QueryBuilder<Vertex>)this; - } - - @Override - public QueryBuilder<E> not(QueryBuilder<E> builder) { - this.list.add(".not(" + "__" + builder.getQuery() + ")"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> as(String name) { - this.list.add(".as('" + name + "')"); - stepIndex++; - - return this; - } - - @Override - public QueryBuilder<E> select(String name) { - this.list.add(".select('" + name + "')"); - stepIndex++; - - return this; - } - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> getParentQuery() { - return cloneQueryAtStep(parentStepIndex); - } - - @Override - public QueryBuilder<E> getContainerQuery() { - return cloneQueryAtStep(containerStepIndex); - } - - /** - * @{inheritDoc} - */ - @Override - public <T2> T2 getQuery() { - StringBuilder sb = new StringBuilder(); - - for (String piece : this.list) { - sb.append(piece); - } - - return (T2)sb.toString(); - } - - /** - * @{inheritDoc} - */ - @Override - public void markParentBoundary() { - parentStepIndex = stepIndex; - } - - @Override - public void markContainer() { - this.containerStepIndex = stepIndex; - } - - protected abstract QueryBuilder<E> cloneQueryAtStep(int index); - /** - * @{inheritDoc} - */ - @Override - public Vertex getStart() { - return this.start; - } - - protected int getParentStepIndex() { - return parentStepIndex; - } - - protected int getContainerStepIndex() { - return containerStepIndex; - } - - protected int getStepIndex() { - return stepIndex; - } - - private void executeQuery() { - String queryString = "g" + Joiner.on("").join(list); - Map<String, Object> params = new HashMap<>(); - if (this.start == null) { - params.put("g", source.V()); - } else { - params.put("g", source.V(this.start)); - } - this.completeTraversal = this.gremlinGroovy.executeTraversal(queryString, params); - } - @Override - public boolean hasNext() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return this.completeTraversal.hasNext(); - } - - @Override - public E next() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return (E)this.completeTraversal.next(); - } - - @Override - public List<E> toList() { - if (this.completeTraversal == null) { - executeQuery(); - } - - return (List<E>)this.completeTraversal.toList(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinTraversal.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinTraversal.java deleted file mode 100644 index daf795fd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinTraversal.java +++ /dev/null @@ -1,136 +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.query.builder; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.TraversalStrategy; - -/** - * The Class GremlinTraversal. - */ -public class GremlinTraversal<E> extends GremlinQueryBuilder<E> { - - /** - * Instantiates a new gremlin traversal. - * - * @param loader the loader - */ - public GremlinTraversal(Loader loader, GraphTraversalSource source) { - super(loader, source); - this.factory = new TraversalStrategy(this.loader, this); - } - - /** - * Instantiates a new gremlin traversal. - * - * @param loader the loader - * @param start the start - */ - public GremlinTraversal(Loader loader, GraphTraversalSource source, Vertex start) { - super(loader, source, start); - this.factory = new TraversalStrategy(this.loader, this); - } - - protected GremlinTraversal(List<String> traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder<E> gtb) { - super(loader, source); - this.list = traversal; - this.stepIndex = gtb.getStepIndex(); - this.parentStepIndex = gtb.getParentStepIndex(); - this.containerStepIndex = gtb.getContainerStepIndex(); - this.factory = new TraversalStrategy(this.loader, this); - this.start = gtb.getStart(); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException { - return factory.buildRelationshipParser(relationship); - } - - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams) - throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromObjectName(String objName) { - return factory.buildObjectNameParser(objName); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> newInstance(Vertex start) { - return new GremlinTraversal<>(loader, source, start); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> newInstance() { - return new GremlinTraversal<>(loader, source); - } - - @Override - protected QueryBuilder<E> cloneQueryAtStep(int index) { - if (index == 0) { - index = stepIndex; - } - List<String> newList = new ArrayList<>(); - for (int i = 0; i < index; i++) { - newList.add(this.list.get(i)); - } - - return new GremlinTraversal<>(newList, loader, source, this); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinUnique.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinUnique.java deleted file mode 100644 index ee2353f1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/GremlinUnique.java +++ /dev/null @@ -1,137 +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.query.builder; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Vertex; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.TraversalStrategy; -import org.openecomp.aai.parsers.query.UniqueStrategy; - -/** - * The Class GremlinUnique. - */ -public class GremlinUnique<E> extends GremlinQueryBuilder<E> { - - /** - * Instantiates a new gremlin unique. - * - * @param loader the loader - */ - public GremlinUnique(Loader loader, GraphTraversalSource source) { - super(loader, source); - this.factory = new UniqueStrategy(this.loader, this); - } - - /** - * Instantiates a new gremlin unique. - * - * @param loader the loader - * @param start the start - */ - public GremlinUnique(Loader loader, GraphTraversalSource source, Vertex start) { - super(loader, source, start); - this.factory = new UniqueStrategy(this.loader, this); - } - - protected GremlinUnique(List<String> traversal, Loader loader, GraphTraversalSource source, GremlinQueryBuilder<E> gtb) { - super(loader, source); - this.list = traversal; - this.stepIndex = gtb.getStepIndex(); - this.parentStepIndex = gtb.getParentStepIndex(); - this.containerStepIndex = gtb.getContainerStepIndex(); - this.factory = new TraversalStrategy(this.loader, this); - this.start = gtb.getStart(); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException { - return factory.buildRelationshipParser(relationship); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams) - throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromObjectName(String objName) { - return factory.buildObjectNameParser(objName); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> newInstance() { - return new GremlinUnique<>(loader, source); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> newInstance(Vertex start) { - return new GremlinUnique<>(loader, source, start); - } - - @Override - protected QueryBuilder<E> cloneQueryAtStep(int index) { - if (index == 0) { - index = stepIndex; - } - List<String> newList = new ArrayList<>(); - for (int i = 0; i < index; i++) { - newList.add(this.list.get(i)); - } - - return new GremlinUnique<>(newList, loader, source, this); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/QueryBuilder.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/QueryBuilder.java deleted file mode 100644 index 717033fa..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/QueryBuilder.java +++ /dev/null @@ -1,318 +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.query.builder; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.QueryParserStrategy; -import org.openecomp.aai.serialization.db.EdgeType; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -/** - * The Class QueryBuilder. - */ -public abstract class QueryBuilder<E> implements Iterator<E> { - - protected QueryParserStrategy factory = null; - - protected Loader loader = null; - - protected boolean optimize = false; - - protected Vertex start = null; - protected final GraphTraversalSource source; - - /** - * Instantiates a new query builder. - * - * @param loader the loader - */ - public QueryBuilder(Loader loader, GraphTraversalSource source) { - this.loader = loader; - this.source = source; - } - - /** - * Instantiates a new query builder. - * - * @param loader the loader - * @param start the start - */ - public QueryBuilder(Loader loader, GraphTraversalSource source, Vertex start) { - this.loader = loader; - this.start = start; - this.source = source; - } - - /** - * Gets the vertices by indexed property. - * - * @param key the key - * @param value the value - * @return the vertices by indexed property - */ - public abstract QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, Object value); - - /** - * Gets the vertices by property. - * - * @param key the key - * @param value the value - * @return the vertices by property - */ - public abstract QueryBuilder<Vertex> getVerticesByProperty(String key, Object value); - - /** - * filters by all the values for this property - * @param key - * @param values - * @return vertices that match these values - */ - public abstract QueryBuilder<Vertex> getVerticesByIndexedProperty(String key, List<?> values); - - /** - * filters by all the values for this property - * @param key - * @param values - * @return vertices that match these values - */ - public abstract QueryBuilder<Vertex> getVerticesByProperty(String key, List<?> values); - - /** - * Gets the child vertices from parent. - * - * @param parentKey the parent key - * @param parentValue the parent value - * @param childType the child type - * @return the child vertices from parent - */ - public abstract QueryBuilder<Vertex> getChildVerticesFromParent(String parentKey, String parentValue, String childType); - - /** - * Gets the typed vertices by map. - * - * @param type the type - * @param map the map - * @return the typed vertices by map - */ - public abstract QueryBuilder<Vertex> getTypedVerticesByMap(String type, LinkedHashMap<String, String> map); - - /** - * Creates the DB query. - * - * @param obj the obj - * @return the query builder - */ - public abstract QueryBuilder<Vertex> createDBQuery(Introspector obj); - - /** - * Creates the key query. - * - * @param obj the obj - * @return the query builder - */ - public abstract QueryBuilder<Vertex> createKeyQuery(Introspector obj); - - /** - * Creates the container query. - * - * @param obj the obj - * @return the query builder - */ - public abstract QueryBuilder<Vertex> createContainerQuery(Introspector obj); - - /** - * Creates the edge traversal. - * - * @param parent the parent - * @param child the child - * @return the query builder - */ - public abstract QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Introspector parent, Introspector child) throws AAIException; - - /** - * Creates the edge traversal. - * - * @param parent the parent - * @param child the child - * @return the query builder - */ - public abstract QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, Vertex parent, Introspector child) throws AAIException; - - public QueryBuilder<Vertex> createEdgeTraversal(EdgeType type, String outNodeType, String inNodeType) throws NoEdgeRuleFoundException, AAIException { - Introspector out = loader.introspectorFromName(outNodeType); - Introspector in = loader.introspectorFromName(inNodeType); - - return createEdgeTraversal(type, out, in); - } - - public abstract QueryBuilder<Edge> getEdgesBetween(EdgeType type, String outNodeType, String inNodeType) throws AAIException; - /** - * Creates the query from URI. - * - * @param uri the uri - * @return the query parser - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public abstract QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException; - - /** - * Creates the query from URI. - * - * @param uri the uri - * @param queryParams the query params - * @return the query parser - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public abstract QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams) throws UnsupportedEncodingException, AAIException; - - /** - * Creates a queryparser from a given object name. - * - * @param objName - name of the object type as it appears in the database - * @return - */ - public abstract QueryParser createQueryFromObjectName(String objName); - - /** - * Creates the query from relationship. - * - * @param relationship the relationship - * @return the query parser - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public abstract QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException; - - /** - * Gets the parent query. - * - * @return the parent query - */ - public abstract QueryBuilder<E> getParentQuery(); - - /** - * Gets the query. - * - * @return the query - */ - public abstract <E2> E2 getQuery(); - - /** - * Form boundary. - */ - public abstract void markParentBoundary(); - - public abstract QueryBuilder<E> limit(long amount); - /** - * New instance. - * - * @param start the start - * @return the query builder - */ - public abstract QueryBuilder<E> newInstance(Vertex start); - - /** - * New instance. - * - * @return the query builder - */ - public abstract QueryBuilder<E> newInstance(); - - /** - * Gets the start. - * - * @return the start - */ - public abstract Vertex getStart(); - - protected Object correctObjectType(Object obj) { - - if (obj != null && obj.getClass().equals(Long.class)) { - return new Integer(obj.toString()); - } - - return obj; - } - /** - * uses all fields in the introspector to create a query - * - * @param obj - * @return - */ - public abstract QueryBuilder<Vertex> exactMatchQuery(Introspector obj); - - /** - * lets you join any number of QueryBuilders - * <b>be careful about starting with a union it will not use indexes</b> - * @param builder - * @return - */ - public abstract QueryBuilder<E> union(QueryBuilder<E>... builder); - - public abstract QueryBuilder<E> where(QueryBuilder<E>... builder); - - public abstract QueryBuilder<E> store(String name); - public abstract QueryBuilder<E> cap(String name); - public abstract QueryBuilder<E> unfold(); - public abstract QueryBuilder<E> dedup(); - public abstract QueryBuilder<E> emit(); - public abstract QueryBuilder<E> repeat(QueryBuilder<E> builder); - public abstract QueryBuilder<Edge> outE(); - public abstract QueryBuilder<Edge> inE(); - public abstract QueryBuilder<Vertex> inV(); - public abstract QueryBuilder<Vertex> outV(); - public abstract QueryBuilder<E> not(QueryBuilder<E> builder); - public abstract QueryBuilder<E> as(String name); - public abstract QueryBuilder<E> select(String name); - public abstract QueryBuilder<E> until(QueryBuilder<E> builder); - - /** - * Used to prevent the traversal from repeating its path through the graph. - * See http://tinkerpop.apache.org/docs/3.0.1-incubating/#simplepath-step for more info. - * - * @return a QueryBuilder with the simplePath step appended to its traversal - */ - public abstract QueryBuilder<E> simplePath(); - - public abstract void markContainer(); - - public abstract QueryBuilder<E> getContainerQuery(); - - public abstract List<E> toList(); - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/query/builder/TraversalQuery.java b/aai-core/src/main/java/org/openecomp/aai/query/builder/TraversalQuery.java deleted file mode 100644 index 628e055e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/query/builder/TraversalQuery.java +++ /dev/null @@ -1,150 +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.query.builder; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.List; - -import javax.ws.rs.core.MultivaluedMap; - -import org.apache.tinkerpop.gremlin.process.traversal.Step; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.structure.Vertex; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.query.TraversalStrategy; - -/** - * The Class TraversalQuery. - */ -public class TraversalQuery<E> extends GraphTraversalBuilder<E> { - - /** - * Instantiates a new traversal query. - * - * @param loader the loader - */ - public TraversalQuery(Loader loader, GraphTraversalSource source) { - super(loader, source); - this.factory = new TraversalStrategy(this.loader, this); - } - - /** - * Instantiates a new traversal query. - * - * @param loader the loader - * @param start the start - */ - public TraversalQuery(Loader loader, GraphTraversalSource source, Vertex start) { - super(loader, source, start); - this.factory = new TraversalStrategy(this.loader, this); - } - - protected TraversalQuery(GraphTraversal<Vertex, E> traversal, Loader loader, GraphTraversalSource source, GraphTraversalBuilder<E> gtb) { - super(loader, source); - this.traversal = traversal; - this.stepIndex = gtb.getStepIndex(); - this.parentStepIndex = gtb.getParentStepIndex(); - this.containerStepIndex = gtb.getContainerStepIndex(); - this.factory = new TraversalStrategy(this.loader, this); - this.start = gtb.getStart(); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromURI(URI uri) throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromRelationship(Introspector relationship) throws UnsupportedEncodingException, AAIException { - return factory.buildRelationshipParser(relationship); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromURI(URI uri, MultivaluedMap<String, String> queryParams) - throws UnsupportedEncodingException, AAIException { - return factory.buildURIParser(uri, queryParams); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryParser createQueryFromObjectName(String objName) { - return factory.buildObjectNameParser(objName); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> newInstance(Vertex start) { - return new TraversalQuery<>(loader, source, start); - } - - /** - * @{inheritDoc} - */ - @Override - public QueryBuilder<E> newInstance() { - return new TraversalQuery<>(loader, source); - } - - @Override - protected QueryBuilder<E> cloneQueryAtStep(int index) { - if (index == 0) { - index = stepIndex; - } - GraphTraversal<Vertex, E> clone = this.traversal.asAdmin().clone(); - GraphTraversal.Admin<Vertex, E> cloneAdmin = clone.asAdmin(); - List<Step> steps = cloneAdmin.getSteps(); - - for (int i = steps.size()-1; i >= index; i--) { - cloneAdmin.removeStep(i); - } - return new TraversalQuery<>(cloneAdmin, loader, source, this); - } - - @Override - protected QueryBuilder<E> removeQueryStepsBetween(int start, int end) { - GraphTraversal<Vertex, E> clone = this.traversal.asAdmin().clone(); - GraphTraversal.Admin<Vertex, E> cloneAdmin = clone.asAdmin(); - - for (int i = end-2; i >= start; i--) { - cloneAdmin.removeStep(i); - } - return new TraversalQuery<>(cloneAdmin, loader, source, this); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/RestTokens.java b/aai-core/src/main/java/org/openecomp/aai/rest/RestTokens.java deleted file mode 100644 index 13bfe650..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/RestTokens.java +++ /dev/null @@ -1,36 +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.rest; - -public enum RestTokens { - - COUSIN("related-to"); - private final String name; - - private RestTokens(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/db/DBRequest.java b/aai-core/src/main/java/org/openecomp/aai/rest/db/DBRequest.java deleted file mode 100644 index e7b68588..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/db/DBRequest.java +++ /dev/null @@ -1,251 +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.rest.db; - -import java.net.URI; -import java.util.Optional; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.UriInfo; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.MarshallerProperties; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.restcore.HttpMethod; - -/** - * The Class DBRequest. - */ -public class DBRequest { - - private final QueryParser parser; - - private final Introspector introspector; - - private final HttpHeaders headers; - - private final String transactionId; - - private final UriInfo info; - - private final HttpMethod method; - - private final URI uri; - - private final Optional<String> rawRequestContent; - - private final Optional<MarshallerProperties> marshallerProperties; - - - /** - * Instantiates a new DB request. - * - * @param method the method - * @param uri the uri - * @param parser the parser - * @param obj the obj - * @param headers the headers - * @param info the info - * @param transactionId the transaction id - */ - private DBRequest(Builder builder) { - this.method = builder.getMethod(); - this.parser = builder.getParser(); - this.introspector = builder.getIntrospector(); - this.headers = builder.getHeaders(); - this.transactionId = builder.getTransactionId(); - this.info = builder.getInfo(); - this.uri = builder.getUri(); - this.marshallerProperties = builder.getMarshallerProperties(); - this.rawRequestContent = builder.getRawRequestContent(); - } - - /** - * Gets the headers. - * - * @return the headers - */ - public HttpHeaders getHeaders() { - return headers; - } - - - /** - * Gets the transaction id. - * - * @return the transaction id - */ - public String getTransactionId() { - return transactionId; - } - - /** - * Gets the info. - * - * @return the info - */ - public UriInfo getInfo() { - return info; - } - - /** - * Gets the parser. - * - * @return the parser - */ - public QueryParser getParser() { - return parser; - } - - /** - * Gets the introspector. - * - * @return the introspector - */ - public Introspector getIntrospector() { - return introspector; - } - - /** - * Gets the method. - * - * @return the method - */ - public HttpMethod getMethod() { - return method; - } - - /** - * Gets the uri. - * - * @return the uri - */ - public URI getUri() { - return uri; - } - - /** - * Gets the raw content. - * - * @return the raw content - */ - public Optional<String> getRawRequestContent() { - return rawRequestContent; - } - - public Optional<MarshallerProperties> getMarshallerProperties() { - return marshallerProperties; - } - - - - public static class Builder { - - private QueryParser parser = null; - - private Introspector introspector = null; - - private HttpHeaders headers = null; - - private String transactionId = null; - - private UriInfo info = null; - - private HttpMethod method = null; - - private URI uri = null; - - private Optional<MarshallerProperties> marshallerProperties = Optional.empty(); - - private Optional<String> rawRequestContent = Optional.empty(); - /** - * Instantiates a new DB request. - * - * @param method the method - * @param uri the uri - * @param parser the parser - * @param obj the obj - * @param headers the headers - * @param info the info - * @param transactionId the transaction id - */ - public Builder(HttpMethod method, URI uri, QueryParser parser, Introspector obj, HttpHeaders headers, UriInfo info, String transactionId) { - this.method = method; - this.parser = parser; - this.introspector = obj; - this.headers = headers; - this.transactionId = transactionId; - this.info = info; - this.uri = uri; - - } - - public QueryParser getParser() { - return parser; - } - - public Introspector getIntrospector() { - return introspector; - } - - public HttpHeaders getHeaders() { - return headers; - } - - public String getTransactionId() { - return transactionId; - } - - public UriInfo getInfo() { - return info; - } - - public HttpMethod getMethod() { - return method; - } - - public URI getUri() { - return uri; - } - - public Builder customMarshaller(MarshallerProperties properties) { - this.marshallerProperties = Optional.of(properties); - return this; - } - - public Builder rawRequestContent(String content) { - this.rawRequestContent = Optional.of(content); - return this; - } - protected Optional<MarshallerProperties> getMarshallerProperties() { - return marshallerProperties; - } - protected Optional<String> getRawRequestContent() { - return rawRequestContent; - } - public DBRequest build() { - - return new DBRequest(this); - } - - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/db/HttpEntry.java b/aai-core/src/main/java/org/openecomp/aai/rest/db/HttpEntry.java deleted file mode 100644 index 226e6023..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/db/HttpEntry.java +++ /dev/null @@ -1,566 +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.rest.db; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Set; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.Response.Status; -import javax.ws.rs.core.UriBuilder; - -import org.apache.commons.lang.StringUtils; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.javatuples.Pair; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.domain.responseMessage.AAIResponseMessage; -import org.openecomp.aai.domain.responseMessage.AAIResponseMessageDatum; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.MarshallerProperties; -import org.openecomp.aai.introspection.ModelInjestor; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.uri.URIToExtensionInformation; -import org.openecomp.aai.rest.ueb.UEBNotification; -import org.openecomp.aai.restcore.HttpMethod; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.engines.QueryStyle; -import org.openecomp.aai.serialization.engines.TitanDBEngine; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; -import org.openecomp.aai.serialization.engines.query.QueryEngine; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.fge.jsonpatch.JsonPatchException; -import com.github.fge.jsonpatch.mergepatch.JsonMergePatch; -import com.thinkaurelius.titan.core.TitanException; - -/** - * The Class HttpEntry. - */ -public class HttpEntry { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(HttpEntry.class); - - private final ModelType introspectorFactoryType; - - private final QueryStyle queryStyle; - - private final Version version; - - private final Loader loader; - - private final TransactionalGraphEngine dbEngine; - - private boolean processSingle = true; - - /** - * Instantiates a new http entry. - * - * @param version the version - * @param modelType the model type - * @param queryStyle the query style - * @param llBuilder the ll builder - */ - public HttpEntry(Version version, ModelType modelType, QueryStyle queryStyle, DBConnectionType connectionType) { - this.introspectorFactoryType = modelType; - this.queryStyle = queryStyle; - this.version = version; - this.loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); - this.dbEngine = new TitanDBEngine( - queryStyle, - connectionType, - loader); - //start transaction on creation - dbEngine.startTransaction(); - - } - - /** - * Gets the introspector factory type. - * - * @return the introspector factory type - */ - public ModelType getIntrospectorFactoryType() { - return introspectorFactoryType; - } - - /** - * Gets the query style. - * - * @return the query style - */ - public QueryStyle getQueryStyle() { - return queryStyle; - } - - /** - * Gets the version. - * - * @return the version - */ - public Version getVersion() { - return version; - } - - /** - * Gets the loader. - * - * @return the loader - */ - public Loader getLoader() { - return loader; - } - - /** - * Gets the db engine. - * - * @return the db engine - */ - public TransactionalGraphEngine getDbEngine() { - return dbEngine; - } - - public Pair<Boolean, List<Pair<URI, Response>>> process (List<DBRequest> requests, String sourceOfTruth) throws AAIException { - return this.process(requests, sourceOfTruth, true); - } - /** - * Process. - * @param requests the requests - * @param sourceOfTruth the source of truth - * - * @return the pair - * @throws AAIException the AAI exception - */ - public Pair<Boolean, List<Pair<URI, Response>>> process (List<DBRequest> requests, String sourceOfTruth, boolean enableResourceVersion) throws AAIException { - DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth); - Response response = null; - Status status = Status.NOT_FOUND; - Introspector obj = null; - QueryParser query = null; - URI uri = null; - String transactionId = null; - UEBNotification notification = new UEBNotification(loader); - int depth = AAIProperties.MAXIMUM_DEPTH; - List<Pair<URI,Response>> responses = new ArrayList<>(); - MultivaluedMap<String, String> params = null; - HttpMethod method = null; - String uriTemp = ""; - Boolean success = true; - QueryEngine queryEngine = dbEngine.getQueryEngine(); - int maxRetries = 10; - int retry = 0; - for (DBRequest request : requests) { - try { - for (retry = 0; retry < maxRetries; ++retry) { - try { - method = request.getMethod(); - obj = request.getIntrospector(); - query = request.getParser(); - transactionId = request.getTransactionId(); - uriTemp = request.getUri().getRawPath().replaceFirst("^v\\d+/", ""); - uri = UriBuilder.fromPath(uriTemp).build(); - List<Vertex> vertices = query.getQueryBuilder().toList(); - boolean isNewVertex = false; - String outputMediaType = getMediaType(request.getHeaders().getAcceptableMediaTypes()); - String result = null; - params = request.getInfo().getQueryParameters(false); - depth = setDepth(obj, params.getFirst("depth")); - String cleanUp = params.getFirst("cleanup"); - String requestContext = ""; - List<String> requestContextList = request.getHeaders().getRequestHeader("aai-request-context"); - if (requestContextList != null) { - requestContext = requestContextList.get(0); - } - - if (cleanUp == null) { - cleanUp = "false"; - } - if (vertices.size() > 1 && processSingle && !method.equals(HttpMethod.GET)) { - if (method.equals(HttpMethod.DELETE)) { - throw new AAIException("AAI_6138"); - } else { - throw new AAIException("AAI_6137"); - } - } - if (method.equals(HttpMethod.PUT)) { - String resourceVersion = (String)obj.getValue("resource-version"); - if (vertices.isEmpty()) { - if (enableResourceVersion) { - serializer.verifyResourceVersion("create", query.getResultType(), "", resourceVersion, obj.getURI()); - } - isNewVertex = true; - } else { - if (enableResourceVersion) { - serializer.verifyResourceVersion("update", query.getResultType(), (String)vertices.get(0).<String>property("resource-version").orElse(null), resourceVersion, obj.getURI()); - } - isNewVertex = false; - } - } else { - if (vertices.isEmpty()) { - String msg = createNotFoundMessage(query.getResultType(), request.getUri()); - throw new AAIException("AAI_6114", msg); - } else { - isNewVertex = false; - } - } - Vertex v = null; - if (!isNewVertex) { - v = vertices.get(0); - } - HashMap<String, Introspector> relatedObjects = new HashMap<>(); - switch (method) { - case GET: - String nodeOnly = params.getFirst("nodes-only"); - boolean isNodeOnly = nodeOnly != null; - - obj = this.getObjectFromDb(vertices, serializer, query, obj, request.getUri(), depth, isNodeOnly, cleanUp); - if (obj != null) { - status = Status.OK; - MarshallerProperties properties; - if (!request.getMarshallerProperties().isPresent()) { - properties = - new MarshallerProperties.Builder(org.openecomp.aai.restcore.MediaType.getEnum(outputMediaType)).build(); - } else { - properties = request.getMarshallerProperties().get(); - } - result = obj.marshal(properties); - } - - break; - case PUT: - if (isNewVertex) { - v = serializer.createNewVertex(obj); - } - serializer.serializeToDb(obj, v, query, uri.getRawPath(), requestContext); - status = Status.OK; - if (isNewVertex) { - status = Status.CREATED; - } - obj = serializer.getLatestVersionView(v); - if (query.isDependent()) { - relatedObjects = this.getRelatedObjects(serializer, queryEngine, v); - } - notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects); - break; - case PUT_EDGE: - serializer.touchStandardVertexProperties(v, false); - serializer.createEdge(obj, v); - status = Status.OK; - break; - case MERGE_PATCH: - Introspector existingObj = (Introspector) obj.clone(); - existingObj = this.getObjectFromDb(vertices, serializer, query, existingObj, request.getUri(), 0, false, cleanUp); - String existingJson = existingObj.marshal(false); - String newJson; - - if (request.getRawRequestContent().isPresent()) { - newJson = request.getRawRequestContent().get(); - } else { - newJson = ""; - } - Object relationshipList = request.getIntrospector().getValue("relationship-list"); - ObjectMapper mapper = new ObjectMapper(); - try { - JsonNode existingNode = mapper.readTree(existingJson); - JsonNode newNode = mapper.readTree(newJson); - JsonMergePatch patch = JsonMergePatch.fromJson(newNode); - JsonNode completed = patch.apply(existingNode); - String patched = mapper.writeValueAsString(completed); - Introspector patchedObj = loader.unmarshal(existingObj.getName(), patched); - if (relationshipList == null) { - //if the caller didn't touch the relationship-list, we shouldn't either - patchedObj.setValue("relationship-list", null); - } - serializer.serializeToDb(patchedObj, v, query, uri.getRawPath(), requestContext); - status = Status.OK; - patchedObj = serializer.getLatestVersionView(v); - if (query.isDependent()) { - relatedObjects = this.getRelatedObjects(serializer, queryEngine, v); - } - notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, patchedObj, relatedObjects); - } catch (IOException | JsonPatchException e) { - throw new AAIException("AAI_3000", "could not perform patch operation"); - } - break; - case DELETE: - String resourceVersion = params.getFirst("resource-version"); - obj = serializer.getLatestVersionView(v); - if (query.isDependent()) { - relatedObjects = this.getRelatedObjects(serializer, queryEngine, v); - } - serializer.delete(v, resourceVersion, enableResourceVersion); - status = Status.NO_CONTENT; - notification.createNotificationEvent(transactionId, sourceOfTruth, status, uri, obj, relatedObjects); - break; - case DELETE_EDGE: - serializer.touchStandardVertexProperties(v, false); - serializer.deleteEdge(obj, v); - status = Status.NO_CONTENT; - break; - default: - break; - } - - - /* temporarily adding vertex id to the headers - * to be able to use for testing the vertex id endpoint functionality - * since we presently have no other way of generating those id urls - */ - if (response == null && v != null && ( - method.equals(HttpMethod.PUT) - || method.equals(HttpMethod.GET) - || method.equals(HttpMethod.MERGE_PATCH)) - ) { - String myvertid = v.id().toString(); - response = Response.status(status) - .header("vertex-id", myvertid) - .entity(result) - .type(outputMediaType).build(); - } else if (response == null) { - response = Response.status(status) - .type(outputMediaType).build(); - } else { - //response already set to something - } - Pair<URI,Response> pairedResp = Pair.with(request.getUri(), response); - responses.add(pairedResp); - //break out of retry loop - break; - } catch (TitanException e) { - this.dbEngine.rollback(); - AAIException ex = new AAIException("AAI_6142", e); - ErrorLogHelper.logException(ex); - Thread.sleep((retry + 1) * 20); - this.dbEngine.startTransaction(); - queryEngine = dbEngine.getQueryEngine(); - serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth); - } - - if (retry == maxRetries) { - throw new AAIException("AAI_6134"); - } - } - } catch (AAIException e) { - success = false; - ArrayList<String> templateVars = new ArrayList<String>(); - templateVars.add(request.getMethod().toString()); //GET, PUT, etc - templateVars.add(request.getUri().getPath().toString()); - templateVars.addAll(e.getTemplateVars()); - - response = Response - .status(e.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), e, templateVars)) - .build(); - Pair<URI,Response> pairedResp = Pair.with(request.getUri(), response); - responses.add(pairedResp); - continue; - } catch (Exception e) { - success = false; - e.printStackTrace(); - AAIException ex = new AAIException("AAI_4000", e); - ArrayList<String> templateVars = new ArrayList<String>(); - templateVars.add(request.getMethod().toString()); //GET, PUT, etc - templateVars.add(request.getUri().getPath().toString()); - - response = Response - .status(ex.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponse(request.getHeaders().getAcceptableMediaTypes(), ex, templateVars)) - .build(); - Pair<URI, Response> pairedResp = Pair.with(request.getUri(), response); - responses.add(pairedResp); - continue; - } - } - - notification.triggerEvents(); - Pair<Boolean, List<Pair<URI, Response>>> tuple = Pair.with(success, responses); - return tuple; - } - - /** - * Gets the media type. - * - * @param mediaTypeList the media type list - * @return the media type - */ - private String getMediaType(List <MediaType> mediaTypeList) { - String mediaType = MediaType.APPLICATION_JSON; // json is the default - for (MediaType mt : mediaTypeList) { - if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt)) { - mediaType = MediaType.APPLICATION_XML; - } - } - return mediaType; - } - - /** - * Gets the object from db. - * - * @param serializer the serializer - * @param g the g - * @param query the query - * @param obj the obj - * @param uri the uri - * @param depth the depth - * @param cleanUp the clean up - * @return the object from db - * @throws AAIException the AAI exception - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws SecurityException the security exception - * @throws InstantiationException the instantiation exception - * @throws NoSuchMethodException the no such method exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws MalformedURLException the malformed URL exception - * @throws AAIUnknownObjectException - * @throws URISyntaxException - */ - private Introspector getObjectFromDb(List<Vertex> results, DBSerializer serializer, QueryParser query, Introspector obj, URI uri, int depth, boolean nodeOnly, String cleanUp) throws AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, UnsupportedEncodingException, AAIUnknownObjectException, URISyntaxException { - - //nothing found - if (results.size() == 0) { - String msg = createNotFoundMessage(query.getResultType(), uri); - throw new AAIException("AAI_6114", msg); - } - - obj = serializer.dbToObject(results, obj, depth, nodeOnly, cleanUp); - - return obj; - } - - - /** - * Creates the not found message. - * - * @param resultType the result type - * @param uri the uri - * @return the string - */ - private String createNotFoundMessage(String resultType, URI uri) { - - String msg = "No Node of type " + resultType + " found at: " + uri.getPath(); - - return msg; - } - - /** - * Sets the depth. - * - * @param depthParam the depth param - * @return the int - * @throws AAIException the AAI exception - */ - protected int setDepth(Introspector obj, String depthParam) throws AAIException { - int depth = AAIProperties.MAXIMUM_DEPTH; - - if(depthParam == null){ - if(this.version.compareTo(Version.v9) >= 0){ - depth = 0; - } else { - depth = AAIProperties.MAXIMUM_DEPTH; - } - } else { - if (depthParam.length() > 0 && !depthParam.equals("all")){ - try { - depth = Integer.valueOf(depthParam); - } catch (Exception e) { - throw new AAIException("AAI_4016"); - } - - } - } - String maxDepth = obj.getMetadata(ObjectMetadata.MAXIMUM_DEPTH); - - int maximumDepth = AAIProperties.MAXIMUM_DEPTH; - - if(maxDepth != null){ - try { - maximumDepth = Integer.parseInt(maxDepth); - } catch(Exception ex){ - throw new AAIException("AAI_4018"); - } - } - - if(depth > maximumDepth){ - throw new AAIException("AAI_3303"); - } - - return depth; - } - - /** - * Checks if is modification method. - * - * @param method the method - * @return true, if is modification method - */ - private boolean isModificationMethod(HttpMethod method) { - boolean result = false; - - if (method.equals(HttpMethod.PUT) || method.equals(HttpMethod.PUT_EDGE) || method.equals(HttpMethod.DELETE_EDGE) || method.equals(HttpMethod.MERGE_PATCH)) { - result = true; - } - - return result; - - } - - private HashMap<String, Introspector> getRelatedObjects(DBSerializer serializer, QueryEngine queryEngine, Vertex v) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, UnsupportedEncodingException, AAIException, URISyntaxException { - HashMap<String, Introspector> relatedVertices = new HashMap<>(); - List<Vertex> vertexChain = queryEngine.findParents(v); - for (Vertex vertex : vertexChain) { - try { - final Introspector vertexObj = serializer.getVertexProperties(vertex); - relatedVertices.put(vertexObj.getObjectId(), vertexObj); - } catch (AAIUnknownObjectException e) { - LOGGER.warn("Unable to get vertex properties, partial list of related vertices returned"); - } - - } - - return relatedVertices; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/ueb/NotificationEvent.java b/aai-core/src/main/java/org/openecomp/aai/rest/ueb/NotificationEvent.java deleted file mode 100644 index e473e9da..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/ueb/NotificationEvent.java +++ /dev/null @@ -1,99 +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.rest.ueb; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.util.StoreNotificationEvent; - -/** - * The Class NotificationEvent. - */ -public class NotificationEvent { - - private final Loader loader; - - private final Introspector eventHeader; - - private final Introspector obj; - private final String transactionId; - private final String sourceOfTruth; - /** - * Instantiates a new notification event. - * - * @param version the version - * @param eventHeader the event header - * @param obj the obj - */ - public NotificationEvent (Loader loader, Introspector eventHeader, Introspector obj, String transactionId, String sourceOfTruth) { - this.loader = loader; - this.eventHeader = eventHeader; - this.obj = obj; - this.transactionId = transactionId; - this.sourceOfTruth = sourceOfTruth; - } - - /** - * Trigger. - * - * @throws AAIException the AAI exception - */ - public void trigger() throws AAIException { - - StoreNotificationEvent sne = new StoreNotificationEvent(transactionId, sourceOfTruth); - - sne.storeEvent(loader, eventHeader, obj); - - } - - /** - * Gets the notification version. - * - * @return the notification version - */ - public Version getNotificationVersion() { - return loader.getVersion(); - } - - /** - * Gets the event header. - * - * @return the event header - */ - public Introspector getEventHeader() { - return eventHeader; - } - - /** - * Gets the obj. - * - * @return the obj - */ - public Introspector getObj() { - return obj; - } - - - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/rest/ueb/UEBNotification.java b/aai-core/src/main/java/org/openecomp/aai/rest/ueb/UEBNotification.java deleted file mode 100644 index fdba3081..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/rest/ueb/UEBNotification.java +++ /dev/null @@ -1,176 +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.rest.ueb; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.ws.rs.core.Response.Status; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.LoaderFactory; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; -import org.openecomp.aai.parsers.uri.URIToObject; -import org.openecomp.aai.util.AAIConfig; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -/** - * The Class UEBNotification. - */ -public class UEBNotification { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(UEBNotification.class); - - private Loader currentVersionLoader = null; - protected List<NotificationEvent> events = null; - private Version notificationVersion = null; - - /** - * Instantiates a new UEB notification. - * - * @param loader the loader - */ - public UEBNotification(Loader loader) { - events = new ArrayList<>(); - currentVersionLoader = LoaderFactory.createLoaderForVersion(loader.getModelType(), AAIProperties.LATEST); - notificationVersion = Version.valueOf(AAIConfig.get("aai.notification.current.version","v11")); - } - - - /** - * Creates the notification event. - * - * @param transactionId the X-TransactionId - * @param sourceOfTruth - * @param status the status - * @param uri the uri - * @param obj the obj - * @throws AAIException the AAI exception - * @throws IllegalArgumentException the illegal argument exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - public void createNotificationEvent(String transactionId, String sourceOfTruth, Status status, URI uri, Introspector obj, HashMap<String, Introspector> relatedObjects) throws AAIException, UnsupportedEncodingException { - - String action = "UPDATE"; - - if (status.equals(Status.CREATED)) { - action = "CREATE"; - } else if (status.equals(Status.OK)) { - action = "UPDATE"; - } else if (status.equals(Status.NO_CONTENT)) { - action = "DELETE"; - } - - try { - Introspector eventHeader = currentVersionLoader.introspectorFromName("notification-event-header"); - URIToObject parser = new URIToObject(currentVersionLoader, uri, relatedObjects); - - String entityLink = ""; - if (uri.toString().startsWith("/")) { - entityLink = "/aai/" + notificationVersion + uri; - } else { - entityLink = "/aai/" + notificationVersion + "/" + uri; - } - - - eventHeader.setValue("entity-link", entityLink); - eventHeader.setValue("action", action); - eventHeader.setValue("entity-type", obj.getDbName()); - eventHeader.setValue("top-entity-type", parser.getTopEntityName()); - eventHeader.setValue("source-name", sourceOfTruth); - eventHeader.setValue("version", notificationVersion.toString()); - eventHeader.setValue("id", transactionId); - - List<Object> parentList = parser.getParentList(); - parentList.clear(); - - if (!parser.getTopEntity().equals(parser.getEntity())) { - Introspector child = obj; - if (!parser.getLoader().getVersion().equals(obj.getVersion())) { - String json = obj.marshal(false); - child = parser.getLoader().unmarshal(parser.getEntity().getName(), json); - } - - //wrap the child object in its parents - parentList.add(child.getUnderlyingObject()); - } - - final Introspector eventObject; - - //convert to most resent version - if (!parser.getLoader().getVersion().equals(currentVersionLoader.getVersion())) { - String json = ""; - if (parser.getTopEntity().equals(parser.getEntity())) { - //convert the parent object passed in - json = obj.marshal(false); - eventObject = currentVersionLoader.unmarshal(obj.getName(), json); - } else { - //convert the object created in the parser - json = parser.getTopEntity().marshal(false); - eventObject = currentVersionLoader.unmarshal(parser.getTopEntity().getName(), json); - } - } else { - if (parser.getTopEntity().equals(parser.getEntity())) { - //take the top level parent object passed in - eventObject = obj; - } else { - //take the wrapped child objects (ogres are like onions) - eventObject = parser.getTopEntity(); - } - } - - final NotificationEvent event = new NotificationEvent(currentVersionLoader, eventHeader, eventObject, transactionId, sourceOfTruth); - events.add(event); - } catch (AAIUnknownObjectException e) { - throw new RuntimeException("Fatal error - notification-event-header object not found!"); - } catch (AAIUnmarshallingException e) { - LOGGER.error("Unmarshalling error occurred while generating UEBNotification", e); - } - } - - /** - * Trigger events. - * - * @throws AAIException the AAI exception - */ - public void triggerEvents() throws AAIException { - for (NotificationEvent event : events) { - event.trigger(); - } - events.clear(); - } - - public List<NotificationEvent> getEvents() { - return this.events; - } - - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/CustomJacksonJaxBJsonProvider.java b/aai-core/src/main/java/org/openecomp/aai/restcore/CustomJacksonJaxBJsonProvider.java deleted file mode 100644 index 1748fd62..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/CustomJacksonJaxBJsonProvider.java +++ /dev/null @@ -1,71 +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.restcore; - -import javax.ws.rs.ext.Provider; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; -import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; - -/** - * The Class CustomJacksonJaxBJsonProvider. - */ -@Provider -public class CustomJacksonJaxBJsonProvider extends JacksonJaxbJsonProvider { - - private static ObjectMapper commonMapper = null; - - /** - * Instantiates a new custom jackson jax B json provider. - */ - public CustomJacksonJaxBJsonProvider() { - if (commonMapper == null) { - ObjectMapper mapper = new ObjectMapper(); - - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - - mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - mapper.configure(SerializationFeature.INDENT_OUTPUT, false); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); - - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); - - mapper.registerModule(new JaxbAnnotationModule()); - - commonMapper = mapper; - } - super.setMapper(commonMapper); - } - - /** - * Gets the mapper. - * - * @return the mapper - */ - public ObjectMapper getMapper() { - return commonMapper; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/HttpMethod.java b/aai-core/src/main/java/org/openecomp/aai/restcore/HttpMethod.java deleted file mode 100644 index 3dab68ee..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/HttpMethod.java +++ /dev/null @@ -1,33 +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.restcore; - -/** - * The Enum HttpMethod. - */ -public enum HttpMethod { - PUT, - MERGE_PATCH, - DELETE, - PUT_EDGE, - DELETE_EDGE, - GET; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/JettyObfuscationConversionCommandLineUtil.java b/aai-core/src/main/java/org/openecomp/aai/restcore/JettyObfuscationConversionCommandLineUtil.java deleted file mode 100644 index b2e2d9f8..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/JettyObfuscationConversionCommandLineUtil.java +++ /dev/null @@ -1,97 +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.restcore; - -import org.apache.commons.cli.BasicParser; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.eclipse.jetty.util.security.Password; - -/* - * The purpose of this class is to be a tool for - * manually applying jetty obfuscation/deobfuscation - * so that one can obfuscate the various passwords/secrets - * in aaiconfig.properties. - * - * Originally, they were being encrypted by a similar - * command line utility, however the encryption key - * was being hardcoded in the src package - * which is a security violation. - * Since this ultimately just moved the problem of how - * to hide secrets to a different secret in a different file, - * and since that encryption was really just being done to - * obfuscate those values in case someone needed to look at - * properties with others looking at their screen, - * we decided that jetty obfuscation would be adequate - * for that task as well as - * removing the "turtles all the way down" secret-to-hide- - * the-secret-to-hide-the-secret problem. - */ -public class JettyObfuscationConversionCommandLineUtil { - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args){ - Options options = new Options(); - options.addOption("e", true, "obfuscate the given string"); - options.addOption("d", true, "deobfuscate the given string"); - - CommandLineParser parser = new BasicParser(); - - try { - CommandLine cmd = parser.parse(options, args); - String toProcess = null; - - if (cmd.hasOption("e")){ - toProcess = cmd.getOptionValue("e"); - String encoded = Password.obfuscate(toProcess); - System.out.println(encoded); - } else if (cmd.hasOption("d")) { - toProcess = cmd.getOptionValue("d"); - String decoded_str = Password.deobfuscate(toProcess); - System.out.println(decoded_str); - } else { - usage(); - } - } catch (ParseException e) { - System.out.println("failed to parse input"); - System.out.println(e.toString()); - usage(); - } catch (Exception e) { - System.out.println("exception:" + e.toString()); - } - } - - /** - * Usage. - */ - private static void usage(){ - System.out.println("usage:");; - System.out.println("-e [string] to obfuscate"); - System.out.println("-d [string] to deobfuscate"); - System.out.println("-h help"); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/MediaType.java b/aai-core/src/main/java/org/openecomp/aai/restcore/MediaType.java deleted file mode 100644 index c6eb13ec..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/MediaType.java +++ /dev/null @@ -1,66 +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.restcore; - -/** - * The Enum MediaType. - */ -public enum MediaType { - APPLICATION_JSON_TYPE("application/json"), - APPLICATION_XML_TYPE("application/xml"); - - private final String text; - - /** - * Instantiates a new media type. - * - * @param text the text - */ - private MediaType(final String text) { - this.text = text; - } - - /** - * Gets the enum. - * - * @param value the value - * @return the enum - */ - public static MediaType getEnum(String value) { - - for(MediaType v : values()) { - if(v.toString().equalsIgnoreCase(value)) { - return v; - } - } - - throw new IllegalArgumentException("bad value: " + value); - - } - - /** - * @{inheritDoc} - */ - @Override - public String toString() { - return text; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java b/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java deleted file mode 100644 index 18aef073..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/RESTAPI.java +++ /dev/null @@ -1,277 +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.restcore; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.tools.CreateUUID; -import org.openecomp.aai.introspection.tools.DefaultFields; -import org.openecomp.aai.introspection.tools.InjectKeysFromURI; -import org.openecomp.aai.introspection.tools.IntrospectorValidator; -import org.openecomp.aai.introspection.tools.Issue; -import org.openecomp.aai.introspection.tools.RemoveNonVisibleProperty; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.logging.LoggingContext; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.FormatDate; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.Joiner; - - -/** - * Base class for AAI REST API classes. - * Provides method to validate header information - * TODO should authenticate caller and authorize them for the API they are calling - * TODO should store the transaction - - * - */ -public class RESTAPI { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RESTAPI.class); - - protected final String COMPONENT = "aairest"; - - /** - * The Enum Action. - */ - public enum Action { - GET, PUT, POST, DELETE - }; - - /** - * Gets the from app id. - * - * @param headers the headers - * @param logline the logline - * @return the from app id - * @throws AAIException the AAI exception - */ - protected String getFromAppId(HttpHeaders headers) throws AAIException { - String fromAppId = null; - if (headers != null) { - List<String> fromAppIdHeader = headers.getRequestHeader("X-FromAppId"); - if (fromAppIdHeader != null) { - for (String fromAppIdValue : fromAppIdHeader) { - fromAppId = fromAppIdValue; - } - } - } - - if (fromAppId == null) { - throw new AAIException("AAI_4009"); - } - - LoggingContext.partnerName(fromAppId); - - return fromAppId; - } - - /** - * Gets the trans id. - * - * @param headers the headers - * @param logline the logline - * @return the trans id - * @throws AAIException the AAI exception - */ - protected String getTransId(HttpHeaders headers) throws AAIException { - String transId = null; - if (headers != null) { - List<String> transIdHeader = headers.getRequestHeader("X-TransactionId"); - if (transIdHeader != null) { - for (String transIdValue : transIdHeader) { - transId = transIdValue; - } - } - } - - if (transId == null) { - throw new AAIException("AAI_4010"); - } - - LoggingContext.requestId(transId); - - return transId; - } - - - /** - * Gen date. - * - * @return the string - */ - protected String genDate() { - FormatDate fd = new FormatDate( "YYMMdd-HH:mm:ss:SSS"); - - return fd.getDateTime(); - } - - /** - * Gets the media type. - * - * @param mediaTypeList the media type list - * @return the media type - */ - protected String getMediaType(List <MediaType> mediaTypeList) { - String mediaType = MediaType.APPLICATION_JSON; // json is the default - for (MediaType mt : mediaTypeList) { - if (MediaType.APPLICATION_XML_TYPE.isCompatible(mt)) { - mediaType = MediaType.APPLICATION_XML; - } - } - return mediaType; - } - - - /* ----------helpers for common consumer actions ----------- */ - - /** - * Sets the depth. - * - * @param depthParam the depth param - * @return the int - * @throws AAIException the AAI exception - */ - protected int setDepth(String depthParam) throws AAIException { - int depth = AAIProperties.MAXIMUM_DEPTH; //default - if (depthParam != null && depthParam.length() > 0 && !depthParam.equals("all")){ - try { - depth = Integer.valueOf(depthParam); - } catch (Exception e) { - throw new AAIException("AAI_4016"); - } - } - return depth; - } - - /** - * Consumer exception response generator. - * - * @param headers the headers - * @param info the info - * @param templateAction the template action - * @param e the e - * @return the response - */ - protected Response consumerExceptionResponseGenerator(HttpHeaders headers, UriInfo info, HttpMethod templateAction, AAIException e) { - ArrayList<String> templateVars = new ArrayList<String>(); - templateVars.add(templateAction.toString()); //GET, PUT, etc - templateVars.add(info.getPath().toString()); - templateVars.addAll(e.getTemplateVars()); - - return Response - .status(e.getErrorObject().getHTTPResponseCode()) - .entity(ErrorLogHelper.getRESTAPIErrorResponseWithLogging(headers.getAcceptableMediaTypes(), e, templateVars)) - .build(); - } - - /** - * Validate introspector. - * - * @param obj the obj - * @param loader the loader - * @param uri the uri - * @param validateRequired the validate required - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - protected void validateIntrospector(Introspector obj, Loader loader, URI uri, HttpMethod method) throws AAIException, UnsupportedEncodingException { - - int maximumDepth = AAIProperties.MAXIMUM_DEPTH; - boolean validateRequired = true; - if (method.equals(HttpMethod.MERGE_PATCH)) { - validateRequired = false; - maximumDepth = 0; - } - IntrospectorValidator validator = new IntrospectorValidator.Builder() - .validateRequired(validateRequired) - .restrictDepth(maximumDepth) - .addResolver(new RemoveNonVisibleProperty()) - .addResolver(new CreateUUID()) - .addResolver(new DefaultFields()) - .addResolver(new InjectKeysFromURI(loader, uri)) - .build(); - boolean result = validator.validate(obj); - if (!result) { - result = validator.resolveIssues(); - } - if (!result) { - List<String> messages = new ArrayList<>(); - for (Issue issue : validator.getIssues()) { - if (!issue.isResolved()) { - messages.add(issue.getDetail()); - } - } - String errors = Joiner.on(",").join(messages); - throw new AAIException("AAI_3000", errors); - } - //check that key in payload and key in request uri are the same - String objURI = obj.getURI(); - //if requested object is a parent objURI will have a leading slash the input uri will lack - //this adds that leading slash for the comparison - String testURI = "/" + uri.getRawPath(); - if (!testURI.endsWith(objURI)) { - throw new AAIException("AAI_3000", "uri and payload keys don't match"); - } - } - - protected DBConnectionType determineConnectionType(String fromAppId, String realTime) { - DBConnectionType type = DBConnectionType.REALTIME; - boolean isRealTimeClient = AAIConfig.get("aai.realtime.clients", "").contains(fromAppId); - if (isRealTimeClient || realTime != null) { - type = DBConnectionType.REALTIME; - } else { - type = DBConnectionType.CACHED; - } - - return type; - } - - /** - * Gets the input media type. - * - * @param mediaType the media type - * @return the input media type - */ - protected String getInputMediaType(MediaType mediaType) { - String result = mediaType.getType() + "/" + mediaType.getSubtype(); - - return result; - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/search/GremlinGroovyShellSingleton.java b/aai-core/src/main/java/org/openecomp/aai/restcore/search/GremlinGroovyShellSingleton.java deleted file mode 100644 index b098dcc4..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/search/GremlinGroovyShellSingleton.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.restcore.search; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.codehaus.groovy.ast.ClassHelper; -import org.codehaus.groovy.ast.expr.ClassExpression; -import org.codehaus.groovy.ast.expr.PropertyExpression; -import org.codehaus.groovy.control.CompilerConfiguration; -import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer; -import org.codehaus.groovy.control.customizers.ImportCustomizer; - -import groovy.lang.Binding; -import groovy.lang.GroovyShell; -import groovy.lang.Script; -import groovy.transform.TimedInterrupt; - -/** - * Creates and returns a groovy shell with the - * configuration to statically import graph classes - * - */ -public class GremlinGroovyShellSingleton { - - private final GroovyShell shell; - private GremlinGroovyShellSingleton() { - Map<String, Object> parameters = new HashMap<>(); - parameters.put("value", 30000); - parameters.put("unit", new PropertyExpression(new ClassExpression(ClassHelper.make(TimeUnit.class)),"MILLISECONDS")); - - ASTTransformationCustomizer custom = new ASTTransformationCustomizer(parameters, TimedInterrupt.class); - ImportCustomizer imports = new ImportCustomizer(); - imports.addStaticStars( - "org.apache.tinkerpop.gremlin.process.traversal.P" - ); - imports.addImports( - "org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__", - "org.apache.tinkerpop.gremlin.structure.T", - "org.apache.tinkerpop.gremlin.process.traversal.P", - "java.util.Map.Entry"); - imports.addStarImports("java.util"); - CompilerConfiguration config = new CompilerConfiguration(); - config.addCompilationCustomizers(custom, imports); - - this.shell = new GroovyShell(config); - } - - private static class Helper { - private static final GremlinGroovyShellSingleton INSTANCE = new GremlinGroovyShellSingleton(); - } - - public static GremlinGroovyShellSingleton getInstance() { - - return Helper.INSTANCE; - } - - /** - * @param traversal - * @param params - * @return result of graph traversal - */ - public GraphTraversal<?, ?> executeTraversal (String traversal, Map<String, Object> params) { - Binding binding = new Binding(params); - Script script = shell.parse(traversal); - script.setBinding(binding); - return (GraphTraversal<?, ?>) script.run(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/util/GenerateEdgeRules.java b/aai-core/src/main/java/org/openecomp/aai/restcore/util/GenerateEdgeRules.java deleted file mode 100644 index 082d6151..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/util/GenerateEdgeRules.java +++ /dev/null @@ -1,154 +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.restcore.util; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -import java.io.*; -import java.util.*; - -public class GenerateEdgeRules { - - private static final EELFLogger LOG = EELFManager.getInstance().getLogger(GenerateEdgeRules.class); - - public static void main(String[] args) throws IOException, TemplateException { - - String filename = "/AAI8032.csv"; - InputStream inputStream = GenerateEdgeRules.class.getResourceAsStream(filename); - Map<String, Integer> headers = new HashMap<>(); - Map<String, Object> edgeRulesMap = new TreeMap<String, Object>(); - List<Map<String, String>> edgeRules = new ArrayList<>(); - - try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { - - String line = null; - - int rowNum = 0; - - // Retrieve the header line to map the indexes to their column names - - while ((line = reader.readLine()) != null) { - - if (rowNum == 0) { - headers = retrieveHeaderMap(line); - } else { - String[] columns = line.split(","); - - String originalNode = columns[headers.get("Orig NodeA|NodeB")]; - String finalNode = columns[headers.get("Final NodeA|NodeB")]; - String originalEdge = columns[headers.get("Orig EdgeLabel")]; - String finalEdge = columns[headers.get("Final EdgeLabel")]; - - String lineage = columns[headers.get("Final Lineage")]; - String originalParent = columns[headers.get("Orig ParentOf")]; - String usesResource = columns[headers.get("Revised UsesResource")]; - String hasDelTarget = columns[headers.get("Revised hasDelTarget")]; - String svcInfra = columns[headers.get("Final SVC-INFRA")]; - String svcInfraRev = ""; - - if(usesResource.equals("T")) - usesResource = "true"; - else if(usesResource.equals("F")) - usesResource = "false"; - - if (hasDelTarget.equals("T") || hasDelTarget.equals("AB")) { - hasDelTarget = "true"; - } else if (hasDelTarget.equals("F")) { - hasDelTarget = "false"; - } - - if (svcInfra.equals("T")) { - svcInfra = "true"; - } else if (svcInfra.equals("F")) { - svcInfra = "false"; - } else if (svcInfra.equals("R")) { - svcInfra = "reverse"; - } - - if (originalParent.equals("T")) { - if (lineage.trim().equalsIgnoreCase("CHILD")) { - lineage = "true"; - } else if (lineage.trim().equalsIgnoreCase("PARENT")) { - lineage = "reverse"; - } - } else { - lineage = "false"; - } - - Map<String, String> edgeMap = new HashMap<String, String>(); - - edgeMap.put("lineage", lineage); - edgeMap.put("usesResource", usesResource); - edgeMap.put("hasDelTarget", hasDelTarget); - edgeMap.put("SVC-INFRA", svcInfra); - edgeMap.put("SVC-INFRA-REV", svcInfraRev); - edgeMap.put("nodes", finalNode); - edgeMap.put("edge", finalEdge); - edgeMap.put("direction", columns[headers.get("Orig Direction")]); - edgeMap.put("multiplicity", columns[headers.get("Revised Multiplicity")]); - - edgeRules.add(edgeMap); - - } - ++rowNum; - } - } catch(Exception ex){ - ex.printStackTrace(); - } - - edgeRulesMap.put("edgeRules", edgeRules); - - Collections.sort(edgeRules, new Comparator<Map<String, String>>() { - @Override - public int compare(Map<String, String> o1, Map<String, String> o2) { - return o1.get("nodes").compareTo(o2.get("nodes")); - } - }); - - Configuration configuration = new Configuration(); - Template template = configuration.getTemplate("ajsc-aai/src/main/resources/EdgeRules.ftl"); - Writer file = new FileWriter(new File("ajsc-aai/src/main/resources" + "/" + "EdgeRules.txt")); - template.process(edgeRulesMap, file); - } - - private static Map<String, Integer> retrieveHeaderMap(String line){ - - if(line == null) - throw new NullPointerException(); - - String[] columnNames = line.split(","); - - Map<String, Integer> map = new HashMap<String, Integer>(); - - int index = 0; - - for(String columnName : columnNames){ - map.put(columnName, index++); - } - - return map; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/restcore/util/URITools.java b/aai-core/src/main/java/org/openecomp/aai/restcore/util/URITools.java deleted file mode 100644 index 0a91d765..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/restcore/util/URITools.java +++ /dev/null @@ -1,113 +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.restcore.util; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -import org.springframework.web.util.UriUtils; - -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; -import org.openecomp.aai.schema.enums.PropertyMetadata; - -public class URITools { - - protected static final Pattern template = Pattern.compile("\\{(.*?)\\}"); - - public static MultivaluedMap<String, String> getQueryMap(URI uri) { - MultivaluedMap<String, String> result = new MultivaluedHashMap<>(); - String queryParams = uri.getRawQuery(); - if (queryParams != null) { - try { - String[] sections = queryParams.split("&"); - String[] query = null; - String key, value = ""; - for (String section : sections) { - query = section.split("="); - key = UriUtils.decode(query[0], "UTF-8"); - value = UriUtils.decode(query[1], "UTF-8"); - if (result.containsKey(key)) { - result.add(key, value); - } else { - result.putSingle(key, value); - } - } - } catch (UnsupportedEncodingException e ) { - - } - } - return result; - - } - - public static Optional<String> replaceTemplates(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException { - String result = uriString; - final Map<String, String> propMap = URITools.findProperties(obj, uriString, metadata, replaceWithWildcard); - if (propMap.isEmpty()) { - return Optional.empty(); - } - for (Entry<String, String> entry : propMap.entrySet()) { - result = result.replaceAll("\\{" + entry.getKey() + "\\}", entry.getValue()); - } - //drop out wildcards if they exist - result = result.replaceFirst("/[^/]+?(?:/\\*)+", ""); - return Optional.of(result); - } - - private static Map<String, String> findProperties(Introspector obj, String uriString, PropertyMetadata metadata, boolean replaceWithWildcard) throws AAIMissingRequiredPropertyException { - - final Map<String, String> result = new HashMap<>(); - final Set<String> missing = new LinkedHashSet<>(); - Matcher m = template.matcher(uriString); - int properties = 0; - while (m.find()) { - String propName = m.group(1); - String value = obj.getValue(propName); - properties++; - if (value != null) { - result.put(propName, value); - } else { - if (replaceWithWildcard) { - result.put(propName, "*"); - } - missing.add(propName); - } - } - - if (!missing.isEmpty() && (properties != missing.size())) { - throw new AAIMissingRequiredPropertyException("Cannot complete " + metadata.toString() + " uri. Missing properties " + missing); - } - return result; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/AAIDirection.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/AAIDirection.java deleted file mode 100644 index fe9be364..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/AAIDirection.java +++ /dev/null @@ -1,34 +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.serialization.db; - -public enum AAIDirection { - IN, OUT, BOTH, NONE; - - public AAIDirection opposite() { - if (this.equals(OUT)) - return IN; - else if (this.equals(IN)) - return OUT; - else - return BOTH; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DBSerializer.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/DBSerializer.java deleted file mode 100644 index 09d405a7..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DBSerializer.java +++ /dev/null @@ -1,1443 +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.serialization.db; - - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.base.CaseFormat; -import com.thinkaurelius.titan.core.SchemaViolationException; -import org.apache.commons.collections.IteratorUtils; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.*; -import org.javatuples.Pair; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.*; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.introspection.sideeffect.DataCopy; -import org.openecomp.aai.introspection.sideeffect.DataLinkReader; -import org.openecomp.aai.introspection.sideeffect.DataLinkWriter; -import org.openecomp.aai.introspection.sideeffect.SideEffectRunner; -import org.openecomp.aai.logging.ErrorLogHelper; -import org.openecomp.aai.parsers.query.QueryParser; -import org.openecomp.aai.parsers.uri.URIParser; -import org.openecomp.aai.parsers.uri.URIToRelationshipObject; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.schema.enums.ObjectMetadata; -import org.openecomp.aai.schema.enums.PropertyMetadata; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; -import org.openecomp.aai.serialization.tinkerpop.TreeBackedVertex; -import org.openecomp.aai.util.AAIApiServerURLBase; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.workarounds.NamingExceptions; - -import javax.ws.rs.core.UriBuilder; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.lang.reflect.InvocationTargetException; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -public class DBSerializer { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(DBSerializer.class); - - private final TransactionalGraphEngine engine; - private final String sourceOfTruth; - private final ModelType introspectionType; - private final Version version; - private final Loader latestLoader; - private final EdgeRules edgeRules = EdgeRules.getInstance(); - private final Loader loader; - private final String baseURL; - /** - * Instantiates a new DB serializer. - * - * @param version the version - * @param engine the engine - * @param g the g - * @param introspectionType the introspection type - * @param sourceOfTruth the source of truth - * @param llBuilder the ll builder - * @throws AAIException - */ - public DBSerializer(Version version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException { - this.engine = engine; - this.sourceOfTruth = sourceOfTruth; - this.introspectionType = introspectionType; - this.latestLoader = LoaderFactory.createLoaderForVersion(introspectionType, AAIProperties.LATEST); - this.version = version; - this.loader = LoaderFactory.createLoaderForVersion(introspectionType, version); - this.baseURL = AAIApiServerURLBase.get(version); - } - - /** - * Touch standard vertex properties. - * - * @param v the v - * @param isNewVertex the is new vertex - */ - public void touchStandardVertexProperties(Vertex v, boolean isNewVertex) { - - long unixTimeNow = System.currentTimeMillis(); - String timeNowInSec = "" + unixTimeNow; - if (isNewVertex) { - v.property(AAIProperties.SOURCE_OF_TRUTH, this.sourceOfTruth); - v.property(AAIProperties.CREATED_TS, timeNowInSec); - } - v.property(AAIProperties.RESOURCE_VERSION, timeNowInSec ); - v.property(AAIProperties.LAST_MOD_TS, timeNowInSec); - v.property(AAIProperties.LAST_MOD_SOURCE_OF_TRUTH, this.sourceOfTruth); - - } - - private void touchStandardVertexProperties(String nodeType, Vertex v, boolean isNewVertex) { - - v.property(AAIProperties.NODE_TYPE, nodeType); - touchStandardVertexProperties(v, isNewVertex); - - } - - - - /** - * Creates the new vertex. - * - * @param wrappedObject the wrapped object - * @return the vertex - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public Vertex createNewVertex(Introspector wrappedObject) { - - - Vertex v = this.engine.tx().addVertex(); - touchStandardVertexProperties(wrappedObject.getDbName(), v, true); - - return v; - } - - /** - * Trim class name. - * - * @param className the class name - * @return the string - */ - /* - * Removes the classpath from a class name - */ - public String trimClassName (String className) { - String returnValue = ""; - - if (className.lastIndexOf('.') == -1) { - return className; - } - returnValue = className.substring(className.lastIndexOf('.') + 1, className.length()); - - return returnValue; - } - - /** - * Serialize to db. - * - * @param obj the obj - * @param v the v - * @param uriQuery the uri query - * @param identifier the identifier - * @throws SecurityException the security exception - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws InstantiationException the instantiation exception - * @throws InterruptedException the interrupted exception - * @throws NoSuchMethodException the no such method exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - public void serializeToDb(Introspector obj, Vertex v, QueryParser uriQuery, String identifier, String requestContext) throws AAIException, UnsupportedEncodingException { - - try { - if (uriQuery.isDependent()) { - //try to find the parent - List<Vertex> vertices = uriQuery.getQueryBuilder().getParentQuery().toList(); - if (!vertices.isEmpty()) { - Vertex parent = vertices.get(0); - this.reflectDependentVertex(parent, v, obj, requestContext); - } else { - throw new AAIException("AAI_6114", "No parent Node of type " + uriQuery.getParentResultType() + " for " + identifier); - } - } else { - serializeSingleVertex(v, obj, requestContext); - } - - } catch (SchemaViolationException e) { - throw new AAIException("AAI_6117", e); - } - - } - - public void serializeSingleVertex(Vertex v, Introspector obj, String requestContext) throws UnsupportedEncodingException, AAIException { - try { - boolean isTopLevel = obj.isTopLevel(); - if (isTopLevel) { - v.property(AAIProperties.AAI_URI, obj.getURI()); - } - processObject(obj, v, requestContext); - if (!isTopLevel) { - URI uri = this.getURIForVertex(v); - URIParser parser = new URIParser(this.loader, uri); - if (parser.validate()) { - VertexProperty<String> uriProp = v.property(AAIProperties.AAI_URI); - if (!uriProp.isPresent() || uriProp.isPresent() && !uriProp.value().equals(uri.toString())) { - v.property(AAIProperties.AAI_URI, uri.toString()); - } - } - } - } catch (SchemaViolationException e) { - throw new AAIException("AAI_6117", e); - } - } - - /** - * Process object. - * - * @param <T> the generic type - * @param obj the obj - * @param v the v - * @return the list - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws InstantiationException the instantiation exception - * @throws NoSuchMethodException the no such method exception - * @throws SecurityException the security exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - /* - * Helper method for reflectToDb - * Handles all the property setting - */ - private <T> List<Vertex> processObject (Introspector obj, Vertex v, String requestContext) throws UnsupportedEncodingException, AAIException { - Set<String> properties = new LinkedHashSet<>(obj.getProperties()); - properties.remove(AAIProperties.RESOURCE_VERSION); - List<Vertex> dependentVertexes = new ArrayList<>(); - List<Vertex> processedVertexes = new ArrayList<>(); - boolean isComplexType = false; - boolean isListType = false; - if (!obj.isContainer()) { - this.touchStandardVertexProperties(obj.getDbName(), v, false); - } - this.executePreSideEffects(obj, v); - for (String property : properties) { - Object value = null; - final String propertyType; - propertyType = obj.getType(property); - isComplexType = obj.isComplexType(property); - isListType = obj.isListType(property); - value = obj.getValue(property); - - if (!(isComplexType || isListType)) { - boolean canModify = this.canModify(obj, property, requestContext); - - if (canModify) { - final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property); - String dbProperty = property; - if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) { - dbProperty = metadata.get(PropertyMetadata.DB_ALIAS); - } - if (metadata.containsKey(PropertyMetadata.DATA_LINK)) { - //data linked properties are ephemeral - //they are populated dynamically on GETs - continue; - } - if (value != null) { - if (!value.equals(v.property(dbProperty).orElse(null))) { - if (propertyType.toLowerCase().contains(".long")) { - v.property(dbProperty, new Integer(((Long)value).toString())); - } else { - v.property(dbProperty, value); - } - } - } else { - v.property(dbProperty).remove(); - } - } - } else if (isListType) { - List<Object> list = (List<Object>)value; - if (obj.isComplexGenericType(property)) { - if (list != null) { - for (Object o : list) { - Introspector child = IntrospectorFactory.newInstance(this.introspectionType, o); - child.setURIChain(obj.getURI()); - processedVertexes.add(reflectDependentVertex(v, child, requestContext)); - } - } - } else { - //simple list case - engine.setListProperty(v, property, list); - } - } else { - //method.getReturnType() is not 'simple' then create a vertex and edge recursively returning an edge back to this method - if (value != null) { //effectively ignore complex properties not included in the object we're processing - if (value.getClass().isArray()) { - - int length = Array.getLength(value); - for (int i = 0; i < length; i ++) { - Object arrayElement = Array.get(value, i); - Introspector child = IntrospectorFactory.newInstance(this.introspectionType, arrayElement); - child.setURIChain(obj.getURI()); - processedVertexes.add(reflectDependentVertex(v, child, requestContext)); - - } - } else if (!property.equals("relationship-list")) { - // container case - Introspector introspector = IntrospectorFactory.newInstance(this.introspectionType, value); - if (introspector.isContainer()) { - dependentVertexes.addAll(this.engine.getQueryEngine().findChildrenOfType(v, introspector.getChildDBName())); - introspector.setURIChain(obj.getURI()); - - processedVertexes.addAll(processObject(introspector, v, requestContext)); - - } else { - dependentVertexes.addAll(this.engine.getQueryEngine().findChildrenOfType(v, introspector.getDbName())); - processedVertexes.add(reflectDependentVertex(v, introspector, requestContext)); - - } - } else if (property.equals("relationship-list")) { - handleRelationships(obj, v); - } - } - } - } - this.writeThroughDefaults(v, obj); - /* handle those vertexes not touched */ - for (Vertex toBeRemoved : processedVertexes) { - dependentVertexes.remove(toBeRemoved); - } - this.deleteItemsWithTraversal(dependentVertexes); - - this.executePostSideEffects(obj, v); - return processedVertexes; - } - - /** - * Handle relationships. - * - * @param obj the obj - * @param vertex the vertex - * @throws SecurityException the security exception - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - /* - * Handles the explicit relationships defined for an obj - */ - private void handleRelationships(Introspector obj, Vertex vertex) throws UnsupportedEncodingException, AAIException { - - - - Introspector wrappedRl = obj.getWrappedValue("relationship-list"); - processRelationshipList(wrappedRl, vertex); - - - } - - - /** - * Process relationship list. - * - * @param wrapped the wrapped - * @param v the v - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - private void processRelationshipList(Introspector wrapped, Vertex v) throws UnsupportedEncodingException, AAIException { - - List<Object> relationships = (List<Object>)wrapped.getValue("relationship"); - - List<Pair<Vertex, Vertex>> addEdges = new ArrayList<>(); - List<Edge> existingEdges = this.engine.getQueryEngine().findEdgesForVersion(v, wrapped.getLoader()); - - for (Object relationship : relationships) { - Edge e = null; - Vertex cousinVertex = null; - Introspector wrappedRel = IntrospectorFactory.newInstance(this.introspectionType, relationship); - QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(wrappedRel); - - List<Vertex> results = parser.getQueryBuilder().toList(); - if (results.isEmpty()) { - final AAIException ex = new AAIException("AAI_6129", "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri()); - ex.getTemplateVars().add(parser.getResultType()); - ex.getTemplateVars().add(parser.getUri().toString()); - throw ex; - } else { - //still an issue if there's more than one - cousinVertex = results.get(0); - } - - if (cousinVertex != null) { - try { - if (!edgeRules.hasEdgeRule(v, cousinVertex)) { - throw new AAIException("AAI_6120", "No EdgeRule found for passed nodeTypes: " + v.property(AAIProperties.NODE_TYPE).value().toString() + ", " - + cousinVertex.property(AAIProperties.NODE_TYPE).value().toString() + "."); - } - e = this.getEdgeBetween(EdgeType.COUSIN, v, cousinVertex); - - if (e == null) { - addEdges.add(new Pair<>(v, cousinVertex)); - } else { - existingEdges.remove(e); - } - } catch (NoEdgeRuleFoundException e1) { - throw new AAIException("AAI_6145"); - } - } - } - - for (Edge edge : existingEdges) { - edge.remove(); - } - for (Pair<Vertex, Vertex> pair : addEdges) { - try { - edgeRules.addEdge(this.engine.asAdmin().getTraversalSource(), pair.getValue0(), pair.getValue1()); - } catch (NoEdgeRuleFoundException e) { - throw new AAIException("AAI_6129", e); - } - } - - } - - /** - * Write through defaults. - * - * @param v the v - * @param obj the obj - * @throws AAIUnknownObjectException - */ - private void writeThroughDefaults(Vertex v, Introspector obj) throws AAIUnknownObjectException { - Introspector latest = this.latestLoader.introspectorFromName(obj.getName()); - if (latest != null) { - Set<String> required = latest.getRequiredProperties(); - - for (String field : required) { - String defaultValue = null; - Object vertexProp = null; - defaultValue = latest.getPropertyMetadata(field).get(PropertyMetadata.DEFAULT_VALUE); - if (defaultValue != null) { - vertexProp = v.<Object>property(field).orElse(null); - if (vertexProp == null) { - v.property(field, defaultValue); - } - } - } - } - - } - - - /** - * Reflect dependent vertex. - * - * @param v the v - * @param dependentObj the dependent obj - * @return the vertex - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws InstantiationException the instantiation exception - * @throws NoSuchMethodException the no such method exception - * @throws SecurityException the security exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - private Vertex reflectDependentVertex(Vertex v, Introspector dependentObj, String requestContext) throws AAIException, UnsupportedEncodingException { - - //QueryParser p = this.engine.getQueryBuilder().createQueryFromURI(obj.getURI()); - //List<Vertex> items = p.getQuery().toList(); - QueryBuilder query = this.engine.getQueryBuilder(v); - query.createEdgeTraversal(EdgeType.TREE, v, dependentObj); - query.createKeyQuery(dependentObj); - - List<Vertex> items = query.toList(); - - Vertex dependentVertex = null; - if (items.size() == 1) { - dependentVertex = items.get(0); - this.verifyResourceVersion("update", dependentObj.getDbName(), dependentVertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), (String)dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String)dependentObj.getURI()); - } else { - this.verifyResourceVersion("create", dependentObj.getDbName(), "", (String)dependentObj.getValue(AAIProperties.RESOURCE_VERSION), (String)dependentObj.getURI()); - dependentVertex = createNewVertex(dependentObj); - } - - return reflectDependentVertex(v, dependentVertex, dependentObj, requestContext); - - } - - /** - * Reflect dependent vertex. - * - * @param parent the parent - * @param child the child - * @param obj the obj - * @return the vertex - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws InstantiationException the instantiation exception - * @throws NoSuchMethodException the no such method exception - * @throws SecurityException the security exception - * @throws AAIException the AAI exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - private Vertex reflectDependentVertex(Vertex parent, Vertex child, Introspector obj, String requestContext) throws AAIException, UnsupportedEncodingException { - - String parentUri = parent.<String>property(AAIProperties.AAI_URI).orElse(null); - if (parentUri != null) { - String uri; - uri = obj.getURI(); - child.property(AAIProperties.AAI_URI, parentUri + uri); - } - processObject(obj, child, requestContext); - - Edge e; - e = this.getEdgeBetween(EdgeType.TREE, parent, child); - if (e == null) { - String canBeLinked = obj.getMetadata(ObjectMetadata.CAN_BE_LINKED); - if (canBeLinked != null && canBeLinked.equals("true")) { - boolean isFirst = !this.engine.getQueryBuilder(parent).createEdgeTraversal(EdgeType.TREE, parent, obj).hasNext(); - if (isFirst) { - child.property(AAIProperties.LINKED, true); - } - } - edgeRules.addTreeEdge(this.engine.asAdmin().getTraversalSource(), parent, child); - } - return child; - - } - - /** - * Db to object. - * - * @param vertices the vertices - * @param obj the obj - * @param depth the depth - * @param cleanUp the clean up - * @return the introspector - * @throws AAIException the AAI exception - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws SecurityException the security exception - * @throws InstantiationException the instantiation exception - * @throws NoSuchMethodException the no such method exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws MalformedURLException the malformed URL exception - * @throws AAIUnknownObjectException - * @throws URISyntaxException - */ - public Introspector dbToObject(List<Vertex> vertices, final Introspector obj, int depth, boolean nodeOnly, String cleanUp) throws UnsupportedEncodingException, AAIException { - - final int internalDepth; - if (depth == Integer.MAX_VALUE) { - internalDepth = depth--; - } else { - internalDepth = depth; - } - if (vertices.size() > 1 && !obj.isContainer()) { - throw new AAIException("AAI_6136", "query object mismatch: this object cannot hold multiple items." + obj.getDbName()); - } else if (obj.isContainer()) { - final List getList; - String listProperty = null; - for (String property : obj.getProperties()) { - if (obj.isListType(property) && obj.isComplexGenericType(property)) { - listProperty = property; - break; - } - } - final String propertyName = listProperty; - getList = (List)obj.getValue(listProperty); - - /* This is an experimental multithreading experiment - * on get alls. - */ - ExecutorService pool = GetAllPool.getInstance().getPool(); - - List<Future<Object>> futures = new ArrayList<>(); - for (Vertex v : vertices) { - Callable<Object> task = () -> { - Set<Vertex> seen = new HashSet<>(); - Introspector childObject = obj.newIntrospectorInstanceOfNestedProperty(propertyName); - Tree<Element> tree = this.engine.getQueryEngine().findSubGraph(v, internalDepth, nodeOnly); - TreeBackedVertex treeVertex = new TreeBackedVertex(v, tree); - dbToObject(childObject, treeVertex, seen, internalDepth, nodeOnly, cleanUp); - return childObject.getUnderlyingObject(); - //getList.add(childObject.getUnderlyingObject()); - }; - futures.add(pool.submit(task)); - } - - for (Future<Object> future : futures) { - try { - getList.add(future.get()); - } catch (ExecutionException e) { - throw new AAIException("AAI_4000", e); - } catch (InterruptedException e) { - throw new AAIException("AAI_4000", e); - } - } - } else if (vertices.size() == 1) { - Set<Vertex> seen = new HashSet<>(); - Tree<Element> tree = this.engine.getQueryEngine().findSubGraph(vertices.get(0), depth, nodeOnly); - TreeBackedVertex treeVertex = new TreeBackedVertex(vertices.get(0), tree); - dbToObject(obj, treeVertex, seen, depth, nodeOnly, cleanUp); - } else { - //obj = null; - } - - - return obj; - } - - /** - * Db to object. - * - * @param obj the obj - * @param v the v - * @param seen the seen - * @param depth the depth - * @param cleanUp the clean up - * @return the introspector - * @throws IllegalAccessException the illegal access exception - * @throws IllegalArgumentException the illegal argument exception - * @throws InvocationTargetException the invocation target exception - * @throws SecurityException the security exception - * @throws InstantiationException the instantiation exception - * @throws NoSuchMethodException the no such method exception - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - * @throws MalformedURLException the malformed URL exception - * @throws AAIUnknownObjectException - * @throws URISyntaxException - */ - private Introspector dbToObject(Introspector obj, Vertex v, Set<Vertex> seen, int depth, boolean nodeOnly, String cleanUp) throws AAIException, UnsupportedEncodingException { - - if (depth < 0) { - return null; - } - depth--; - seen.add(v); - - boolean modified = false; - for (String property : obj.getProperties(PropertyPredicates.isVisible())) { - List<Object> getList = null; - Vertex[] vertices = null; - - if (!(obj.isComplexType(property) || obj.isListType(property))) { - this.copySimpleProperty(property, obj, v); - modified = true; - } else { - if (obj.isComplexType(property)) { - /* container case */ - - if (!property.equals("relationship-list") && depth >= 0) { - Introspector argumentObject = obj.newIntrospectorInstanceOfProperty(property); - Object result = dbToObject(argumentObject, v, seen, depth+1, nodeOnly, cleanUp); - if (result != null) { - obj.setValue(property, argumentObject.getUnderlyingObject()); - modified = true; - } - } else if (property.equals("relationship-list") && !nodeOnly){ - /* relationships need to be handled correctly */ - Introspector relationshipList = obj.newIntrospectorInstanceOfProperty(property); - relationshipList = createRelationshipList(v, relationshipList, cleanUp); - if (relationshipList != null) { - modified = true; - obj.setValue(property, relationshipList.getUnderlyingObject()); - modified = true; - } - - } - } else if (obj.isListType(property)) { - - if (property.equals("any")) { - continue; - } - String genericType = obj.getGenericTypeClass(property).getSimpleName(); - if (obj.isComplexGenericType(property) && depth >= 0) { - final String childDbName = convertFromCamelCase(genericType); - String vType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null); - EdgeRule rule; - - rule = edgeRules.getEdgeRule(EdgeType.TREE, vType, childDbName); - if (!rule.getContains().equals(AAIDirection.NONE.toString())) { - //vertices = this.queryEngine.findRelatedVertices(v, Direction.OUT, rule.getLabel(), childDbName); - Direction ruleDirection = rule.getDirection(); - Iterator<Vertex> itr = v.vertices(ruleDirection, rule.getLabel()); - List<Vertex> verticesList = (List<Vertex>)IteratorUtils.toList(itr); - itr = verticesList.stream().filter(item -> { - return item.property(AAIProperties.NODE_TYPE).orElse("").equals(childDbName); - }).iterator(); - if (itr.hasNext()) { - getList = (List<Object>)obj.getValue(property); - } - int processed = 0; - int removed = 0; - while (itr.hasNext()) { - Vertex childVertex = itr.next(); - if (!seen.contains(childVertex)) { - Introspector argumentObject = obj.newIntrospectorInstanceOfNestedProperty(property); - - Object result = dbToObject(argumentObject, childVertex, seen, depth, nodeOnly, cleanUp); - if (result != null && getList != null) { - getList.add(argumentObject.getUnderlyingObject()); - } - - processed++; - } else { - removed++; - LOGGER.warn("Cycle found while serializing vertex id={}", childVertex.id().toString()); - } - } - if (processed == 0) { - //vertices were all seen, reset the list - getList = null; - } - if (processed > 0) { - modified = true; - } - } - } else if (obj.isSimpleGenericType(property)) { - List<Object> temp = this.engine.getListProperty(v, property); - if (temp != null) { - getList = (List<Object>)obj.getValue(property); - getList.addAll(temp); - modified = true; - } - - } - - } - - } - } - - //no changes were made to this obj, discard the instance - if (!modified) { - return null; - } - this.enrichData(obj, v); - return obj; - - } - - - public Introspector getVertexProperties(Vertex v) throws AAIException, UnsupportedEncodingException { - String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null); - if (nodeType == null) { - throw new AAIException("AAI_6143"); - } - Introspector obj = this.latestLoader.introspectorFromName(nodeType); - Set<Vertex> seen = new HashSet<>(); - int depth = 0; - String cleanUp = "false"; - boolean nodeOnly = true; - this.dbToObject(obj, v, seen, depth, nodeOnly, cleanUp); - - return obj; - - } - public Introspector getLatestVersionView(Vertex v) throws AAIException, UnsupportedEncodingException { - String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null); - if (nodeType == null) { - throw new AAIException("AAI_6143"); - } - Introspector obj = this.latestLoader.introspectorFromName(nodeType); - Set<Vertex> seen = new HashSet<>(); - int depth = AAIProperties.MAXIMUM_DEPTH; - String cleanUp = "false"; - boolean nodeOnly = false; - Tree<Element> tree = this.engine.getQueryEngine().findSubGraph(v, depth, nodeOnly); - TreeBackedVertex treeVertex = new TreeBackedVertex(v, tree); - this.dbToObject(obj, treeVertex, seen, depth, nodeOnly, cleanUp); - - return obj; - } - /** - * Copy simple property. - * - * @param property the property - * @param obj the obj - * @param v the v - * @throws InstantiationException the instantiation exception - * @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 - */ - private void copySimpleProperty(String property, Introspector obj, Vertex v) { - final Map<PropertyMetadata, String> metadata = obj.getPropertyMetadata(property); - String dbPropertyName = property; - if (metadata.containsKey(PropertyMetadata.DB_ALIAS)) { - dbPropertyName = metadata.get(PropertyMetadata.DB_ALIAS); - } - final Object temp = v.<Object>property(dbPropertyName).orElse(null); - if (temp != null) { - - obj.setValue(property, temp); - } - } - - /** - * Simple db to object. - * - * @param obj the obj - * @param v the v - * @throws InstantiationException the instantiation exception - * @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 - */ - private void simpleDbToObject (Introspector obj, Vertex v) { - for (String property : obj.getProperties()) { - - - if (!(obj.isComplexType(property) || obj.isListType(property))) { - this.copySimpleProperty(property, obj, v); - } - } - } - - /** - * Creates the relationship list. - * - * @param v the v - * @param obj the obj - * @param cleanUp the clean up - * @return the object - * @throws InstantiationException the instantiation exception - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - * @throws MalformedURLException the malformed URL exception - * @throws URISyntaxException - */ - private Introspector createRelationshipList(Vertex v, Introspector obj, String cleanUp) throws UnsupportedEncodingException, AAIException { - - - List<Vertex> cousins = this.engine.getQueryEngine().findCousinVertices(v); - - List<Object> relationshipObjList = obj.getValue("relationship"); - - for (Vertex cousin : cousins) { - - Introspector relationshipObj = obj.newIntrospectorInstanceOfNestedProperty("relationship"); - Object result = processEdgeRelationship(relationshipObj, cousin, cleanUp); - if (result != null) { - relationshipObjList.add(result); - } - - } - - if (relationshipObjList.isEmpty()) { - return null; - } else { - return obj; - } - } - - /** - * Process edge relationship. - * - * @param relationshipObj the relationship obj - * @param edge the edge - * @param direction the direction - * @param cleanUp the clean up - * @return the object - * @throws InstantiationException the instantiation exception - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - * @throws MalformedURLException the malformed URL exception - * @throws AAIUnknownObjectException - * @throws URISyntaxException - */ - private Object processEdgeRelationship(Introspector relationshipObj, Vertex cousin, String cleanUp) throws UnsupportedEncodingException, AAIUnknownObjectException { - - - //we must look up all parents in this case because we need to compute name-properties - //we cannot used the cached aaiUri to perform this action currently - Optional<Pair<Vertex, List<Introspector>>> tuple = this.getParents(relationshipObj.getLoader(), cousin, "true".equals(cleanUp)); - //damaged vertex found, ignore - if (!tuple.isPresent()) { - return null; - } - List<Introspector> list = tuple.get().getValue1(); - URI uri = this.getURIFromList(list); - - URIToRelationshipObject uriParser = null; - Introspector result = null; - try { - uriParser = new URIToRelationshipObject(relationshipObj.getLoader(), uri, this.baseURL); - result = uriParser.getResult(); - } catch (AAIException | URISyntaxException e) { - LOGGER.error("Error while processing edge relationship in version " + relationshipObj.getVersion() + " (bad vertex ID=" + tuple.get().getValue0().id().toString() + ": " + e.getMessage(), e); - if ("true".equals(cleanUp)) { - this.deleteWithTraversal(tuple.get().getValue0()); - } - return null; - } - - if(list.size() > 0 && this.version.compareTo(Version.v8) >= 0){ - this.addRelatedToProperty(result, list.get(0)); - } - - return result.getUnderlyingObject(); - } - - /** - * Gets the URI for vertex. - * - * @param v the v - * @return the URI for vertex - * @throws InstantiationException the instantiation exception - * @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 UnsupportedEncodingException the unsupported encoding exception - * @throws AAIUnknownObjectException - */ - public URI getURIForVertex(Vertex v) throws UnsupportedEncodingException { - - return getURIForVertex(v, false); - } - - public URI getURIForVertex(Vertex v, boolean overwrite) throws UnsupportedEncodingException { - URI uri = UriBuilder.fromPath("/unknown-uri").build(); - - String aaiUri = v.<String>property(AAIProperties.AAI_URI).orElse(null); - - if (aaiUri != null && !overwrite) { - uri = UriBuilder.fromPath(aaiUri).build(); - } else { - Optional<Pair<Vertex, List<Introspector>>> tuple = this.getParents(this.loader, v, false); - if (tuple.isPresent()) { - List<Introspector> list = tuple.get().getValue1(); - uri = this.getURIFromList(list); - } - } - return uri; - } - /** - * Gets the URI from list. - * - * @param list the list - * @return the URI from list - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - private URI getURIFromList(List<Introspector> list) throws UnsupportedEncodingException { - String uri = ""; - StringBuilder sb = new StringBuilder(); - for (Introspector i : list) { - sb.insert(0, i.getURI()); - } - - uri = sb.toString(); - URI result = UriBuilder.fromPath(uri).build(); - return result; - } - - /** - * Gets the parents. - * - * @param start the start - * @param removeDamaged the remove damaged - * @return the parents - * @throws InstantiationException the instantiation exception - * @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 AAIUnknownObjectException - */ - private Optional<Pair<Vertex, List<Introspector>>> getParents(Loader loader, Vertex start, boolean removeDamaged) { - - List<Vertex> results = this.engine.getQueryEngine().findParents(start); - List<Introspector> objs = new ArrayList<>(); - boolean shortCircuit = false; - for (Vertex v : results) { - String nodeType = v.<String>property(AAIProperties.NODE_TYPE).orElse(null); - Introspector obj = null; - //vertex on the other end of this edge is bad - if (nodeType == null) { - //log something here about what was found and that it was removed - ErrorLogHelper.logError("AAI-6143", "Found a damaged parent vertex " + v.id().toString()); - if (removeDamaged) { - this.deleteWithTraversal(v); - } - shortCircuit = true; - } else { - try { - obj = loader.introspectorFromName(nodeType); - } catch (AAIUnknownObjectException e) { - LOGGER.info("attempted to create node type " + nodeType + " but we do not understand it for version: " + loader.getVersion()); - obj = null; - } - } - - if (obj == null) { - //can't make a valid path because we don't understand this object - // don't include it - } else { - this.simpleDbToObject(obj, v); - objs.add(obj); - } - } - - //stop processing and don't return anything for this bad vertex - if (shortCircuit) { - return Optional.empty(); - } - - return Optional.of(new Pair<>(results.get(results.size()-1), objs)); - } - /** - * Takes a list of vertices and a list of objs and assumes they are in - * the order you want the URIs to be nested. - * [A,B,C] creates uris [A, AB, ABC] - * @param vertices - * @param objs - * @throws UnsupportedEncodingException - * @throws URISyntaxException - */ - public void setCachedURIs(List<Vertex> vertices, List<Introspector> objs) throws UnsupportedEncodingException, URISyntaxException { - - String uriChain = ""; - for (int i = 0; i < vertices.size(); i++) { - String aaiUri = ""; - Vertex v = null; - v = vertices.get(i); - aaiUri = v.<String>property(AAIProperties.AAI_URI).orElse(null); - if (aaiUri != null) { - uriChain += aaiUri; - } else { - URI uri = UriBuilder.fromPath(objs.get(i).getURI()).build(); - aaiUri = uri.toString(); - uriChain += aaiUri; - v.property(AAIProperties.AAI_URI, uriChain); - } - } - - - - } - - - /** - * Adds the r - * @throws AAIUnknownObjectException - * @throws IllegalArgumentException elated to property. - * - * @param relationship the relationship - * @param child the throws IllegalArgumentException, AAIUnknownObjectException child - */ - public void addRelatedToProperty(Introspector relationship, Introspector child) throws AAIUnknownObjectException { - String nameProps = child.getMetadata(ObjectMetadata.NAME_PROPS); - List<Introspector> relatedToProperties = new ArrayList<>(); - - if (nameProps != null) { - String[] props = nameProps.split(","); - for (String prop : props) { - Introspector relatedTo = relationship.newIntrospectorInstanceOfNestedProperty("related-to-property"); - relatedTo.setValue("property-key", child.getDbName() + "." + prop); - relatedTo.setValue("property-value", child.getValue(prop)); - relatedToProperties.add(relatedTo); - } - } - - if (relatedToProperties.size() > 0) { - List relatedToList = (List)relationship.getValue("related-to-property"); - for (Introspector obj : relatedToProperties) { - relatedToList.add(obj.getUnderlyingObject()); - } - } - - } - - /** - * Creates the edge. - * - * @param relationship the relationship - * @param inputVertex the input vertex - * @return true, if successful - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public boolean createEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException { - - Vertex relatedVertex = null; - - QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship); - - List<Vertex> results = parser.getQueryBuilder().toList(); - if (results.size() == 0) { - AAIException e = new AAIException("AAI_6129", "Node of type " + parser.getResultType() + ". Could not find object at: " + parser.getUri()); - e.getTemplateVars().add(parser.getResultType()); - e.getTemplateVars().add(parser.getUri().toString()); - throw e; - } else { - //still an issue if there's more than one - relatedVertex = results.get(0); - } - - if (relatedVertex != null) { - - Edge e; - try { - e = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex); - if (e == null) { - edgeRules.addEdge(this.engine.asAdmin().getTraversalSource(), inputVertex, relatedVertex); - - } else { - //attempted to link two vertexes already linked - } - } catch (NoEdgeRuleFoundException e1) { - throw new AAIException("AAI_6129", e1); - } - - - - - } - - return true; - } - - /** - * Gets the edges between. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edges between - * @throws AAIException the AAI exception - * @throws NoEdgeRuleFoundException - */ - private List<Edge> getEdgesBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException, NoEdgeRuleFoundException { - - List<Edge> result = new ArrayList<>(); - - if (bVertex != null) { - EdgeRule rule = edgeRules.getEdgeRule(type, aVertex, bVertex); - GraphTraversal<Vertex, Edge> findEdgesBetween = null; - findEdgesBetween = this.engine.asAdmin().getTraversalSource().V(aVertex).bothE(rule.getLabel()).filter(__.otherV().hasId(bVertex.id())); - List<Edge> edges = findEdgesBetween.toList(); - for (Edge edge : edges) { - if (edge.label().equals(rule.getLabel())) { - result.add(edge); - } - } - - } - - return result; - } - - /** - * Gets the edge between. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edge between - * @throws AAIException the AAI exception - * @throws NoEdgeRuleFoundException - */ - public Edge getEdgeBetween(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException { - - - - if (bVertex != null) { - - List<Edge> edges = this.getEdgesBetween(type, aVertex, bVertex); - - if (edges.size() > 0) { - return edges.get(0); - } - - } - - return null; - } - - - /** - * Delete edge. - * - * @param relationship the relationship - * @param inputVertex the input vertex - * @return true, if successful - * @throws UnsupportedEncodingException the unsupported encoding exception - * @throws AAIException the AAI exception - */ - public boolean deleteEdge(Introspector relationship, Vertex inputVertex) throws UnsupportedEncodingException, AAIException { - - Vertex relatedVertex = null; - - QueryParser parser = engine.getQueryBuilder().createQueryFromRelationship(relationship); - - List<Vertex> results = parser.getQueryBuilder().toList(); - - if (results.size() == 0) { - return false; - } - - relatedVertex = results.get(0); - Edge edge; - try { - edge = this.getEdgeBetween(EdgeType.COUSIN, inputVertex, relatedVertex); - } catch (NoEdgeRuleFoundException e) { - throw new AAIException("AAI_6129", e); - } - if (edge != null) { - edge.remove(); - return true; - } else { - return false; - } - - } - - /** - * Delete items with traversal. - * - * @param vertexes the vertexes - * @throws IllegalStateException the illegal state exception - */ - public void deleteItemsWithTraversal(List<Vertex> vertexes) throws IllegalStateException { - for (Vertex v : vertexes) { - LOGGER.debug("About to delete the vertex with id: " + v.id()); - deleteWithTraversal(v); - } - } - - /** - * Delete with traversal. - * - * @param startVertex the start vertex - */ - public void deleteWithTraversal(Vertex startVertex) { - - List<Vertex> results = this.engine.getQueryEngine().findDeletable(startVertex); - - for (Vertex v : results) { - LOGGER.warn("Removing vertex " + v.id().toString()); - - v.remove(); - } - - } - - /** - * Delete. - * - * @param v the v - * @param resourceVersion the resource version - * @throws IllegalArgumentException the illegal argument exception - * @throws AAIException the AAI exception - * @throws InterruptedException the interrupted exception - */ - public void delete(Vertex v, String resourceVersion, boolean enableResourceVersion) throws IllegalArgumentException, AAIException { - - boolean result = verifyDeleteSemantics(v, resourceVersion, enableResourceVersion); - if (result) { - try { - deleteWithTraversal(v); - } catch (IllegalStateException e) { - throw new AAIException("AAI_6110", e); - } - - } - - } - - - /** - * Verify delete semantics. - * - * @param vertex the vertex - * @param resourceVersion the resource version - * @return true, if successful - * @throws AAIException the AAI exception - */ - private boolean verifyDeleteSemantics(Vertex vertex, String resourceVersion, boolean enableResourceVersion) throws AAIException { - boolean result = true; - String nodeType = ""; - String errorDetail = " unknown delete semantic found"; - String aaiExceptionCode = ""; - nodeType = vertex.<String>property(AAIProperties.NODE_TYPE).orElse(null); - if (enableResourceVersion && !this.verifyResourceVersion("delete", nodeType, vertex.<String>property(AAIProperties.RESOURCE_VERSION).orElse(null), resourceVersion, nodeType)) { - } - List<Object> preventDeleteVertices = this.engine.asAdmin().getReadOnlyTraversalSource().V(vertex).union(__.inE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.IN.toString()).outV().values(AAIProperties.NODE_TYPE), __.outE().has(EdgeProperty.PREVENT_DELETE.toString(), AAIDirection.OUT.toString()).inV().values(AAIProperties.NODE_TYPE)).dedup().toList(); - - if (preventDeleteVertices.size() > 0) { - aaiExceptionCode = "AAI_6110"; - errorDetail = String.format("Object is being reference by additional objects preventing it from being deleted. Please clean up references from the following types %s", preventDeleteVertices); - result = false; - } - if (!result) { - throw new AAIException(aaiExceptionCode, errorDetail); - } - return result; - } - - /** - * Verify resource version. - * - * @param action the action - * @param nodeType the node type - * @param currentResourceVersion the current resource version - * @param resourceVersion the resource version - * @param uri the uri - * @return true, if successful - * @throws AAIException the AAI exception - */ - public boolean verifyResourceVersion(String action, String nodeType, String currentResourceVersion, String resourceVersion, String uri) throws AAIException { - String enabled = ""; - String errorDetail = ""; - String aaiExceptionCode = ""; - if (currentResourceVersion == null) { - currentResourceVersion = ""; - } - - if (resourceVersion == null) { - resourceVersion = ""; - } - try { - enabled = AAIConfig.get(AAIConstants.AAI_RESVERSION_ENABLEFLAG); - } catch (AAIException e) { - ErrorLogHelper.logException(e); - } - // We're only doing the resource version checks for v5 and later - if (enabled.equals("true") && this.version.compareTo(Version.v8) > 0) { - if (!currentResourceVersion.equals(resourceVersion)) { - if (action.equals("create") && !resourceVersion.equals("")) { - errorDetail = "resource-version passed for " + action + " of " + uri; - aaiExceptionCode = "AAI_6135"; - } else if (resourceVersion.equals("")) { - errorDetail = "resource-version not passed for " + action + " of " + uri; - aaiExceptionCode = "AAI_6130"; - } else { - errorDetail = "resource-version MISMATCH for " + action + " of " + uri; - aaiExceptionCode = "AAI_6131"; - } - - throw new AAIException(aaiExceptionCode, errorDetail); - - } - } - return true; - } - - /** - * Convert from camel case. - * - * @param name the name - * @return the string - */ - private String convertFromCamelCase (String name) { - String result = ""; - result = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name); - - NamingExceptions exceptions = NamingExceptions.getInstance(); - result = exceptions.getDBName(result); - - return result; - } - - private boolean canModify(Introspector obj, String propName, String requestContext) { - final String readOnly = obj.getPropertyMetadata(propName).get(PropertyMetadata.READ_ONLY); - if (readOnly != null) { - final String[] items = readOnly.split(","); - for (String item : items) { - if (requestContext.equals(item)) { - return false; - } - } - } - return true; - } - - private void executePreSideEffects(Introspector obj, Vertex self) throws AAIException { - - SideEffectRunner runner = new SideEffectRunner - .Builder(this.engine, this).addSideEffect(DataCopy.class).build(); - - runner.execute(obj, self); - } - - private void executePostSideEffects(Introspector obj, Vertex self) throws AAIException { - - SideEffectRunner runner = new SideEffectRunner - .Builder(this.engine, this).addSideEffect(DataLinkWriter.class).build(); - - runner.execute(obj, self); - } - - private void enrichData(Introspector obj, Vertex self) throws AAIException { - - SideEffectRunner runner = new SideEffectRunner - .Builder(this.engine, this).addSideEffect(DataLinkReader.class).build(); - - runner.execute(obj, self); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DeleteSemantic.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/DeleteSemantic.java deleted file mode 100644 index 5b153c29..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/DeleteSemantic.java +++ /dev/null @@ -1,40 +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.serialization.db; - - -/** - * Possible values for deleteScope can be: - * USE_DEFAULT - Get the scope from ref data for this node - * THIS_NODE_ONLY (but should fail if it there are nodes that depend on it for uniqueness) - * CASCADE_TO_CHILDREN - will look for OUT-Edges that have parentOf/hasDelTarget = true and follow those down - * ERROR_4_IN_EDGES_OR_CASCADE - combo of error-if-any-IN-edges + CascadeToChildren - * ERROR_IF_ANY_IN_EDGES - Fail if this node has any existing IN edges - * ERROR_IF_ANY_EDGES - Fail if this node has any existing edges at all! - */ -public enum DeleteSemantic { - USE_DEFAULT, - THIS_NODE_ONLY, - CASCADE_TO_CHILDREN, - ERROR_4_IN_EDGES_OR_CASCADE, - ERROR_IF_ANY_IN_EDGES, - ERROR_IF_ANY_EDGES, -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperties.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperties.java deleted file mode 100644 index 8ce1d1c9..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperties.java +++ /dev/null @@ -1,43 +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.serialization.db; - -public class EdgeProperties { - - public static String out(EdgeProperty prop) { - - return out(prop.toString()); - } - - public static String in(EdgeProperty prop) { - return in(prop.toString()); - } - - public static String out(String prop) { - - return prop; - } - - public static String in(String prop) { - return prop + "-REV"; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperty.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperty.java deleted file mode 100644 index 21f07451..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeProperty.java +++ /dev/null @@ -1,44 +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.serialization.db; - -public enum EdgeProperty { - FROM("from"), - TO("to"), - LABEL("label"), - DIRECTION("direction"), - MULTIPLICITY("multiplicity"), - CONTAINS("contains-other-v"), - DELETE_OTHER_V("delete-other-v"), - SVC_INFRA("SVC-INFRA"), - PREVENT_DELETE("prevent-delete"); - - private final String name; - - private EdgeProperty(String name) { - this.name = name; - } - - @Override - public String toString() { - return name; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgePropertyMap.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgePropertyMap.java deleted file mode 100644 index bce2c313..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgePropertyMap.java +++ /dev/null @@ -1,59 +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.serialization.db; - -import org.apache.tinkerpop.gremlin.structure.Direction; - -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class EdgePropertyMap<K, V> extends HashMap<K, V> { - - private static final long serialVersionUID = -8298355506617458683L; - - private static final Pattern variablePattern = Pattern.compile("(!)?\\$\\{(\\w+)\\}"); - - @Override - public V get(Object arg0) { - - V value = super.get(arg0); - - Matcher m = variablePattern.matcher(value.toString()); - if (m.find()) { - if (m.groupCount() == 2) { - if (m.group(1) == null) { - value = super.get(m.group(2)); - } else { - value = reverse(super.get(m.group(2))); - } - } - } - - return value; - } - - - protected V reverse(V value) { - - return (V)Direction.valueOf(value.toString()).opposite().toString(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRule.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRule.java deleted file mode 100644 index 1b6c19f0..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRule.java +++ /dev/null @@ -1,210 +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.serialization.db; - -import org.apache.tinkerpop.gremlin.structure.Direction; - -import java.util.HashMap; -import java.util.Map; - -public class EdgeRule { - - private String label = ""; - private MultiplicityRule multiplicityRule = null; - private Direction direction = null; - private Map<EdgeProperty, String> edgeProperties = null; - - /** - * Instantiates a new edge rule. - */ - public EdgeRule() { - edgeProperties = new HashMap<>(); - } - - /** - * Gets the label. - * - * @return the label - */ - public String getLabel() { - return label; - } - - /** - * Sets the label. - * - * @param label the new label - */ - public void setLabel(String label) { - this.label = label; - } - - /** - * Gets the multiplicity rule. - * - * @return the multiplicity rule - */ - public MultiplicityRule getMultiplicityRule() { - return multiplicityRule; - } - - public void setMultiplicityRule(String multiplicity){ - if ("Many2Many".equalsIgnoreCase(multiplicity)) { - this.multiplicityRule = MultiplicityRule.MANY2MANY; - } else if ("One2Many".equalsIgnoreCase(multiplicity)) { - this.multiplicityRule = MultiplicityRule.ONE2MANY; - } else if ("One2One".equalsIgnoreCase(multiplicity)) { - this.multiplicityRule = MultiplicityRule.ONE2ONE; - } else { //should be "Many2One" - this.multiplicityRule = MultiplicityRule.MANY2ONE; - } - } - - /** - * Sets the multiplicity rule. - * - * @param multiplicityRule the new multiplicity rule - */ - public void setMultiplicityRule(MultiplicityRule multiplicityRule) { - this.multiplicityRule = multiplicityRule; - } - - /** - * Gets the direction. - * - * @return the direction - */ - public Direction getDirection() { - return direction; - } - - public void setDirection(String direction){ - if ("OUT".equalsIgnoreCase(direction)) { - this.direction = Direction.OUT; - } else if ("IN".equalsIgnoreCase(direction)) { - this.direction = Direction.IN; - } else { - this.direction = Direction.BOTH; - } - } - - /** - * Sets the direction. - * - * @param direction the new direction - */ - public void setDirection(Direction direction) { - this.direction = direction; - } - - /** - * Gets the checks if is parent. - * - * @return the checks if is parent - */ - public String getContains() { - return this.getProp(EdgeProperty.CONTAINS); - } - - /** - * Sets the checks if is parent. - * - * @param isParent the new checks if is parent - */ - public void setContains(String isParent) { - this.setProp(EdgeProperty.CONTAINS, isParent); - } - - /** - * Gets the checks for del target. - * - * @return the checks for del target - */ - public String getDeleteOtherV() { - return this.getProp(EdgeProperty.DELETE_OTHER_V); - } - - /** - * Sets the checks for del target. - * - * @param hasDelTarget the new checks for del target - */ - public void setDeleteOtherV(String hasDelTarget) { - this.setProp(EdgeProperty.DELETE_OTHER_V, hasDelTarget); - } - - /** - * Gets the service infrastructure. - * - * @return the service infrastructure - */ - public String getServiceInfrastructure() { - return this.getProp(EdgeProperty.SVC_INFRA); - } - - /** - * Sets the service infrastructure. - * - * @param serviceInfrastructure the new service infrastructure - */ - public void setServiceInfrastructure(String serviceInfrastructure) { - this.setProp(EdgeProperty.SVC_INFRA, serviceInfrastructure); - } - - public String getPreventDelete() { - return this.getProp(EdgeProperty.PREVENT_DELETE); - } - - public void setPreventDelete(String preventDelete) { - this.setProp(EdgeProperty.PREVENT_DELETE, preventDelete); - } - - /** - * Gets the edge properties. - * - * @return the edge properties - */ - public Map<EdgeProperty, String> getEdgeProperties() { - return this.edgeProperties; - } - - /** - * Sets the prop. - * - * @param key the key - * @param value the value - */ - private void setProp(EdgeProperty key, String value) { - this.edgeProperties.put(key, value); - } - - /** - * Gets the prop. - * - * @param key the key - * @return the prop - */ - private String getProp(EdgeProperty key) { - return this.edgeProperties.get(key); - } - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRules.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRules.java deleted file mode 100644 index f819b9ea..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeRules.java +++ /dev/null @@ -1,588 +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.serialization.db; - -import static com.jayway.jsonpath.Criteria.where; -import static com.jayway.jsonpath.Filter.filter; - -import java.io.InputStream; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.Scanner; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.exceptions.EdgeMultiplicityException; -import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Multimap; -import com.jayway.jsonpath.DocumentContext; -import com.jayway.jsonpath.Filter; -import com.jayway.jsonpath.JsonPath; - -public class EdgeRules { - - private EELFLogger logger = EELFManager.getInstance().getLogger(EdgeRules.class); - - private DocumentContext rulesDoc; - - /** - * Loads the most recent DbEdgeRules json file for later parsing. - * Only need most recent version for actual A&AI operations that call this class; - * the old ones are only used in tests. - */ - private EdgeRules() { - - String json = this.getEdgeRuleJson(Version.getLatest()); - rulesDoc = JsonPath.parse(json); - - } - - private EdgeRules(String rulesFilename) { - String json = this.getEdgeRuleJson(rulesFilename); - rulesDoc = JsonPath.parse(json); - } - - private String getEdgeRuleJson(String rulesFilename) { - InputStream is = getClass().getResourceAsStream(rulesFilename); - - Scanner scanner = new Scanner(is); - String json = scanner.useDelimiter("\\Z").next(); - scanner.close(); - - return json; - } - - /** - * Loads the versioned DbEdgeRules json file for later parsing. - */ - @SuppressWarnings("unchecked") - private EdgeRules(Version version) { - String json = this.getEdgeRuleJson(version); - rulesDoc = JsonPath.parse(json); - } - - private String getEdgeRuleJson(Version version) { - InputStream is = getClass().getResourceAsStream("/dbedgerules/DbEdgeRules_" + version.toString() + ".json"); - - Scanner scanner = new Scanner(is); - String json = scanner.useDelimiter("\\Z").next(); - scanner.close(); - - return json; - } - - private static class Helper { - private static final EdgeRules INSTANCE = new EdgeRules(); - private static final Map<Version, EdgeRules> INSTANCEMAP = new ConcurrentHashMap<>(); - - private static EdgeRules getEdgeRulesByFilename(String rulesFilename) { - return new EdgeRules(rulesFilename); - } - - private static EdgeRules getVersionedEdgeRules(Version v) { - if (Version.isLatest(v)) { - return INSTANCE; - } - if (!INSTANCEMAP.containsKey(v)) { - INSTANCEMAP.put(v, new EdgeRules(v)); - } - return INSTANCEMAP.get(v); - } - } - - /** - * Gets the single instance of EdgeRules. - * - * @return single instance of EdgeRules - */ - public static EdgeRules getInstance() { - return Helper.INSTANCE; - - } - - /** - * Gets the versioned instance of EdgeRules. - * - * @return versioned instance of EdgeRules - */ - public static EdgeRules getInstance(Version v) { - return Helper.getVersionedEdgeRules(v); - - } - - /** - * Loads edge rules from the given file. - * - * @param rulesFilename - name of the file to load rules from - * @return the EdgeRules instance - */ - public static EdgeRules getInstance(String rulesFilename) { - return Helper.getEdgeRulesByFilename(rulesFilename); - } - - /** - * Adds the tree edge. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edge - * @throws AAIException the AAI exception - */ - public Edge addTreeEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException { - return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, false); - } - - /** - * Adds the edge. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edge - * @throws AAIException the AAI exception - */ - public Edge addEdge(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException { - return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, false); - } - - /** - * Adds the tree edge. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edge - * @throws AAIException the AAI exception - */ - public Edge addTreeEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException { - return this.addEdge(EdgeType.TREE, traversalSource, aVertex, bVertex, true); - } - - /** - * Adds the edge. - * - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edge - * @throws AAIException the AAI exception - */ - public Edge addEdgeIfPossible(GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) throws AAIException { - return this.addEdge(EdgeType.COUSIN, traversalSource, aVertex, bVertex, true); - } - - /** - * Adds the edge. - * - * @param type the type - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return the edge - * @throws AAIException the AAI exception - */ - private Edge addEdge(EdgeType type, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex, boolean isBestEffort) throws AAIException { - - EdgeRule rule = this.getEdgeRule(type, aVertex, bVertex); - - Edge e = null; - - Optional<String> message = this.validateMultiplicity(rule, traversalSource, aVertex, bVertex); - - if (message.isPresent() && !isBestEffort) { - throw new EdgeMultiplicityException(message.get()); - } - if (!message.isPresent()) { - if (rule.getDirection().equals(Direction.OUT)) { - e = aVertex.addEdge(rule.getLabel(), bVertex); - } else if (rule.getDirection().equals(Direction.IN)) { - e = bVertex.addEdge(rule.getLabel(), aVertex); - } - - this.addProperties(e, rule); - } - return e; - } - - /** - * Adds the properties. - * - * @param edge the edge - * @param rule the rule - */ - public void addProperties(Edge edge, EdgeRule rule) { - - // In DbEdgeRules.EdgeRules -- What we have as "edgeRule" is a comma-delimited set of strings. - // The first item is the edgeLabel. - // The second in the list is always "direction" which is always OUT for the way we've implemented it. - // Items starting at "firstTagIndex" and up are all assumed to be booleans that map according to - // tags as defined in EdgeInfoMap. - // Note - if they are tagged as 'reverse', that means they get the tag name with "-REV" on it - Map<EdgeProperty, String> propMap = rule.getEdgeProperties(); - - for (Entry<EdgeProperty, String> entry : propMap.entrySet()) { - edge.property(entry.getKey().toString(), entry.getValue()); - } - } - - /** - * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order. - * - * @param nodeA - node at one end of the edge - * @param nodeB - node at the other end - * @return true, if any such rules exist - */ - public boolean hasEdgeRule(String nodeA, String nodeB) { - Filter aToB = filter( - where("from").is(nodeA).and("to").is(nodeB) - ); - Filter bToA = filter( - where("from").is(nodeB).and("to").is(nodeA) - ); - - List<Map<String, String>> results = readRules(aToB); - results.addAll(readRules(bToA)); - - return !results.isEmpty(); - - } - - /** - * Checks if any edge rules exist between the two given nodes, in either A|B or B|A order. - * - * @param aVertex - node at one end of the edge - * @param bVertex - node at the other end - * @return true, if any such rules exist - */ - public boolean hasEdgeRule(Vertex aVertex, Vertex bVertex) { - String outType = aVertex.<String>property("aai-node-type").orElse(null); - String inType = bVertex.<String>property("aai-node-type").orElse(null); - - return this.hasEdgeRule(outType, inType); - - } - - /** - * Gets all the edge rules that exist between the given node types. - * The rules will be phrased in terms of out|in, though this will - * also find rules defined as in|out (it will flip the direction in - * the EdgeRule object returned accordingly to match out|in). - * - * @param outType - * @param inType - * @return Map<String edgeLabel, EdgeRule rule> where edgeLabel is the label name - * @throws AAIException - */ - public Map<String, EdgeRule> getEdgeRules(String outType, String inType) throws AAIException { - Map<String, EdgeRule> result = new HashMap<>(); - EdgeRule rule = null; - for (EdgeType type : EdgeType.values()) { - try { - rule = this.getEdgeRule(type, outType, inType); - result.put(rule.getLabel(), rule); - } catch (NoEdgeRuleFoundException e) { - continue; - } - } - - return result; - } - - - - /** - * Gets the edge rule of the given type that exists between A and B. - * Will check B|A as well, and flips the direction accordingly if that succeeds - * to match the expected A|B return. - * - * @param type - the type of edge you're looking for - * @param nodeA - first node type - * @param nodeB - second node type - * @return EdgeRule describing the rule in terms of A|B, if there is any such rule - * @throws AAIException if no such edge exists - */ - public EdgeRule getEdgeRule(EdgeType type, String nodeA, String nodeB) throws AAIException { - //try A to B - List<Map<String, String>> aToBEdges = readRules(buildFilter(type, nodeA, nodeB)); - if (!aToBEdges.isEmpty()) { - //lazily stop iterating if we find a match - //should there be a mismatch between type and isParent, - //the caller will receive something. - //this operates on the assumption that there are at most two rules - //for a given vertex pair - verifyRule(aToBEdges.get(0)); - return buildRule(aToBEdges.get(0)); - } - - //we get here if there was nothing for A to B, so let's try B to A - List<Map<String, String>> bToAEdges = readRules(buildFilter(type, nodeB, nodeA)); - if (!bToAEdges.isEmpty()) { - verifyRule(bToAEdges.get(0)); - return flipDirection(buildRule(bToAEdges.get(0))); //bc we need to return as A|B, so flip the direction to match - } - - //found none - throw new NoEdgeRuleFoundException("no " + type.toString() + " edge between " + nodeA + " and " + nodeB); - } - - /** - * Builds a JsonPath filter to search for an edge from nodeA to nodeB with the given edge type (cousin or parent/child) - * - * @param type - * @param nodeA - start node - * @param nodeB - end node - * @return - */ - private Filter buildFilter(EdgeType type, String nodeA, String nodeB) { - if (EdgeType.COUSIN.equals(type)) { - return filter( - where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is(AAIDirection.NONE.toString()) - ); - } else { - return filter( - where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("${direction}")).or( - where("from").is(nodeA).and("to").is(nodeB).and(EdgeProperty.CONTAINS.toString()).is("!${direction}") - ); - } - } - - /** - * Puts the give edge rule information into an EdgeRule object. - * - * @param edge - the edge information returned from JsonPath - * @return EdgeRule containing that information - */ - private EdgeRule buildRule(Map<String, String> map) { - Map<String, String> edge = new EdgePropertyMap<>(); - edge.putAll(map); - - EdgeRule rule = new EdgeRule(); - rule.setLabel(edge.get("label")); - rule.setDirection(edge.get("direction")); - rule.setMultiplicityRule(edge.get("multiplicity")); - rule.setContains(edge.get(EdgeProperty.CONTAINS.toString())); - rule.setDeleteOtherV(edge.get(EdgeProperty.DELETE_OTHER_V.toString())); - rule.setServiceInfrastructure(edge.get(EdgeProperty.SVC_INFRA.toString())); - rule.setPreventDelete(edge.get(EdgeProperty.PREVENT_DELETE.toString())); - - return rule; - } - - /** - * If getEdgeRule gets a request for A|B, and it finds something as B|A, the caller still expects - * the returned EdgeRule to reflect A|B directionality. This helper method flips B|A direction to - * match this expectation. - * - * @param rule whose direction needs flipped - * @return the updated rule - */ - private EdgeRule flipDirection(EdgeRule rule) { - if (Direction.IN.equals(rule.getDirection())) { - rule.setDirection(Direction.OUT); - return rule; - } else if (Direction.OUT.equals(rule.getDirection())) { - rule.setDirection(Direction.IN); - return rule; - } else { //direction is BOTH, flipping both is still both - return rule; - } - } - - /** - * Gets the edge rule of the given type that exists between A and B. - * Will check B|A as well, and flips the direction accordingly if that succeeds - * to match the expected A|B return. - * - * @param type - the type of edge you're looking for - * @param aVertex - first node type - * @param bVertex - second node type - * @return EdgeRule describing the rule in terms of A|B, if there is any such rule - * @throws AAIException if no such edge exists - */ - public EdgeRule getEdgeRule(EdgeType type, Vertex aVertex, Vertex bVertex) throws AAIException { - String outType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null); - String inType = bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null); - - return this.getEdgeRule(type, outType, inType); - - - } - - /** - * Validate multiplicity. - * - * @param rule the rule - * @param aVertex the out vertex - * @param bVertex the in vertex - * @return true, if successful - * @throws AAIException the AAI exception - */ - private Optional<String> validateMultiplicity(EdgeRule rule, GraphTraversalSource traversalSource, Vertex aVertex, Vertex bVertex) { - - if (rule.getDirection().equals(Direction.OUT)) { - - } else if (rule.getDirection().equals(Direction.IN)) { - Vertex tempV = bVertex; - bVertex = aVertex; - aVertex = tempV; - } - - String aVertexType = aVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null); - String bVertexType = bVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null); - String label = rule.getLabel(); - MultiplicityRule multiplicityRule = rule.getMultiplicityRule(); - List<Edge> outEdges = traversalSource.V(aVertex).outE(label).where(__.inV().has(AAIProperties.NODE_TYPE, bVertexType)).toList(); - List<Edge> inEdges = traversalSource.V(bVertex).inE(label).where(__.outV().has(AAIProperties.NODE_TYPE, aVertexType)).toList(); - String detail = ""; - if (multiplicityRule.equals(MultiplicityRule.ONE2ONE)) { - if (inEdges.size() >= 1 || outEdges.size() >= 1 ) { - detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; - } - } else if (multiplicityRule.equals(MultiplicityRule.ONE2MANY)) { - if (inEdges.size() >= 1) { - detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; - } - } else if (multiplicityRule.equals(MultiplicityRule.MANY2ONE)) { - if (outEdges.size() >= 1) { - detail = "multiplicity rule violated: only one edge can exist with label: " + label + " between " + aVertexType + " and " + bVertexType; - } - } else { - - } - - if (!"".equals(detail)) { - return Optional.of(detail); - } else { - return Optional.empty(); - } - - - } - - /** - * Verifies that all required properties are defined in the given edge rule. - * If they are not, throws a RuntimeException. - * - * @param rule - Map<String edge property, String edge property value> representing - * an edge rule - */ - private void verifyRule(Map<String, String> rule) { - for (EdgeProperty prop : EdgeProperty.values()) { - if (!rule.containsKey(prop.toString())) { - /* Throws RuntimeException as rule definition errors - * cannot be recovered from, and should never happen anyway - * because these are configuration files, so requiring all - * downstream code to check for this exception seems inappropriate. - * It's instantiated with an AAIException to make sure all - * relevant information is present in the error message. - */ - throw new RuntimeException(new AAIException("AAI_4005", - "Rule between " + rule.get("from") + " and " + rule.get("to") + - " is missing property " + prop + ".")); - } - } - } - - /** - * Reads all the edge rules from the loaded json file. - * - * @return List<Map<String edge property, String edge property value>> - * Each map represents a rule read from the json. - */ - private List<Map<String, String>> readRules() { - return readRules(null); - } - - /** - * Reads the edge rules from the loaded json file, using the given filter - * to get specific rules. If filter is null, will get all rules. - * - * @param filter - may be null to indicate get all - * @return List<Map<String edge property, String edge property value>> - * Each map represents a rule read from the json. - */ - private List<Map<String, String>> readRules(Filter filter) { - List<Map<String, String>> results; - if (filter == null) { //no filter means get all - results = rulesDoc.read("$.rules.*"); - } else { - results = rulesDoc.read("$.rules.[?]", filter); - } - for (Map<String, String> result : results) { - verifyRule(result); - } - return results; - } - - /** - * Gets all the edge rules we define. - * - * @return Multimap<String "from|to", EdgeRule rule> - */ - public Multimap<String, EdgeRule> getAllRules() { - Multimap<String, EdgeRule> result = ArrayListMultimap.create(); - - List<Map<String, String>> rules = readRules(); - for (Map<String, String> rule : rules) { - EdgeRule er = buildRule(rule); - String name = rule.get("from") + "|" + rule.get("to"); - result.put(name, er); - } - - return result; - } - - /** - * Gets all edge rules that define a child relationship from - * the given node type. - * - * @param nodeType - * @return - */ - public Set<EdgeRule> getChildren(String nodeType) { - - final Filter filter = filter( - where("from").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("${direction}") - ).or(where("to").is(nodeType).and(EdgeProperty.CONTAINS.toString()).is("!${direction}")); - - final List<Map<String, String>> rules = readRules(filter); - final Set<EdgeRule> result = new HashSet<>(); - rules.forEach(item -> { - verifyRule(item); - result.add(buildRule(item)); - }); - - return result; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeType.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeType.java deleted file mode 100644 index cf3219fa..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/EdgeType.java +++ /dev/null @@ -1,26 +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.serialization.db; - -public enum EdgeType { - COUSIN, - TREE; -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GetAllPool.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/GetAllPool.java deleted file mode 100644 index 379c3f30..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GetAllPool.java +++ /dev/null @@ -1,46 +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.serialization.db; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -public class GetAllPool { - - private ExecutorService pool; - - private GetAllPool() { - pool = Executors.newWorkStealingPool(Runtime.getRuntime().availableProcessors()); - } - - private static class Helper { - private static final GetAllPool INSTANCE = new GetAllPool(); - } - - public static GetAllPool getInstance() { - return Helper.INSTANCE; - } - - public ExecutorService getPool() { - - return this.pool; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GraphSingleton.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/GraphSingleton.java deleted file mode 100644 index ba616387..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/GraphSingleton.java +++ /dev/null @@ -1,69 +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.serialization.db; - -import com.thinkaurelius.titan.core.TitanGraph; -import org.openecomp.aai.dbmap.AAIGraph; -import org.openecomp.aai.dbmap.DBConnectionType; - -import java.util.concurrent.atomic.AtomicInteger; - -/* This class simply calls AAIGraph under the covers for now */ -public class GraphSingleton { - - protected AtomicInteger totalCount = new AtomicInteger(); - - private static class Helper { - private static final GraphSingleton INSTANCE = new GraphSingleton(); - } - - /** - * Gets the single instance of GraphSingleton. - * - * @return single instance of GraphSingleton - */ - public static GraphSingleton getInstance() { - return Helper.INSTANCE; - - } - - /** - * Gets the count. - * - * @return the count - */ - public AtomicInteger getCount() { - return totalCount; - } - - /** - * Gets the tx graph. - * - * @return the tx graph - */ - public TitanGraph getTxGraph() { - return AAIGraph.getInstance().getGraph(); - } - - public TitanGraph getTxGraph(DBConnectionType connectionType) { - return AAIGraph.getInstance().getGraph(connectionType); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/LegacyDBSerializer.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/LegacyDBSerializer.java deleted file mode 100644 index 5d419852..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/LegacyDBSerializer.java +++ /dev/null @@ -1,34 +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.serialization.db; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.ModelType; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; - -public class LegacyDBSerializer extends DBSerializer { - - public LegacyDBSerializer(Version version, TransactionalGraphEngine engine, ModelType introspectionType, String sourceOfTruth) throws AAIException { - super(version, engine, introspectionType, sourceOfTruth); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/MultiplicityRule.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/MultiplicityRule.java deleted file mode 100644 index a1c9124d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/MultiplicityRule.java +++ /dev/null @@ -1,28 +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.serialization.db; - -public enum MultiplicityRule { - MANY2ONE, - ONE2MANY, - ONE2ONE, - MANY2MANY -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/TitanGraphSingleton.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/TitanGraphSingleton.java deleted file mode 100644 index 58008dab..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/TitanGraphSingleton.java +++ /dev/null @@ -1,38 +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.serialization.db; - -/* This is class is just a wrapper of its parent */ -public class TitanGraphSingleton extends GraphSingleton { - - private static class Helper { - private static final TitanGraphSingleton INSTANCE = new TitanGraphSingleton(); - } - - /** - * Gets the single instance of TitanGraphSingleton. - * - * @return single instance of TitanGraphSingleton - */ - public static TitanGraphSingleton getInstance() { - return Helper.INSTANCE; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/EdgeMultiplicityException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/EdgeMultiplicityException.java deleted file mode 100644 index 081a2d62..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/EdgeMultiplicityException.java +++ /dev/null @@ -1,40 +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.serialization.db.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class EdgeMultiplicityException extends AAIException { - - private static final long serialVersionUID = -5575661036426538012L; - - public EdgeMultiplicityException(String message) { - super("AAI_6140", message); - } - - public EdgeMultiplicityException(Throwable cause) { - super("AAI_6140",cause); - } - - public EdgeMultiplicityException(String message, Throwable cause) { - super("AAI_6140", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java deleted file mode 100644 index 025dfd82..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/db/exceptions/NoEdgeRuleFoundException.java +++ /dev/null @@ -1,40 +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.serialization.db.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class NoEdgeRuleFoundException extends AAIException { - - private static final long serialVersionUID = -906843868234976763L; - - public NoEdgeRuleFoundException(String message) { - super("AAI_6129", message); - } - - public NoEdgeRuleFoundException(Throwable cause) { - super("AAI_6129",cause); - } - - public NoEdgeRuleFoundException(String message, Throwable cause) { - super("AAI_6129", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/QueryStyle.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/QueryStyle.java deleted file mode 100644 index f6fae4d5..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/QueryStyle.java +++ /dev/null @@ -1,25 +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.serialization.engines; - -public enum QueryStyle { - GREMLIN_TRAVERSAL, GREMLIN_UNIQUE, GREMLINPIPELINE_TRAVERSAL, TRAVERSAL -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TitanDBEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TitanDBEngine.java deleted file mode 100644 index 8611ba6b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TitanDBEngine.java +++ /dev/null @@ -1,101 +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.serialization.engines; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.TitanGraphSingleton; - -public class TitanDBEngine extends TransactionalGraphEngine { - - /** - * Instantiates a new titan DB engine. - * - * @param style the style - * @param loader the loader - */ - public TitanDBEngine(QueryStyle style, DBConnectionType connectionType, Loader loader) { - super(style, loader, connectionType, TitanGraphSingleton.getInstance()); - } - - /** - * Instantiates a new titan DB engine. - * - * @param style the style - * @param loader the loader - * @param connect the connect - */ - public TitanDBEngine(QueryStyle style, Loader loader, boolean connect) { - super(style, loader); - if (connect) { - this.singleton = TitanGraphSingleton.getInstance(); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean setListProperty(Vertex v, String name, List<?> objs) { - - //clear out list full replace style - - Iterator<VertexProperty<Object>> iterator = v.properties(name); - while (iterator.hasNext()) { - iterator.next().remove(); - } - if (objs != null) { - for (Object obj : objs) { - v.property(name, obj); - } - } - return true; - } - - /** - * {@inheritDoc} - */ - @Override - public List<Object> getListProperty(Vertex v, String name) { - - List<Object> result = new ArrayList<Object>(); - - Iterator<VertexProperty<Object>> iterator = v.properties(name); - - while (iterator.hasNext()) { - result.add(iterator.next().value()); - } - - if (result.size() == 0) { - result = null; - } - - return result; - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TransactionalGraphEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TransactionalGraphEngine.java deleted file mode 100644 index ef91a868..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/TransactionalGraphEngine.java +++ /dev/null @@ -1,245 +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.serialization.engines; - -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.dbmap.DBConnectionType; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.query.builder.GremlinTraversal; -import org.openecomp.aai.query.builder.GremlinUnique; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.query.builder.TraversalQuery; -import org.openecomp.aai.serialization.db.GraphSingleton; -import org.openecomp.aai.serialization.engines.query.GraphTraversalQueryEngine; -import org.openecomp.aai.serialization.engines.query.QueryEngine; - -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.schema.TitanManagement; - -public abstract class TransactionalGraphEngine { - - protected GraphSingleton singleton = null; - protected QueryEngine queryEngine = null; - protected QueryBuilder<Vertex> queryBuilder = null; - protected QueryStyle style = null; - protected final DBConnectionType connectionType; - protected final Loader loader; - protected Graph currentTx = null; - protected GraphTraversalSource currentTraversal = null; - protected GraphTraversalSource readOnlyTraversal = null; - private final Admin admin; - /** - * Instantiates a new transactional graph engine. - * - * @param style the style - * @param loader the loader - */ - public TransactionalGraphEngine (QueryStyle style, Loader loader, DBConnectionType connectionType, GraphSingleton singleton) { - this.loader = loader; - this.style = style; - this.singleton = singleton; - this.connectionType = connectionType; - admin = new Admin(); - - } - - public TransactionalGraphEngine (QueryStyle style, Loader loader) { - this.loader = loader; - this.style = style; - this.connectionType = DBConnectionType.REALTIME; - admin = new Admin(); - } - - /** - * Sets the list property. - * - * @param v the v - * @param name the name - * @param obj the obj - * @return true, if successful - */ - public abstract boolean setListProperty(Vertex v, String name, List<?> obj); - - /** - * Gets the list property. - * - * @param v the v - * @param name the name - * @return the list property - */ - public abstract List<Object> getListProperty(Vertex v, String name); - - /** - * Gets the graph. - * - * @return the graph - */ - private TitanGraph getGraph() { - return singleton.getTxGraph(this.connectionType); - } - - /** - * Gets the count. - * - * @return the count - */ - public AtomicInteger getCount() { - return singleton.getCount(); - } - - - /** - * Gets the query engine. - * - * @return the query engine - */ - public QueryEngine getQueryEngine() { - QueryEngine engine = null; - if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) { - //this.queryEngine = new GremlinQueryEngine(this); - } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) { - //this.queryEngine = new GremlinQueryEngine(this); - } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) { - //this.queryEngine = new GremlinPipelineQueryEngine(this); - } else if (style.equals(QueryStyle.TRAVERSAL)) { - - return new GraphTraversalQueryEngine(this.asAdmin().getTraversalSource()); - - } else { - throw new IllegalArgumentException("Query Engine type not recognized"); - } - - return engine; - } - - /** - * Gets the query builder. - * - * @return the query builder - */ - public QueryBuilder<Vertex> getQueryBuilder() { - return getQueryBuilder(this.loader); - } - - public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style) { - return getQueryBuilder(style, this.loader); - } - - public QueryBuilder<Vertex> getQueryBuilder(Loader loader) { - return getQueryBuilder(this.style, loader); - } - - public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader) { - if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) { - return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource()); - } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) { - return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource()); - } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) { - //return new GremlinPipelineTraversal(loader); - } else if (style.equals(QueryStyle.TRAVERSAL)) { - return new TraversalQuery<>(loader, this.asAdmin().getTraversalSource()); - } else { - throw new IllegalArgumentException("Query Builder type not recognized"); - } - return queryBuilder; - } - /** - * Gets the query builder. - * - * @param start the start - * @return the query builder - */ - public QueryBuilder<Vertex> getQueryBuilder(Vertex start) { - return getQueryBuilder(this.loader, start); - } - - public QueryBuilder<Vertex> getQueryBuilder(Loader loader, Vertex start) { - return getQueryBuilder(this.style, loader, start); - } - - public QueryBuilder<Vertex> getQueryBuilder(QueryStyle style, Loader loader, Vertex start) { - if (style.equals(QueryStyle.GREMLIN_TRAVERSAL)) { - return new GremlinTraversal<>(loader, this.asAdmin().getTraversalSource(), start); - } else if (style.equals(QueryStyle.GREMLIN_UNIQUE)) { - return new GremlinUnique<>(loader, this.asAdmin().getTraversalSource(), start); - } else if (style.equals(QueryStyle.GREMLINPIPELINE_TRAVERSAL)) { - //return new GremlinPipelineTraversal(loader,start); - } else if (style.equals(QueryStyle.TRAVERSAL)) { - return new TraversalQuery<>(loader, this.asAdmin().getTraversalSource(), start); - } else { - throw new IllegalArgumentException("Query Builder type not recognized"); - } - return queryBuilder; - } - public Graph startTransaction() { - if (this.tx() == null) { - this.currentTx = this.getGraph().newTransaction(); - this.currentTraversal = this.tx().traversal(); - this.readOnlyTraversal = this.tx().traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance())); - } - return currentTx; - } - - public void rollback() { - if (this.tx() != null) { - this.tx().tx().rollback(); - this.currentTx = null; - this.currentTraversal = null; - this.readOnlyTraversal = null; - } - } - public void commit() { - if (this.tx() != null) { - this.tx().tx().commit(); - this.currentTx = null; - this.currentTraversal = null; - this.readOnlyTraversal = null; - } - } - - public Graph tx() { - return this.currentTx; - } - - public Admin asAdmin() { - return admin; - } - - public class Admin { - - public GraphTraversalSource getTraversalSource() { - return currentTraversal; - } - public GraphTraversalSource getReadOnlyTraversalSource() { - return readOnlyTraversal; - } - - public TitanManagement getManagementSystem() { - return getGraph().openManagement(); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GraphTraversalQueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GraphTraversalQueryEngine.java deleted file mode 100644 index ac8b21e1..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GraphTraversalQueryEngine.java +++ /dev/null @@ -1,197 +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.serialization.engines.query; - - -import static org.openecomp.aai.serialization.db.AAIDirection.IN; -import static org.openecomp.aai.serialization.db.AAIDirection.NONE; -import static org.openecomp.aai.serialization.db.AAIDirection.OUT; -import static org.openecomp.aai.serialization.db.EdgeProperty.CONTAINS; -import static org.openecomp.aai.serialization.db.EdgeProperty.DELETE_OTHER_V; - -import java.util.List; -import java.util.Set; - -import org.apache.tinkerpop.gremlin.process.traversal.P; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; - -/* - * This class needs some big explanation despite its compact size. - * This controls all the queries performed by the CRUD API in A&AI. - * findParents, findChildren, and findDeletable require special attention - * These methods use 'repeat'. You cannot use 'emit' with repeat currently - * as it is extremely buggy as of tinkerpop-3.0.1-incubating. The way around - * it (for now) is to sideEffect all the vertices we traverse into an ArrayList. - * - */ -public class GraphTraversalQueryEngine extends QueryEngine { - - /** - * Instantiates a new graph traversal query engine. - * - * @param graphEngine the graph engine - */ - public GraphTraversalQueryEngine(GraphTraversalSource g) { - super(g); - } - - /** - * {@inheritDoc} - */ - @Override - public List<Vertex> findParents(Vertex start) { - - final GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).emit(v -> true).repeat(__.union(__.inE().has(CONTAINS.toString(), OUT.toString()).outV(), __.outE().has(CONTAINS.toString(), IN.toString()).inV())); - return pipe.toList(); - } - - /** - * {@inheritDoc} - */ - @Override - public List<Vertex> findAllChildren(Vertex start) { - - GraphTraversal<Vertex, Vertex> pipe = this.g - .V(start).emit(v -> true).repeat(__.union(__.outE().has(CONTAINS.toString(), OUT.toString()).inV(), __.inE().has(CONTAINS.toString(), IN.toString()).outV())); - - - return pipe.toList(); - - } - - public List<Vertex> findChildrenOfType(Vertex start, String type) { - GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).union( - __.outE().has(CONTAINS.toString(), OUT.toString()).inV(), - __.inE().has(CONTAINS.toString(), IN.toString()).outV() - ).has(AAIProperties.NODE_TYPE, type).dedup(); - - return pipe.toList(); - } - - public List<Vertex> findChildren(Vertex start) { - GraphTraversal<Vertex, Vertex> pipe = this.g.V(start).union( - __.outE().has(CONTAINS.toString(), OUT.toString()), - __.inE().has(CONTAINS.toString(), IN.toString()) - ).otherV().dedup(); - - return pipe.toList(); - } - - /** - * {@inheritDoc} - */ - @Override - public List<Vertex> findDeletable(Vertex start) { - GraphTraversal<Vertex, Vertex> pipe = this.g - .V(start).emit(v -> true).repeat( - __.union( - __.outE().or( - __.has(CONTAINS.toString(), OUT.toString()), - __.has(DELETE_OTHER_V.toString(), OUT.toString()) - ).inV(), - __.inE().or( - __.has(CONTAINS.toString(), IN.toString()), - __.has(DELETE_OTHER_V.toString(), IN.toString()) - ).outV() - ) - ); - - return pipe.toList(); - } - - /** - * {@inheritDoc} - */ - @Override - public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) { - GraphTraversal<Vertex, Vertex> pipe = this.g.V(start); - switch (direction) { - case OUT: - pipe.out(label); - break; - case IN: - pipe.in(label); - break; - case BOTH: - pipe.both(label); - break; - default: - break; - } - - pipe.has(AAIProperties.NODE_TYPE, nodeType).dedup(); - return pipe.toList(); - } - - @Override - public Tree<Element> findSubGraph(Vertex start, int iterations, boolean nodeOnly) { - final GraphTraversal<Vertex, ?> t = this.g.V(start).emit(v -> true).times(iterations).repeat( - __.union( - __.outE().has(CONTAINS.toString(), OUT.toString()).inV(), - __.inE().has(CONTAINS.toString(), IN.toString()).outV()) - ); - - if (!nodeOnly) { - t.union( - __.identity(), - __.bothE().has(CONTAINS.toString(), NONE.toString()).dedup().otherV() - ); - } - t.tree(); - if (t.hasNext()) { - return (Tree)t.next(); - } else { - return new Tree(); - } - } - - @Override - public List<Edge> findEdgesForVersion(Vertex start, Loader loader) { - final Set<String> objects = loader.getAllObjects().keySet(); - GraphTraversal<Vertex, Edge> pipeline = this.g.V(start).union( - __.inE().has(CONTAINS.toString(), NONE.toString()).where(__.outV().has(AAIProperties.NODE_TYPE, P.within(objects))), - __.outE().has(CONTAINS.toString(), NONE.toString()).where(__.inV().has(AAIProperties.NODE_TYPE, P.within(objects))) - ).dedup(); - - return pipeline.toList(); - } - - - @Override - public List<Vertex> findCousinVertices(Vertex start) { - GraphTraversal<Vertex, Vertex> pipeline = this.g.V(start).union( - __.inE().has(CONTAINS.toString(), NONE.toString()), - __.outE().has(CONTAINS.toString(), NONE.toString())).otherV().dedup(); - - return pipeline.toList(); - } - -} - diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinPipelineQueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinPipelineQueryEngine.java deleted file mode 100644 index 809b6d96..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinPipelineQueryEngine.java +++ /dev/null @@ -1,185 +0,0 @@ -package org.openecomp.aai.serialization.engines.query;/*- - * ============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.serialization.engines.query; - -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.openecomp.aai.db.AAIProperties; -import org.openecomp.aai.query.builder.QueryBuilder; -import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; -import com.tinkerpop.blueprints.Direction; -import com.tinkerpop.blueprints.TransactionalGraph; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.gremlin.java.GremlinPipeline; -import com.tinkerpop.pipes.IdentityPipe; -import com.tinkerpop.pipes.PipeFunction; -import com.tinkerpop.pipes.branch.LoopPipe; - -public class GremlinPipelineQueryEngine extends QueryEngine { - - public GremlinPipelineQueryEngine(TransactionalGraphEngine graphEngine) { - super(graphEngine); - } - - @Override - public List<Vertex> executeQuery(TransactionalGraph g, QueryBuilder query) { - List<Vertex> results = null; - Vertex start = query.getStart(); - if (start != null) { - results = ((GremlinPipeline)query.getQuery()).cast(Vertex.class).toList(); - } else { - GremlinPipeline pipe = new GremlinPipeline(g); - results = process(pipe, (GremlinPipeline)query.getQuery()); - - } - return results; - } - - @Override - public List<Vertex> executeParentQuery(TransactionalGraph g, QueryBuilder query) { - List<Vertex> results = null; - Vertex start = query.getStart(); - if (start != null) { - results = ((GremlinPipeline)query.getParentQuery()).cast(Vertex.class).toList(); - } else { - GremlinPipeline pipe = new GremlinPipeline(g); - results = process(pipe, (GremlinPipeline)query.getParentQuery()); - - } - return results; - } - - @Override - public List<Vertex> findParents(Vertex start) { - GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline(start).as("x").inE() - .has("isParent", true).outV().loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) { - GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject()); - return pipe.inE().has("isParent", true).count() == 1 || argument.getLoops() < 100; - } - - }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) { - return true; - } - - }); - - List<Vertex> results = pipe.toList(); - results.add(0, start); - return results; - } - - @Override - public List<Vertex> findChildren(Vertex start) { - Set<Vertex> seen = new HashSet<>(); - seen.add(start); - GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline(start).as("x").outE().has("isParent", true).inV() - .except(seen).store(seen).loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) { - GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject()); - return pipe.outE().has("isParent", true).count() >= 1 || argument.getLoops() < 100; - } - - }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) { - return true; - } - - }); - - List<Vertex> results = pipe.toList(); - results.add(0, start); - return results; - } - - @Override - public List<Vertex> findDeletable(Vertex start) { - Set<Vertex> seen = new HashSet<>(); - seen.add(start); - GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline<Vertex, Vertex>(start).as("x").outE().or( - new GremlinPipeline(new IdentityPipe()).has("isParent", true), - new GremlinPipeline(new IdentityPipe()).has("hasDelTarget", true)).inV() - .except(seen).store(seen).loop("x", new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) { - GremlinPipeline<Vertex, Long> pipe = new GremlinPipeline<>(argument.getObject()); - return pipe.outE().or( - new GremlinPipeline(new IdentityPipe()).has("isParent", true), - new GremlinPipeline(new IdentityPipe()).has("hasDelTarget", true)).count() >= 1 || argument.getLoops() < 100; - } - - }, new PipeFunction<LoopPipe.LoopBundle<Vertex>, Boolean>() { - - @Override - public Boolean compute(LoopPipe.LoopBundle<Vertex> argument) { - return true; - } - - }); - List<Vertex> results = pipe.toList(); - results.add(0, start); - - return results; - } - - private List<Vertex> process(GremlinPipeline start, GremlinPipeline pipe) { - - - return start.add(pipe).cast(Vertex.class).toList(); - } - - @Override - public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) { - GremlinPipeline<Vertex, Vertex> pipe = new GremlinPipeline<Vertex, Vertex>(start); - switch (direction) { - case OUT: - pipe.out(label); - break; - case IN: - pipe.in(label); - break; - case BOTH: - pipe.both(label); - break; - default: - break; - } - - pipe.has(AAIProperties.NODE_TYPE, nodeType).dedup(); - List<Vertex> result = pipe.toList(); - return result; - } - -} -*/ diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinQueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinQueryEngine.java deleted file mode 100644 index 1ca02112..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/GremlinQueryEngine.java +++ /dev/null @@ -1,175 +0,0 @@ -package org.openecomp.aai.serialization.engines.query;/*- - * ============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.serialization.engines.query; -// -//import java.util.List; -//import java.util.regex.Matcher; -//import java.util.regex.Pattern; -// -//import org.apache.commons.collections.IteratorUtils; -// -//import org.openecomp.aai.db.AAIProperties; -//import org.openecomp.aai.query.builder.QueryBuilder; -//import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; -//import com.tinkerpop.blueprints.Direction; -//import com.tinkerpop.blueprints.Graph; -//import com.tinkerpop.blueprints.TransactionalGraph; -//import com.tinkerpop.blueprints.Vertex; -//import com.tinkerpop.gremlin.groovy.Gremlin; -//import com.tinkerpop.gremlin.java.GremlinPipeline; -//import com.tinkerpop.pipes.Pipe; -//import com.tinkerpop.pipes.util.iterators.SingleIterator; -// -//public class GremlinQueryEngine extends QueryEngine { -// -// public GremlinQueryEngine (TransactionalGraphEngine engine) { -// super(engine); -// -// } -// -// -// @Override -// public List<Vertex> executeQuery(TransactionalGraph g, QueryBuilder query) { -// List<Vertex> result = null; -// Vertex start = query.getStart(); -// if (start != null) { -// result = this.executeQuery(start, (String)query.getQuery()); -// } else { -// result = this.processGremlinQuery((String)query.getQuery()); -// } -// return result; -// -// } -// -// @Override -// public List<Vertex> executeParentQuery(TransactionalGraph g, QueryBuilder query) { -// -// List<Vertex> result = null; -// Vertex start = query.getStart(); -// if (start != null) { -// result = this.executeQuery(start, (String)query.getParentQuery()); -// } else { -// result = this.processGremlinQuery((String)query.getParentQuery()); -// } -// return result; -// } -// -// private List<Vertex> executeQuery(Vertex startVertex, String query) { -// -// return this.processGremlinQuery(startVertex, "_()" + query); -// -// } -// -// @Override -// public List<Vertex> findParents(Vertex start) { -// -// String findAllParents = ".as('x').inE.has('isParent', true).outV" -// + ".loop('x'){it.object.inE.has('isParent',true).count()==1}{true}"; -// -// List<Vertex> results = this.executeQuery(start, findAllParents); -// results.add(0, start); -// return results; -// -// } -// -// @Override -// public List<Vertex> findChildren(Vertex start) { -// String findAllChildren = ".as('x').outE.has('isParent', true).inV" -// + ".loop('x'){it.object.outE.has('isParent', true).count() >= 1}{true}"; -// -// List<Vertex> results = this.executeQuery(start, findAllChildren); -// results.add(0, start); -// return results; -// -// } -// -// @Override -// public List<Vertex> findDeletable(Vertex start) { -// String findAllChildren = ".as('x').outE.or(_().has('isParent', true), _().has('hasDelTarget', true)).inV" -// + ".loop('x'){it.object.outE.or(_().has('isParent', true), _().has('hasDelTarget', true)).count() >= 1}{true}"; -// -// List<Vertex> results = this.executeQuery(start, findAllChildren); -// results.add(0, start); -// return results; -// } -// private List<Vertex> processGremlinQuery(String query) { -// -// Pattern firstHasSet = Pattern.compile("^(\\.has\\(.*?\\))(\\.has\\(.*?\\))*(?!\\.has)"); -// Pattern p = Pattern.compile("\\.has\\('(.*?)',\\s?'(.*?)'\\)"); -// Matcher m = firstHasSet.matcher(query); -// List<Vertex> results = null; -// GremlinPipeline<Graph, Vertex> pipe = new GremlinPipeline<>(dbEngine.getGraph()); -// if (m.find()) { -// String hasSet = m.group(); -// query = query.replace(m.group(0), ""); -// m = p.matcher(hasSet); -// pipe.V(); -// while (m.find()) { -// pipe.has(m.group(1), m.group(2)); -// } -// results = processGremlinQuery(pipe.toList(), "_()" + query); -// } -// -// return results; -// -// } -// private List<Vertex> processGremlinQuery(Vertex startVertex, String query) { -// -// Pipe pipe = Gremlin.compile(query); -// pipe.setStarts(new SingleIterator<Vertex>(startVertex)); -// -// return (List<Vertex>)IteratorUtils.toList(pipe.iterator()); -// } -// private List<Vertex> processGremlinQuery(List<Vertex> list, String query) { -// -// Pipe pipe = Gremlin.compile(query); -// -// pipe.setStarts(list); -// -// return (List<Vertex>)IteratorUtils.toList(pipe.iterator()); -// } -// -// -// @Override -// public List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType) { -// String findRelatedVertices = "_()"; -// switch (direction) { -// case OUT: -// findRelatedVertices += ".out('" + label + "')"; -// break; -// case IN: -// findRelatedVertices += ".in('" + label + "')"; -// break; -// case BOTH: -// findRelatedVertices += ".both('" + label + "')"; -// break; -// default: -// break; -// } -// findRelatedVertices += ".has('" + AAIProperties.NODE_TYPE + "', '" + nodeType + "').dedup()"; -// List<Vertex> results = this.executeQuery(start, findRelatedVertices); -// results.add(0, start); -// return results; -// } -// -//} -// diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/QueryEngine.java b/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/QueryEngine.java deleted file mode 100644 index 5ac94d6c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/engines/query/QueryEngine.java +++ /dev/null @@ -1,93 +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.serialization.engines.query; - -import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Element; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; - -import java.util.List; - -public abstract class QueryEngine { - - final protected GraphTraversalSource g; - - /** - * Instantiates a new query engine. - * - * @param graphEngine the graph engine - */ - public QueryEngine (GraphTraversalSource g) { - this.g = g; - } - - /** - * Find parents. - * - * @param start the start - * @return the list - */ - public abstract List<Vertex> findParents(Vertex start); - - /** - * Find children. - * - * @param start the start - * @return the list - */ - public abstract List<Vertex> findAllChildren(Vertex start); - - public abstract List<Vertex> findChildrenOfType(Vertex start, String type); - - public abstract List<Vertex> findChildren(Vertex start); - /** - * Find deletable. - * - * @param start the start - * @return the list - */ - public abstract List<Vertex> findDeletable(Vertex start); - - public Tree<Element> findSubGraph(Vertex start) { - return findSubGraph(start, AAIProperties.MAXIMUM_DEPTH, false); - } - public abstract Tree<Element> findSubGraph(Vertex start, int iterations, boolean nodeOnly); - /** - * Find related vertices. - * - * @param start the start - * @param direction the direction - * @param label the label - * @param nodeType the node type - * @return the list - */ - public abstract List<Vertex> findRelatedVertices(Vertex start, Direction direction, String label, String nodeType); - - public abstract List<Edge> findEdgesForVersion(Vertex start, Loader loader); - - public abstract List<Vertex> findCousinVertices(Vertex start); - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Console.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Console.java deleted file mode 100644 index 561fd6cf..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Console.java +++ /dev/null @@ -1,42 +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.serialization.queryformats; - -import com.google.gson.JsonObject; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -public class Console implements FormatMapper { - - @Override - public JsonObject formatObject(Object v) throws AAIFormatVertexException { - - JsonObject json = new JsonObject(); - json.addProperty("result", v.toString()); - - return json; - } - - @Override - public int parallelThreshold() { - return 100; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Format.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Format.java deleted file mode 100644 index 0505f626..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Format.java +++ /dev/null @@ -1,30 +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.serialization.queryformats; - -public enum Format { - graphson, - pathed, id, resource, - simple, - resource_and_url, - console, - raw -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatFactory.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatFactory.java deleted file mode 100644 index 7753ae77..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatFactory.java +++ /dev/null @@ -1,96 +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.serialization.queryformats; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.QueryParamInjectionException; -import org.openecomp.aai.serialization.queryformats.utils.QueryParamInjector; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.MultivaluedMap; - -public class FormatFactory { - - private final Loader loader; - private final DBSerializer serializer; - private final UrlBuilder urlBuilder; - private final QueryParamInjector injector; - public FormatFactory (Loader loader, DBSerializer serializer) throws AAIException { - this.loader = loader; - this.serializer = serializer; - this.urlBuilder = new UrlBuilder(loader.getVersion(), serializer); - this.injector = QueryParamInjector.getInstance(); - } - - public Formatter get(Format format) throws AAIException { - return get(format, new MultivaluedHashMap<String, String>()); - } - - public Formatter get(Format format, MultivaluedMap<String, String> params) throws AAIException { - - Formatter formattter = null; - - switch (format) { - case graphson : - formattter = new Formatter(inject(new GraphSON(), params)); - break; - case pathed : - formattter = new Formatter(inject(new PathedURL(loader, urlBuilder), params)); - break; - case id : - formattter = new Formatter(inject(new IdURL(loader, urlBuilder), params)); - break; - case resource : - formattter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder), params).build()); - break; - case resource_and_url : - formattter = new Formatter(inject(new Resource.Builder(loader, serializer, urlBuilder).includeUrl(), params).build()); - break; - case raw : - formattter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder), params).build()); - break; - case simple : - formattter = new Formatter(inject(new RawFormat.Builder(loader, serializer, urlBuilder).depth(0).modelDriven(), params).build()); - break; - case console : - formattter = new Formatter(inject(new Console(), params)); - break; - default : - break; - - } - - return formattter; - } - - private <T> T inject (T obj, MultivaluedMap<String, String> params) throws QueryParamInjectionException { - - injector.injectParams(obj, params); - return obj; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatMapper.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatMapper.java deleted file mode 100644 index e9f17c6b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/FormatMapper.java +++ /dev/null @@ -1,31 +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.serialization.queryformats; - -import com.google.gson.JsonObject; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -public interface FormatMapper { - - public JsonObject formatObject(Object v) throws AAIFormatVertexException; - - public int parallelThreshold(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Formatter.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Formatter.java deleted file mode 100644 index 26b0411e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Formatter.java +++ /dev/null @@ -1,79 +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.serialization.queryformats; - -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Stream; - -public class Formatter { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(Formatter.class); - - protected JsonParser parser = new JsonParser(); - protected final FormatMapper format; - public Formatter (FormatMapper format) { - this.format = format; - } - - public JsonObject output(List<Object> vertices) { - Stream<Object> stream = null; - JsonObject result = new JsonObject(); - JsonArray body = new JsonArray(); - if (vertices.size() >= format.parallelThreshold()) { - stream = vertices.parallelStream(); - } else { - stream = vertices.stream(); - } - final boolean isParallel = stream.isParallel(); - stream.map(v -> { - try { - return Optional.<JsonObject>of(format.formatObject(v)); - } catch (AAIFormatVertexException e) { - LOGGER.warn("Failed to format vertex, returning a partial list", e); - } - - return Optional.<JsonObject>empty(); - }).forEach(obj -> { - if (obj.isPresent()) { - if (isParallel) { - synchronized (body) { - body.add(obj.get()); - } - } else { - body.add(obj.get()); - } - } - }); - - result.add("results", body); - - return result.getAsJsonObject(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/GraphSON.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/GraphSON.java deleted file mode 100644 index 9d119875..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/GraphSON.java +++ /dev/null @@ -1,62 +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.serialization.queryformats; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.thinkaurelius.titan.graphdb.tinkerpop.TitanIoRegistry; -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONMapper; -import org.apache.tinkerpop.gremlin.structure.io.graphson.GraphSONWriter; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class GraphSON implements FormatMapper { - - private final GraphSONMapper mapper = GraphSONMapper.build().addRegistry(TitanIoRegistry.INSTANCE).create(); - private final GraphSONWriter writer = GraphSONWriter.build().mapper(mapper).create(); - protected JsonParser parser = new JsonParser(); - - @Override - public JsonObject formatObject(Object v) { - OutputStream os = new ByteArrayOutputStream(); - String result = ""; - try { - writer.writeVertex(os, (Vertex)v, Direction.BOTH); - - result = os.toString(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - return parser.parse(result).getAsJsonObject(); - - } - - @Override - public int parallelThreshold() { - return 50; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/IdURL.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/IdURL.java deleted file mode 100644 index d0496c65..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/IdURL.java +++ /dev/null @@ -1,70 +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.serialization.queryformats; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -public class IdURL implements FormatMapper { - - private final UrlBuilder urlBuilder; - private final JsonParser parser; - private final Loader loader; - - public IdURL (Loader loader, UrlBuilder urlBuilder) throws AAIException { - this.urlBuilder = urlBuilder; - this.parser = new JsonParser(); - this.loader = loader; - } - - @Override - public int parallelThreshold() { - return 2500; - } - - @Override - public JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - try { - final Introspector searchResult = this.loader.introspectorFromName("result-data"); - - searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE)); - searchResult.setValue("resource-link", this.urlBuilder.id(v)); - - final String json = searchResult.marshal(false); - - return parser.parse(json).getAsJsonObject(); - - } catch (AAIUnknownObjectException e) { - throw new RuntimeException("Fatal error - result-data object does not exist!"); - } - - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/PathedURL.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/PathedURL.java deleted file mode 100644 index 09383c9a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/PathedURL.java +++ /dev/null @@ -1,69 +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.serialization.queryformats; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -public final class PathedURL implements FormatMapper { - - private final UrlBuilder urlBuilder; - private final JsonParser parser; - private final Loader loader; - - public PathedURL (Loader loader, UrlBuilder urlBuilder) throws AAIException { - this.urlBuilder = urlBuilder; - this.parser = new JsonParser(); - this.loader = loader; - } - - @Override - public int parallelThreshold() { - return 20; - } - - @Override - public JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - try { - final Introspector searchResult = this.loader.introspectorFromName("result-data"); - - searchResult.setValue("resource-type", v.value(AAIProperties.NODE_TYPE)); - - searchResult.setValue("resource-link", this.urlBuilder.pathed(v)); - final String json = searchResult.marshal(false); - return this.parser.parse(json).getAsJsonObject(); - - } catch (AAIUnknownObjectException e) { - throw new RuntimeException("Fatal error - result-data does not exist!", e); - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/RawFormat.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/RawFormat.java deleted file mode 100644 index 070e22f4..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/RawFormat.java +++ /dev/null @@ -1,189 +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.serialization.queryformats; - -import java.util.Iterator; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.params.Depth; -import org.openecomp.aai.serialization.queryformats.params.NodesOnly; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - - -public class RawFormat implements FormatMapper { - protected JsonParser parser = new JsonParser(); - protected final DBSerializer serializer; - protected final Loader loader; - protected final UrlBuilder urlBuilder; - protected final int depth; - protected final boolean nodesOnly; - protected RawFormat(Builder builder) { - this.urlBuilder = builder.getUrlBuilder(); - this.loader = builder.getLoader(); - this.serializer = builder.getSerializer(); - this.depth = builder.getDepth(); - this.nodesOnly = builder.isNodesOnly(); - } - - @Override - public JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - JsonObject json = new JsonObject(); - json.addProperty("id", v.id().toString()); - json.addProperty("node-type", v.<String>value(AAIProperties.NODE_TYPE)); - json.addProperty("url", this.urlBuilder.pathed(v)); - json.add("properties", this.createPropertiesObject(v)); - if (!nodesOnly) { - json.add("related-to", this.createRelationshipObject(v)); - } - return json; - } - - @Override - public int parallelThreshold() { - return 100; - } - - - public JsonObject createPropertiesObject(Vertex v) throws AAIFormatVertexException { - JsonObject json = new JsonObject(); - Iterator<VertexProperty<Object>> iter = v.properties(); - - while (iter.hasNext()) { - VertexProperty<Object> prop = iter.next(); - if (prop.value() instanceof String) { - json.addProperty(prop.key(), (String)prop.value()); - } else if (prop.value() instanceof Boolean) { - json.addProperty(prop.key(), (Boolean)prop.value()); - } else if (prop.value() instanceof Number) { - json.addProperty(prop.key(), (Number)prop.value()); - } else if (prop.value() instanceof List) { - Gson gson = new Gson(); - String list = gson.toJson(prop.value()); - - json.addProperty(prop.key(), list); - } else { - //throw exception? - return null; - } - } - - return json; - } - protected JsonArray createRelationshipObject(Vertex v) throws AAIFormatVertexException { - JsonArray jarray = new JsonArray(); - Iterator<Vertex> iter = v.vertices(Direction.BOTH); - - while (iter.hasNext()) { - Vertex related = iter.next(); - - JsonObject json = new JsonObject(); - json.addProperty("id", related.id().toString()); - json.addProperty("node-type", related.<String>value(AAIProperties.NODE_TYPE)); - json.addProperty("url", this.urlBuilder.pathed(related)); - jarray.add(json); - } - - return jarray; - } - - public static class Builder implements NodesOnly<Builder>, Depth<Builder> { - - protected final Loader loader; - protected final DBSerializer serializer; - protected final UrlBuilder urlBuilder; - protected boolean includeUrl = false; - protected boolean nodesOnly = false; - protected int depth = 1; - protected boolean modelDriven = false; - public Builder(Loader loader, DBSerializer serializer, UrlBuilder urlBuilder) { - this.loader = loader; - this.serializer = serializer; - this.urlBuilder = urlBuilder; - } - - protected Loader getLoader() { - return this.loader; - } - - protected DBSerializer getSerializer() { - return this.serializer; - } - - protected UrlBuilder getUrlBuilder() { - return this.urlBuilder; - } - - public Builder includeUrl() { - this.includeUrl = true; - return this; - } - - public Builder nodesOnly(Boolean nodesOnly) { - this.nodesOnly = nodesOnly; - return this; - } - public boolean isNodesOnly() { - return this.nodesOnly; - } - - public Builder depth(Integer depth) { - this.depth = depth; - return this; - } - - public int getDepth() { - return this.depth; - } - - public boolean isIncludeUrl() { - return this.includeUrl; - } - - public Builder modelDriven() { - this.modelDriven = true; - return this; - } - - public boolean getModelDriven() { - return this.modelDriven; - } - public RawFormat build() { - if (modelDriven) { - return new SimpleFormat(this); - } else { - return new RawFormat(this); - } - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Resource.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Resource.java deleted file mode 100644 index 9a090a4b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/Resource.java +++ /dev/null @@ -1,162 +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.serialization.queryformats; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.serialization.queryformats.params.Depth; -import org.openecomp.aai.serialization.queryformats.params.NodesOnly; -import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; - -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - -public class Resource implements FormatMapper { - - private final Loader loader; - private final DBSerializer serializer; - private final JsonParser parser; - private final UrlBuilder urlBuilder; - private final boolean includeUrl; - private final boolean nodesOnly; - private final int depth; - private Resource (Builder builder) { - this.parser = new JsonParser(); - this.loader = builder.getLoader(); - this.serializer = builder.getSerializer(); - this.urlBuilder = builder.getUrlBuilder(); - this.includeUrl = builder.isIncludeUrl(); - this.nodesOnly = builder.isNodesOnly(); - this.depth = builder.getDepth(); - } - - @Override - public JsonObject formatObject(Object input) throws AAIFormatVertexException { - Vertex v = (Vertex)input; - JsonObject json = new JsonObject(); - - if (this.includeUrl) { - json.addProperty("url", this.urlBuilder.pathed(v)); - } - json.add(v.<String>property(AAIProperties.NODE_TYPE) - .orElse(null), this.vertexToJsonObject(v)); - - return json; - } - - protected JsonObject vertexToJsonObject(Vertex v) throws AAIFormatVertexException { - try { - final Introspector obj = getLoader().introspectorFromName( - v.<String>property(AAIProperties.NODE_TYPE) - .orElse(null) - ); - - final List<Vertex> wrapper = new ArrayList<>(); - - wrapper.add(v); - - try { - getSerializer().dbToObject(wrapper, obj, this.depth, this.nodesOnly, "false"); - } catch (AAIException | UnsupportedEncodingException e) { - throw new AAIFormatVertexException("Failed to format vertex - error while serializing: " + e.getMessage(), e); - } - - final String json = obj.marshal(false); - - return getParser().parse(json).getAsJsonObject(); - } catch (AAIUnknownObjectException e) { - throw new AAIFormatVertexException("Failed to format vertex - unknown object", e); - } - } - - @Override - public int parallelThreshold() { - return 20; - } - - private Loader getLoader() { return loader; } - private DBSerializer getSerializer() { return serializer; } - private JsonParser getParser() { return parser; } - - public static class Builder implements NodesOnly<Builder>, Depth<Builder> { - - private final Loader loader; - private final DBSerializer serializer; - private final UrlBuilder urlBuilder; - private boolean includeUrl = false; - private boolean nodesOnly = false; - private int depth = 1; - public Builder(Loader loader, DBSerializer serializer, UrlBuilder urlBuilder) { - this.loader = loader; - this.serializer = serializer; - this.urlBuilder = urlBuilder; - } - - protected Loader getLoader() { - return this.loader; - } - - protected DBSerializer getSerializer() { - return this.serializer; - } - - protected UrlBuilder getUrlBuilder() { - return this.urlBuilder; - } - - public Builder includeUrl() { - this.includeUrl = true; - return this; - } - - public Builder nodesOnly(Boolean nodesOnly) { - this.nodesOnly = nodesOnly; - return this; - } - public boolean isNodesOnly() { - return this.nodesOnly; - } - public Builder depth(Integer depth) { - this.depth = depth; - return this; - } - public int getDepth() { - return this.depth; - } - public boolean isIncludeUrl() { - return this.includeUrl; - } - - public Resource build() { - return new Resource(this); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SimpleFormat.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SimpleFormat.java deleted file mode 100644 index f3a2990c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SimpleFormat.java +++ /dev/null @@ -1,75 +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.serialization.queryformats; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.db.props.AAIProperties; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; - -import com.google.gson.JsonObject; - -public class SimpleFormat extends RawFormat { - - - protected SimpleFormat(Builder builder) { - super(builder); - - } - - @Override - public int parallelThreshold() { - return 20; - } - - @Override - public JsonObject createPropertiesObject(Vertex v) throws AAIFormatVertexException { - try { - final Introspector obj = loader.introspectorFromName( - v.<String>property(AAIProperties.NODE_TYPE) - .orElse(null) - ); - - final List<Vertex> wrapper = new ArrayList<>(); - - wrapper.add(v); - - try { - serializer.dbToObject(wrapper, obj, this.depth, true, "false"); - } catch (AAIException | UnsupportedEncodingException e) { - throw new AAIFormatVertexException("Failed to format vertex - error while serializing: " + e.getMessage(), e); - } - - final String json = obj.marshal(false); - return parser.parse(json).getAsJsonObject(); - } catch (AAIUnknownObjectException e) { - throw new AAIFormatVertexException("Failed to format vertex - unknown object", e); - } - - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SubGraphStyle.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SubGraphStyle.java deleted file mode 100644 index 15c5041d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/SubGraphStyle.java +++ /dev/null @@ -1,27 +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.serialization.queryformats; - -public enum SubGraphStyle { - star, - prune, - no_op -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java deleted file mode 100644 index dc2b8a71..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/AAIFormatVertexException.java +++ /dev/null @@ -1,40 +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.serialization.queryformats.exceptions; - -public class AAIFormatVertexException extends Exception { - - private static final long serialVersionUID = -5814240841844624097L; - - public AAIFormatVertexException() {} - - public AAIFormatVertexException(String message) { - super(message); - } - - public AAIFormatVertexException(Throwable cause) { - super(cause); - } - - public AAIFormatVertexException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java deleted file mode 100644 index 6f75e3ba..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/exceptions/QueryParamInjectionException.java +++ /dev/null @@ -1,40 +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.serialization.queryformats.exceptions; - -import org.openecomp.aai.exceptions.AAIException; - -public class QueryParamInjectionException extends AAIException { - - private static final long serialVersionUID = -5575661036426538012L; - - public QueryParamInjectionException(String message) { - super("AAI_4017", message); - } - - public QueryParamInjectionException(Throwable cause) { - super("AAI_4017",cause); - } - - public QueryParamInjectionException(String message, Throwable cause) { - super("AAI_4017", cause, message); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Depth.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Depth.java deleted file mode 100644 index d5ade869..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Depth.java +++ /dev/null @@ -1,28 +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.serialization.queryformats.params; - -@Inject(name = "depth") -public interface Depth<T> { - - @Setter - public T depth(Integer depth); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Inject.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Inject.java deleted file mode 100644 index 128b7394..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Inject.java +++ /dev/null @@ -1,34 +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.serialization.queryformats.params; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - -@Retention(RetentionPolicy.RUNTIME) -public @interface Inject { - - /** - * The way the query parameter appears in the URI - * @return - */ - String name(); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/NodesOnly.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/NodesOnly.java deleted file mode 100644 index e81b5447..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/NodesOnly.java +++ /dev/null @@ -1,28 +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.serialization.queryformats.params; - -@Inject(name = "nodesOnly") -public interface NodesOnly<T> { - - @Setter - public T nodesOnly(Boolean nodesOnly); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Setter.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Setter.java deleted file mode 100644 index ad866c22..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/params/Setter.java +++ /dev/null @@ -1,36 +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.serialization.queryformats.params; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) -/** - * Marks what method in the object should be used for setting the value - * of the query parameter - */ -public @interface Setter { - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjector.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjector.java deleted file mode 100644 index 725152dd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/QueryParamInjector.java +++ /dev/null @@ -1,84 +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.serialization.queryformats.utils; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Set; - -import javax.ws.rs.core.MultivaluedMap; - -import org.openecomp.aai.serialization.queryformats.exceptions.QueryParamInjectionException; -import org.openecomp.aai.serialization.queryformats.params.Inject; -import org.openecomp.aai.serialization.queryformats.params.Setter; -import org.reflections.Reflections; - -public class QueryParamInjector { - - private final Set<Class<?>> results; - - - private QueryParamInjector () { - Reflections reflections = new Reflections("org.openecomp.aai.serialization.queryformats.params"); - results = reflections.getTypesAnnotatedWith(Inject.class); - } - - private static class Helper { - private static final QueryParamInjector INSTANCE = new QueryParamInjector(); - } - - public static QueryParamInjector getInstance() { - return Helper.INSTANCE; - } - - public <T> T injectParams(T obj, MultivaluedMap<String, String> params) throws QueryParamInjectionException{ - try { - for (Class<?> item : results) { - if (item.isAssignableFrom(obj.getClass())) { - String name = item.getAnnotation(Inject.class).name(); - - if (params.containsKey(name)) { - String value = params.getFirst(name); - - for (Method method : item.getMethods()) { - if (method.isAnnotationPresent(Setter.class)) { - Class<?>[] args = method.getParameterTypes(); - if (args.length == 1) { - Object o = args[0].getConstructor(String.class).newInstance(value); - method.invoke(obj, o); - } else { - method.invoke(obj); - } - } - } - } - } - } - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException - | SecurityException e) { - throw new QueryParamInjectionException("issue with query params", e); - } - - - return obj; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilder.java b/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilder.java deleted file mode 100644 index 5579c8a6..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/queryformats/utils/UrlBuilder.java +++ /dev/null @@ -1,91 +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.serialization.queryformats.utils; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; - -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.DBSerializer; -import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; -import org.openecomp.aai.util.AAIApiServerURLBase; -import org.openecomp.aai.util.AAIConstants; -import org.openecomp.aai.workarounds.LegacyURITransformer; - -public class UrlBuilder { - - private final DBSerializer serializer; - private final Version version; - private final String serverBase; - - public UrlBuilder (Version version, DBSerializer serializer) throws AAIException { - this.serializer = serializer; - this.version = version; - this.serverBase = this.getServerBase(version); - } - - public UrlBuilder (Version version, DBSerializer serializer, String serverBase) { - this.serializer = serializer; - this.version = version; - this.serverBase = serverBase; - } - - public String pathed(Vertex v) throws AAIFormatVertexException { - - try { - final StringBuilder result = new StringBuilder(); - final URI uri = this.serializer.getURIForVertex(v); - - if (this.version.compareTo(Version.v11) >= 0) { - result.append(AAIConstants.AAI_APP_ROOT); - } else { - result.append(this.serverBase); - } - result.append(this.version); - result.append(uri); - - return result.toString(); - } catch (UnsupportedEncodingException | IllegalArgumentException | SecurityException e) { - throw new AAIFormatVertexException(e); - } - } - - public String id(Vertex v) { - final StringBuilder result = new StringBuilder(); - - result.append("/resources/id/" + v.id()); - result.insert(0, this.version); - if (this.version.compareTo(Version.v11) >= 0) { - result.insert(0, AAIConstants.AAI_APP_ROOT); - } else { - result.insert(0, this.serverBase); - } - - return result.toString(); - } - - protected String getServerBase(Version v) throws AAIException { - return AAIApiServerURLBase.get(v); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedEdge.java b/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedEdge.java deleted file mode 100644 index 774ab28f..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedEdge.java +++ /dev/null @@ -1,80 +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.serialization.tinkerpop; - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge; -import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils; - -import java.util.Iterator; - - -/** - * Represents a {@link Edge} that is disconnected from a {@link Graph} however, - * traversals are supported as they are backed by a Tree with saturated {@link Vertex} and {@link Edge} objects. - * These objects are not mutable and can only be used to read information out. - * - */ -public class TreeBackedEdge extends DetachedEdge implements Edge { - - private static final long serialVersionUID = 5419650145562077538L; - private TreeBackedVertex inVertex; - private TreeBackedVertex outVertex; - public TreeBackedEdge(Edge edge, TreeBackedVertex inVertex, TreeBackedVertex outVertex) { - super(edge, true); - this.inVertex = inVertex; - this.outVertex = outVertex; - } - - @Override - public Vertex inVertex() { - return this.inVertex; - } - - @Override - public Vertex outVertex() { - return this.outVertex; - } - - @Override - public Iterator<Vertex> bothVertices() { - return this.vertices(Direction.BOTH); - } - - @Override - public Iterator<Vertex> vertices(Direction direction) { - switch (direction) { - case OUT: - return IteratorUtils.of(this.outVertex); - case IN: - return IteratorUtils.of(this.inVertex); - default: - return IteratorUtils.of(this.outVertex, this.inVertex); - } - } - - - - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertex.java b/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertex.java deleted file mode 100644 index 7ebad216..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertex.java +++ /dev/null @@ -1,162 +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.serialization.tinkerpop; - -import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; -import org.apache.tinkerpop.gremlin.structure.*; -import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertex; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * Represents a {@link Vertex} that is disconnected from a {@link Graph} however, - * traversals are supported as they are backed by a Tree with saturated {@link Vertex} and {@link Edge} objects. - * These objects are not mutable and can only be used to read information out. - * - */ - -public class TreeBackedVertex extends DetachedVertex implements Vertex { - - private static final long serialVersionUID = -976854460992756953L; - private final Tree<Element> tree; - private final Vertex self; - public TreeBackedVertex (Vertex v, Tree<Element> tree) { - super(v, true); - this.self = v; - this.tree = tree; - } - - @Override - public Iterator<Edge> edges(final Direction direction, final String... edgeLabels) { - final List<Element> edges = tree.getObjectsAtDepth(2); - final List<Tree<Element>> trees = tree.getTreesAtDepth(2); - final List<Tree<Element>> vTrees = tree.getTreesAtDepth(3); - return edges.stream().map( ele -> (Edge)ele).filter(e -> { - if (Direction.IN.equals(direction)) { - return e.inVertex().equals(self); - } else if (Direction.OUT.equals(direction)) { - return e.outVertex().equals(self); - } else { - return true; - } - }).filter(e -> { - boolean result = false; - if (edgeLabels.length == 0) { - return true; - } - for (String label : edgeLabels) { - if (label.equals(e.label())) { - result = true; - break; - } - } - return result; - }).map(e -> { - Tree<Element> eTree = new Tree<>(); - for (Tree<Element> tree : trees) { - if (tree.keySet().contains(e)) { - eTree = tree; - break; - } - } - TreeBackedVertex in = null; - TreeBackedVertex out = null; - if (e.inVertex().equals(self)) { - in = this; - out = this.createForVertex(e.outVertex(), vTrees); - } else if (e.outVertex().equals(self)) { - out = this; - in = this.createForVertex(e.inVertex(), vTrees); - } - return (Edge)new TreeBackedEdge(e, in, out); - }).iterator(); - - } - - private TreeBackedVertex createForVertex(Vertex v, List<Tree<Element>> trees) { - Tree<Element> vTree = new Tree<>(); - for (Tree<Element> tree : trees) { - if (tree.keySet().contains(v)) { - vTree = tree; - break; - } - } - - return new TreeBackedVertex((Vertex)vTree.keySet().iterator().next(), vTree); - } - @Override - public Iterator<Vertex> vertices(final Direction direction, final String... labels) { - final List<Tree<Element>> vertexElements = tree.getTreesAtDepth(3); - final List<Element> edgeElements = tree.getObjectsAtDepth(2); - return edgeElements.stream().map( ele -> (Edge)ele).filter(e -> { - boolean result = false; - if (labels.length == 0) { - return true; - } - for (String label : labels) { - if (label.equals(e.label())) { - result = true; - break; - } - } - return result; - }).filter(e -> { - if (Direction.IN.equals(direction) && e.inVertex().equals(self)) { - return true; - } else if (Direction.OUT.equals(direction) && e.outVertex().equals(self)) { - return true; - } else if (Direction.BOTH.equals(direction)){ - return true; - } else { - return false; - } - }).map(e -> { - final List<Vertex> list; - if (Direction.IN.equals(direction)) { - list = Collections.singletonList(e.outVertex()); - } else if (Direction.OUT.equals(direction)){ - list = Collections.singletonList(e.inVertex()); - } else { - list = new ArrayList<>(); - Iterator<Vertex> itr = e.bothVertices(); - while (itr.hasNext()) { - list.add(itr.next()); - } - } - return list; - - }).flatMap(list -> list.stream()).map(v -> { - Tree<Element> vTree = new Tree<Element>(); - for (Tree<Element> tree : vertexElements) { - if (tree.keySet().contains(v)) { - vTree = tree; - break; - } - } - - return (Vertex)new TreeBackedVertex(v, vTree); - }).iterator(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/tasks/ScheduledTasks.java b/aai-core/src/main/java/org/openecomp/aai/tasks/ScheduledTasks.java deleted file mode 100644 index f0a4d41a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/tasks/ScheduledTasks.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.tasks; - -import java.io.File; -import java.util.Arrays; -import java.util.Date; -import java.util.UUID; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.comparator.LastModifiedFileComparator; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -import org.openecomp.aai.logging.LoggingContext; -import org.openecomp.aai.util.AAIConfig; -import org.openecomp.aai.util.AAIConstants; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -@Component -public class ScheduledTasks { - - private static EELFLogger LOGGER = EELFManager.getInstance().getLogger(ScheduledTasks.class); - - private static final String COMPONENT = "Scheduler"; - private static final String FROM_APP_ID = "CronApp"; - private static final long PROPERTY_READ_INTERVAL = 60000; // every minute - - private String GlobalPropFileName = AAIConstants.AAI_CONFIG_FILENAME; - - // for read and possibly reloading aaiconfig.properties and other - /** - * Load AAI properties. - */ - // configuration properties files - @Scheduled(fixedRate = PROPERTY_READ_INTERVAL) - public void loadAAIProperties() { - final UUID transId = UUID.randomUUID(); - - LoggingContext.requestId(transId); - LoggingContext.partnerName(FROM_APP_ID); - LoggingContext.component(COMPONENT); - - String dir = FilenameUtils.getFullPathNoEndSeparator(GlobalPropFileName); - if (dir == null || dir.length() < 3) { - dir = "/opt/aai/etc"; - } - - File pdir = new File(dir); - File[] files = pdir.listFiles(); - Arrays.sort(files, LastModifiedFileComparator.LASTMODIFIED_REVERSE); - String fn; - - // leave this loop here since we may want to check other configurable - // property files in the SAME directory - for (File file : files) { - fn = file.getName(); - if (fn.equals("aaiconfig.properties")) { - Date lastMod = new Date(file.lastModified()); - long lastModTm = lastMod.getTime(); - Date curTS = new Date(); - long curTSTm = curTS.getTime(); - if (curTSTm - lastModTm < PROPERTY_READ_INTERVAL + 1000) { - AAIConfig.reloadConfig(); - LOGGER.info("reloaded from aaiconfig.properties"); - } - break; - } - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiServerURLBase.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIApiServerURLBase.java deleted file mode 100644 index 12a2c06d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiServerURLBase.java +++ /dev/null @@ -1,80 +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.util.List; -import java.util.Map; - -import org.apache.cxf.helpers.CastUtils; -import org.apache.cxf.message.Message; -import org.apache.cxf.phase.PhaseInterceptorChain; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.introspection.Version; - -public class AAIApiServerURLBase { - - /** - * Gets the. - * - * @return the string - * @throws AAIException the AAI exception - */ - public static String get() throws AAIException { - - String hostName = null; - try { - Message message = PhaseInterceptorChain.getCurrentMessage(); - Map<String, List<String>> headers = CastUtils.cast((Map) message.get(Message.PROTOCOL_HEADERS)); - List sa = null; - if (headers != null) { - sa = headers.get("host"); - } - - if (sa != null && sa.size() == 1) { - hostName = "https://"+ sa.get(0).toString() + "/aai/"; - } - } catch (Exception e) { - // TODO: we may want to log an error here - } - // TODO: should this check the value a little closer and look for a pattern? - if (hostName == null) { - hostName = AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE); - //AAIConstants.AAI_SERVER_URL_BASE; - } - return hostName; - } - - /** - * Gets the. - * - * @param v the v - * @return the string - * @throws AAIException the AAI exception - */ - public static String get(Version v) throws AAIException { - String hostName = null; - hostName = AAIApiServerURLBase.get(); - - return hostName; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiVersion.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIApiVersion.java deleted file mode 100644 index 680fcf63..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIApiVersion.java +++ /dev/null @@ -1,74 +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.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.cxf.message.Message; -import org.apache.cxf.phase.PhaseInterceptorChain; - -import org.openecomp.aai.exceptions.AAIException; - -public class AAIApiVersion { - - private static final Pattern versionPattern = Pattern.compile("(^|\\/)(v\\d+)\\/"); - - private static final Pattern latestVersionPattern = Pattern.compile("(^|\\/)(latest)\\/"); - - /** - * Gets the. - * - * @return the string - * @throws AAIException the AAI exception - */ - public static String get() throws AAIException { - - String apiVersion = null; - try { - Message message = PhaseInterceptorChain.getCurrentMessage(); - String requestURI = (String) message.get(Message.REQUEST_URI); - - if (requestURI != null) { - Matcher matcher = versionPattern.matcher(requestURI); - if (matcher.find() && matcher.groupCount() >= 2) { - apiVersion = matcher.group(2); - } - if (apiVersion == null) { - Matcher latestMatcher = latestVersionPattern.matcher(requestURI); - if (latestMatcher.find() && latestMatcher.groupCount() >= 2) { - apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION); - } - } - - } - - } catch (Exception e) { - // TODO: we may want to log an error here - } - // TODO: should this check the value a little closer and look for a pattern? - if (apiVersion == null || !apiVersion.startsWith("v")) { - apiVersion = AAIConfig.get (AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION); - //apiVersion = AAIConstants.AAI_DEFAULT_API_VERSION; - } - return apiVersion; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAICSVWriter.java b/aai-core/src/main/java/org/openecomp/aai/util/AAICSVWriter.java deleted file mode 100644 index 5467168c..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAICSVWriter.java +++ /dev/null @@ -1,167 +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.io.IOException; -import java.io.PrintWriter; -import java.io.Writer; - -import com.opencsv.CSVWriter; - -/** - * had to overwrite the separate character to separate string - * Based on the public - A very simple CSV writer released under a commercial-friendly license. - * - - */ -public class AAICSVWriter extends CSVWriter { - - private String separatorStr; - private char overridequotechar; - private String overridelineEnd; - private Writer rawWriter; - private PrintWriter pw; - - /** - * Instantiates a new AAICSV writer. - * - * @param writer the writer - */ - public AAICSVWriter(Writer writer) { - super(writer); - // TODO Auto-generated constructor stub - } - - /** - * Constructs AAICSVWriter with supplied separator string and quote char. - * - * @param writer the writer to an underlying CSV source. - * @param overrideseparator the overrideseparator - * @param quotechar the character to use for quoted elements - * @param lineEnd the line feed terminator to use - */ - public AAICSVWriter(Writer writer, String overrideseparator, char quotechar, String lineEnd) { - super(writer, CSVWriter.DEFAULT_SEPARATOR, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd); - separatorStr = overrideseparator; - overridequotechar = quotechar; - overridelineEnd = lineEnd; - this.rawWriter = writer; - this.pw = new PrintWriter(writer); - } - - /** - * String contains special characters. - * - * @param line the line - * @return true, if successful - */ - private boolean stringContainsSpecialCharacters(String line) { - return line.indexOf(overridequotechar) != -1 || line.indexOf(DEFAULT_ESCAPE_CHARACTER) != -1 || line.indexOf(separatorStr) != -1 || line.contains("\n") || line.contains("\r"); - } - - /** - * Close the underlying stream writer flushing any buffered content. - * - * @throws IOException if bad things happen - */ - public void close() throws IOException { - flush(); - pw.close(); - rawWriter.close(); - } - - /** - * Writes the next line to the file. - * - * @param nextLine a string array with each comma-separated element as a separate - * entry. - * @param applyQuotesToAll true if all values are to be quoted. false applies quotes only - * to values which contain the separator, escape, quote or new line characters. - */ - public void writeNext(String[] nextLine, boolean applyQuotesToAll) { - - if (nextLine == null) - return; - - StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); - for (int i = 0; i < nextLine.length; i++) { - - if (i != 0) { - sb.append(separatorStr); - } - - String nextElement = nextLine[i]; - - if (nextElement == null) - continue; - - Boolean stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement); - - if ((applyQuotesToAll || stringContainsSpecialCharacters) && overridequotechar != NO_QUOTE_CHARACTER) - sb.append(overridequotechar); - - if (stringContainsSpecialCharacters) { - sb.append(processLine(nextElement)); - } else { - sb.append(nextElement); - } - - if ((applyQuotesToAll || stringContainsSpecialCharacters) && overridequotechar != NO_QUOTE_CHARACTER) - sb.append(overridequotechar); - } - - sb.append(overridelineEnd); - pw.write(sb.toString()); - } - - - /** - * Writes the next line to the file ignoring all exceptions. - * - * @param nextLine a string array with each comma-separated element as a separate - * entry. - */ - public void writeColumn(String[] nextLine) { - - if (nextLine == null) - return; - - StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE); - for (int i = 0; i < nextLine.length; i++) { - - - String nextElement = nextLine[i]; - - if (nextElement == null) - continue; - - sb.append(nextElement); - - - } - - sb.append(overridelineEnd); - pw.write(sb.toString()); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIConfig.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIConfig.java deleted file mode 100644 index 9fcb521d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIConfig.java +++ /dev/null @@ -1,266 +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.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Properties; -import java.util.Timer; - -import org.eclipse.jetty.util.security.Password; - -import org.openecomp.aai.exceptions.AAIException; -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class AAIConfig { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIConfig.class); - private static final String GLOBAL_PROP_FILE_NAME = AAIConstants.AAI_CONFIG_FILENAME; - private static Properties serverProps; - private static boolean propsInitialized = false; - - // this (probably) won't change between releases, put it in the config if it gets annoying... - private static HashMap<String,ArrayList<String>> defaultBools = new HashMap<String,ArrayList<String>>(); - private static Timer timer = new Timer(); - - /** - * Instantiates a new AAI config. - */ - // Don't instantiate - private AAIConfig() {} - - /** - * Inits the. - * - * @throws AAIException the AAI exception - */ - public synchronized static void init() throws AAIException{ - LOGGER.info("Initializing AAIConfig"); - - ArrayList<String> genericVnfBools = new ArrayList<String>(); - ArrayList<String> l3NetworkBools = new ArrayList<String>(); - ArrayList<String> pserverBools = new ArrayList<String>(); - ArrayList<String> subnetBools = new ArrayList<String>(); - ArrayList<String> vserverBools = new ArrayList<String>(); - ArrayList<String> vnfcBools = new ArrayList<String>(); - - genericVnfBools.add("in-maint"); - genericVnfBools.add("is-closed-loop-disabled"); - l3NetworkBools.add("is-bound-to-vpn"); - pserverBools.add("in-maint"); - subnetBools.add("dhcp-enabled"); - vserverBools.add("in-maint"); - vserverBools.add("is-closed-loop-disabled"); - vnfcBools.add("in-maint"); - vnfcBools.add("is-closed-loop-disabled"); - - defaultBools.put("generic-vnf", genericVnfBools); - defaultBools.put("l3-network", l3NetworkBools); - defaultBools.put("pserver", pserverBools); - defaultBools.put("subnet", subnetBools); - defaultBools.put("vserver", vserverBools); - defaultBools.put("vnfc", vnfcBools); - - AAIConfig.getConfigFile(); - AAIConfig.reloadConfig(); - - if (AAIConstants.AAI_NODENAME == null || AAIConstants.AAI_NODENAME == "") { - ErrorLogHelper.logError("AAI_4005", " AAI_NODENAME is not defined"); - } else { - LOGGER.info("A&AI Server Node Name = " + AAIConstants.AAI_NODENAME); - } - } - - /** - * Gets the default bools. - * - * @return the default bools - */ - public static HashMap<String,ArrayList<String>> getDefaultBools() { - return defaultBools; - } - - /** - * Cleanup. - */ - public static void cleanup() { - timer.cancel(); - } - - /** - * Gets the config file. - * - * @return the config file - */ - public static String getConfigFile() { -// if (GlobalPropFileName == null) { -// String nc = System.getProperty("aaiconfig"); -// if (nc == null) nc = "/home/aaiadmin/etc/aaiconfig.props"; -// logger.info( "aaiconfig = " + nc==null?"null":nc); -// GlobalPropFileName = nc; -// } - return GLOBAL_PROP_FILE_NAME; - } - - /** - * Reload config. - */ - public synchronized static void reloadConfig() { - - String propFileName = GLOBAL_PROP_FILE_NAME; - Properties newServerProps = null; - - LOGGER.info("Reloading config from " + propFileName); - - try { - InputStream is = new FileInputStream(propFileName); - newServerProps = new Properties(); - newServerProps.load(is); - propsInitialized = true; - - serverProps = newServerProps; - newServerProps = null; - - } catch (FileNotFoundException fnfe) { - ErrorLogHelper.logError("AAI_4001", " " + propFileName + ". Exception: "+fnfe.getMessage()); - } catch (IOException e) { - ErrorLogHelper.logError("AAI_4002", " " + propFileName + ". IOException: "+e.getMessage()); - } - } - - /** - * Gets the. - * - * @param key the key - * @param defaultValue the default value - * @return the string - */ - public static String get(String key, String defaultValue) { - String result = defaultValue; - try { - result = get (key); - } - catch ( AAIException a ) { - - } - return ( result ); - } - - /** - * Gets the. - * - * @param key the key - * @return the string - * @throws AAIException the AAI exception - */ - public static String get(String key) throws AAIException { - String response = null; - - if (key.equals(AAIConstants.AAI_NODENAME)) { - // Get this from InetAddress rather than the properties file - String nodeName = getNodeName(); - if (nodeName != null) { - return nodeName; - } - // else get from property file - } - - if (!propsInitialized || (serverProps == null)) { - reloadConfig(); - } - - if ((key.endsWith("password") || key.endsWith("passwd") || key.endsWith("apisecret")) && serverProps.containsKey(key+".x")) { - String valx = serverProps.getProperty(key+".x"); - return Password.deobfuscate(valx); - } - - if (!serverProps.containsKey(key)) { - throw new AAIException("AAI_4005", "Property key "+key+" cannot be found"); - } else { - response = serverProps.getProperty(key); - if (response == null || response.isEmpty()) { - throw new AAIException("AAI_4005", "Property key "+key+" is null or empty"); - } - } - return response; - } - - /** - * Gets the int. - * - * @param key the key - * @return the int - * @throws AAIException the AAI exception - */ - public static int getInt(String key) throws AAIException{ - return Integer.valueOf(AAIConfig.get(key)); - } - - /** - * Gets the server props. - * - * @return the server props - */ - public static Properties getServerProps() { - return serverProps; - } - - /** - * Gets the node name. - * - * @return the node name - */ - public static String getNodeName() { - try { - InetAddress ip = InetAddress.getLocalHost(); - if (ip != null) { - String hostname = ip.getHostName(); - if (hostname != null) { - return hostname; - } - } - } catch (Exception e) { - return null; - } - return null; - } - - - /** - * Check if a null or an Empty string is passed in. - * - * @param s the s - * @return boolean - */ - public static boolean isEmpty(String s) - { - return (s == null || s.length() == 0); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIConfigCommandLinePropGetter.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIConfigCommandLinePropGetter.java deleted file mode 100644 index c6ddc4fd..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIConfigCommandLinePropGetter.java +++ /dev/null @@ -1,66 +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 org.openecomp.aai.exceptions.AAIException; - -/* - * The script deobfuscatePW.sh needs to retrieve pws from the AAIConfig file. - * As AAIConfig has no main to be callable on the command line, this class helps - * by providing one for accessing AAIConfig that way. - * (AAIConfig deobfuscates pws itself, so we just need to call its .get() on the desired pw.) - * - * This could be used to get any property from AAIConfig via the command line, - * not just the pws, even though it was made for pw-related needs. - */ -public class AAIConfigCommandLinePropGetter { - - /** - * The main method. - * - * @param args the arguments - */ - /* - * usage: - * AAIConfigCommandLinePropGetter propertyname - */ - public static void main(String[] args) { - if (args.length != 1) { - System.out.println("only one property may be requested at a time"); - System.out.println("usage: AAIConfigCommandLinePropGetter propertyname"); - } - try { - AAIConfig.init(); - String value = AAIConfig.get(args[0]); - if (value != null) { - System.out.println(value); //bc this utility used by a shell script so it needs the result sent to stdout - } else { - System.out.println("requested property could not be found"); - } - } catch(AAIException e) { - System.out.println("exception:" + e.toString()); //TODO is this reasonable? - } finally { - System.exit(0); - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIConstants.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIConstants.java deleted file mode 100644 index 6c23c6e3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIConstants.java +++ /dev/null @@ -1,151 +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 org.openecomp.aai.db.props.AAIProperties; - -public final class AAIConstants { - - // - // - /** Default to unix file separator if system property file.separator is null */ - public static final String AAI_FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator"); - // - /** Default to opt aai if system property aai.home is null, using file.separator */ - public static final String AAI_HOME = (System.getProperty("AJSC_HOME") == null) ? AAI_FILESEP + "opt" + AAI_FILESEP + "app" + AAI_FILESEP +"aai" : System.getProperty("AJSC_HOME"); - public static final String AAI_BUNDLECONFIG_NAME = (System.getProperty("BUNDLECONFIG_DIR") == null) ? "bundleconfig" : System.getProperty("BUNDLECONFIG_DIR"); - public static final String AAI_HOME_BUNDLECONFIG = (System.getProperty("AJSC_HOME") == null) ? AAI_FILESEP + "opt" + AAI_FILESEP + "app" + AAI_FILESEP + "aai" + AAI_FILESEP + AAI_BUNDLECONFIG_NAME : System.getProperty("AJSC_HOME")+ AAI_FILESEP + AAI_BUNDLECONFIG_NAME; - - /** etc directory, relative to AAI_HOME */ - public static final String AAI_HOME_ETC = AAI_HOME_BUNDLECONFIG + AAI_FILESEP + "etc" + AAI_FILESEP; - public static final String AAI_HOME_ETC_APP_PROPERTIES = AAI_HOME_ETC + "appprops" + AAI_FILESEP; - public static final String AAI_V2_OUTPUT_TRANSFORMS = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + AAIConstants.AAI_FILESEP + "output" + AAIConstants.AAI_FILESEP; - public static final String AAI_HOME_ETC_AUTH = AAI_HOME_ETC + "auth" + AAI_FILESEP; - public static final String AAI_CONFIG_FILENAME = AAI_HOME_ETC_APP_PROPERTIES + "aaiconfig.properties"; - public static final String AAI_AUTH_CONFIG_FILENAME = AAI_HOME_ETC_AUTH + "aai_policy.json"; - public static final String AAI_MECHID_CONFIG_FILENAME = AAI_HOME_ETC_APP_PROPERTIES + "mechIds.json"; - public static final String AAI_HOME_ETC_QUERY = AAI_HOME_ETC + "query" + AAI_FILESEP + "stored-queries.properties"; - public static final String REALTIME_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "titan-realtime.properties"; - public static final String CACHED_DB_CONFIG = AAI_HOME_ETC_APP_PROPERTIES + "titan-cached.properties"; - public static final String AAI_HOME_ETC_OXM = AAI_HOME_ETC + "oxm" + AAI_FILESEP; - public static final String AAI_EVENT_DMAAP_PROPS = AAI_HOME_ETC_APP_PROPERTIES + "aaiEventDMaaPPublisher.properties"; - - public static final String AAI_PROV_LOGBACK_PROPS = "prov-logback.xml"; - public static final String AAI_GETRES_LOGBACK_PROPS = "getres-logback.xml"; - public static final String AAI_DELTOOL_LOGBACK_PROPS = "deltool-logback.xml"; - public static final String AAI_UPDTOOL_LOGBACK_PROPS = "updtool-logback.xml"; - public static final String AAI_PUTTOOL_LOGBACK_PROPS = "puttool-logback.xml"; - public static final String AAI_POSTTOOL_LOGBACK_PROPS = "posttool-logback.xml"; - public static final String AAI_NOTIFYSDNCTOOL_LOGBACK_PROPS = "notifysdnctool-logback.xml"; - public static final String AAI_RSHIPTOOL_LOGBACK_PROPS = "rshiptool-logback.xml"; - public static final String AAI_LOGBACK_PROPS = "logback.xml"; - - - public static final String AAI_CREATE_DB_SCHEMA_LOGBACK_PROPS = "createDBSchema-logback.xml"; - public static final String AAI_PULL_INV_DATA_LOGBACK_PROPS = "pullInvData-logback.xml"; - public static final String AAI_DATA_GROOMING_LOGBACK_PROPS = "dataGrooming-logback.xml"; - public static final String AAI_DATA_SNAPSHOT_LOGBACK_PROPS = "dataSnapshot-logback.xml"; - public static final String AAI_SCHEMA_MOD_LOGBACK_PROPS = "schemaMod-logback.xml"; - public static final String AAI_FORCE_DELETE_LOGBACK_PROPS = "forceDelete-logback.xml"; - - public static final String AAI_LOAD_DATA_DHV_LOGBACK_PROPS = "loadDataForDHV-logback.xml"; - - public static final String AVPN_INTERIM_LAG_INTERFACE = "aai.avpn.interim.laginterface"; - - public static final String AAI_TRUSTSTORE_FILENAME = "aai.truststore.filename"; - public static final String AAI_TRUSTSTORE_PASSWD = "aai.truststore.passwd"; - public static final String AAI_KEYSTORE_FILENAME = "aai.keystore.filename"; - public static final String AAI_KEYSTORE_PASSWD = "aai.keystore.passwd"; - - public static final String AAI_OLDSERVER_URL_BASE = "aai.oldserver.url.base"; - public static final String AAI_SERVER_URL_BASE = "aai.server.url.base"; - public static final String AAI_SERVER_URL = "aai.server.url"; - public static final String AAI_OLDSERVER_URL = "aai.oldserver.url"; - public static final String AAI_GLOBAL_CALLBACK_URL = "aai.global.callback.url"; - public static final String AAI_LOCAL_REST = "https://localhost:%d/aai/" + AAIProperties.LATEST + "/"; - public static final String AAI_APP_ROOT = "/aai/"; - - public static final int AAI_RESOURCES_PORT = 8447; - public static final int AAI_QUERY_PORT = 8446; - public static final int AAI_LEGACY_PORT = 8443; - - public static final String AAI_DEFAULT_API_VERSION = "v7"; - public static final String AAI_DEFAULT_API_VERSION_PROP = "aai.default.api.version"; - public static final String AAI_NOTIFICATION_CURRENT_VERSION = "aai.notification.current.version"; - - public static final String AAI_NODENAME = "aai.config.nodename"; - - public static final String AAI_LOGGING_HBASE_INTERCEPTOR = "aai.logging.hbase.interceptor"; - public static final String AAI_LOGGING_HBASE_ENABLED = "aai.logging.hbase.enabled"; - public static final String AAI_LOGGING_HBASE_LOGREQUEST = "aai.logging.hbase.logrequest"; - public static final String AAI_LOGGING_HBASE_LOGRESPONSE = "aai.logging.hbase.logresponse"; - - public static final String AAI_LOGGING_TRACE_ENABLED = "aai.logging.trace.enabled"; - public static final String AAI_LOGGING_TRACE_LOGREQUEST = "aai.logging.trace.logrequest"; - public static final String AAI_LOGGING_TRACE_LOGRESPONSE = "aai.logging.trace.logresponse"; - - public static final String AAI_CONFIG_CHECKINGTIME = "aai.config.checktime"; - public static final String AAI_DBMODEL_FILENAME = "aai.dbmodel.filename"; - public static final String AAI_RESVERSION_ENABLEFLAG = "aai.resourceversion.enableflag"; - - public static final int AAI_MAX_TRANS_RETRIES = 5; - public static final long AAI_TRANS_RETRY_SLEEP_MSEC = 500; - - public static final int AAI_GROOMING_DEFAULT_MAX_FIX = 150; - public static final int AAI_GROOMING_DEFAULT_SLEEP_MINUTES = 7; - - public static final int AAI_DUPETOOL_DEFAULT_MAX_FIX = 25; - public static final int AAI_DUPETOOL_DEFAULT_SLEEP_MINUTES = 7; - - public static final String LOGGING_MAX_STACK_TRACE_ENTRIES = "aai.logging.maxStackTraceEntries"; - - /** Default to skipping real-time grooming unless system property aai.skiprealtime.grooming is set to "false" */ - public static final String AAI_SKIPREALTIME_GROOMING = (System.getProperty("aai.skiprealtime.grooming") == null) ? "true" : System.getProperty("aai.skiprealtime.grooming"); - - - /*** UEB ***/ - public static final String UEB_PUB_PARTITION_AAI = "AAI"; - public static final String UEB_PUB_AAI_VCE_INTERFACE_DATA_TOPIC = "ueb.pub.aai.vce.interface.data.topic"; - - - /** Service description for Hosted Communications */ - public static final String AAI_SERVICEDESCRIPTION_HOSTEDCOMM = "aai.servicedescription.hostedcomm"; - - /** Service description for Mobility */ - public static final String AAI_SERVICEDESCRIPTION_MOBILITY = "aai.servicedescription.mobility"; - - /** Service description for Mobility */ - public static final String AAI_SERVICEDESCRIPTION_VUSP = "aai.servicedescription.vusp"; - - /** Service description for Vvig */ - public static final String AAI_SERVICEDESCRIPTION_VVIG = "aai.servicedescription.vvig"; - - /** Service description for LRSI */ - public static final String AAI_SERVICEDESCRIPTION_LRSI = "aai.servicedescription.lrsi"; - - /** - * Instantiates a new AAI constants. - */ - private AAIConstants() { - // prevent instantiation - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIMechIdConfig.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIMechIdConfig.java deleted file mode 100644 index 54331f4e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIMechIdConfig.java +++ /dev/null @@ -1,129 +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.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Set; - -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; - -import org.openecomp.aai.logging.ErrorLogHelper; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - -public class AAIMechIdConfig { - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIMechIdConfig.class); - private static final String mechIdConfigFileName = AAIConstants.AAI_HOME_ETC_APP_PROPERTIES + "mechid-config.json"; - - public static final String SYSTEM_GFP_IP = "GFP"; - public static final String SYSTEM_GCP = "GCP"; - public static final String SYSTEM_DCAE = "DCAE"; - public static final String SYSTEM_RUBY = "RUBY"; - public static final String SYSTEM_ACTION = "ACTION"; - public static final String SYSTEM_INSTAR = "INSTAR-LPP-AMS"; - public static final String FILE_CLASS_GFP_IP = "GFP-IP"; - public static final String FILE_CLASS_INSTAR = "INSTAR-LPP-AMS"; - - public static HashMap<String, String> mechIdtoSystem = new HashMap<String, String>(); - public static HashMap<String, ArrayList<String>> fileClassToMechId = new HashMap<String, ArrayList<String>>(); - - /** - * Inits the. - * - * @param tId the t id - * @param appId the app id - * @param logger the logger - */ - public static void init() { - LOGGER.debug("Initializing AAIMechIdConfig"); - Boolean enable; - String systemMechId = ""; - JSONParser parser = new JSONParser(); - - try { - Object obj = parser.parse(new FileReader(mechIdConfigFileName)); - JSONObject jsonObject = (JSONObject) obj; - JSONObject mechIds = (JSONObject) jsonObject.get("mech-ids"); - - @SuppressWarnings("unchecked") - Set<String> systemSet = mechIds.keySet(); - for (String system : systemSet) { - JSONObject systemJsonObj = (JSONObject) mechIds.get(system); - systemMechId = (String) systemJsonObj.get("mechid"); - enable = (Boolean) systemJsonObj.get("enable"); - if (systemMechId != null && !systemMechId.isEmpty() && enable != null && enable == true) { - mechIdtoSystem.put(systemMechId, system); - JSONArray fileClasses = (JSONArray) systemJsonObj.get("file-classes"); - if (fileClasses != null ) { - String fileClass = ""; - for (Object fileClassObj : fileClasses) { - fileClass = (String) fileClassObj; - - if (!fileClassToMechId.containsKey(fileClass)) { - fileClassToMechId.put(fileClass, new ArrayList<String>()); - fileClassToMechId.get(fileClass).add(systemMechId); - } else { - if(!fileClassToMechId.get(fileClass).contains(systemMechId)){ - fileClassToMechId.get(fileClass).add(systemMechId); - - } - } - } - } - } - } - - } catch (FileNotFoundException fnfe) { - ErrorLogHelper.logError("AAI_4001", - " " + mechIdConfigFileName + ". Exception: " + fnfe.getMessage()); - } catch (Exception e) { - ErrorLogHelper.logError("AAI_4004", - " " + mechIdConfigFileName + ". Exception: " + e.getMessage()); - } - } - - - /** - * Transform mech id to pickup dir. - * - * @param systemMechId the system mech id - * @return the string - */ - public static String transformMechIdToPickupDir(String systemMechId) { - String pickupDir = ""; - if (systemMechId != null && !systemMechId.isEmpty()) { - pickupDir = "/opt/aaihome/" + systemMechId + "/pickup"; - - if (pickupDir != null && !pickupDir.isEmpty() && new File(pickupDir).isDirectory()) { - return pickupDir; - } - - } - return null; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/AAIRSyncUtility.java b/aai-core/src/main/java/org/openecomp/aai/util/AAIRSyncUtility.java deleted file mode 100644 index 9c93d5ef..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/AAIRSyncUtility.java +++ /dev/null @@ -1,197 +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.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import org.openecomp.aai.exceptions.AAIException; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; - - -public class AAIRSyncUtility { - - private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(AAIRSyncUtility.class); - private final String DEFAULT_CHECK = new String("aai.primary.filetransfer."); - - /** - * Instantiates a new AAIR sync utility. - */ - public AAIRSyncUtility() { - - } - - /** - * Do command. - * - * @param command the command - * @return the int - * @throws Exception the exception - */ - public int doCommand(List<String> command) - throws Exception - { - String s = null; - - ProcessBuilder pb = new ProcessBuilder(command); - Process process = pb.start(); - - BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); - BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream())); - - LOGGER.debug("Here is the standard output of the command:\n"); - while ((s = stdInput.readLine()) != null) - { - LOGGER.debug(s); - } - - LOGGER.debug("Here is the standard error of the command (if any):\n"); - while ((s = stdError.readLine()) != null) - { - LOGGER.debug(s); - } - return process.waitFor(); - } - - - /** - * Method sendRsyncCommand. - * - * @param transId the trans id - * @param fileName the file name - */ - public void sendRsyncCommand(String transId, String fileName) - { - String aaiServerList = null; - String rsyncOptionsList = null; - - try { - aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist"); - rsyncOptionsList = AAIConfig.get("aai.rsync.options.list"); - String enableRsync = AAIConfig.get("aai.rsync.enabled"); - - if (!AAIConfig.isEmpty(enableRsync) && "n".equalsIgnoreCase(enableRsync)){ - LOGGER.info("rsync not invoked for " + fileName + ": rsync is not enabled in aaiconfig.properties"); - return; - } - } catch ( Exception e ) { - LOGGER.warn( "rsync not invoked: missing aaiconfig.properties entries for rsync" ); - } - - LOGGER.info("rsync to copy files started...."); - - ArrayList<String> remoteHostList = new ArrayList<String>(); - StringTokenizer serverList = new StringTokenizer( aaiServerList, "|" ); - String host = null; - try { - host = getHost(); - String remoteConnString = null; - - remoteHostList = getRemoteHostList(serverList, host); - LOGGER.debug("This host:" + host); - String pickUpDirectory = AAIConfig.get("instar.pickup.dir"); - String user = AAIConfig.get("aai.rsync.remote.user"); - String rsyncCmd = AAIConfig.get("aai.rsync.command"); - - //Push: rsync [OPTION...] SRC... [USER@]HOST:DEST - - java.util.Iterator<String> remoteHostItr = remoteHostList.iterator(); - while (!remoteHostList.isEmpty() && remoteHostItr.hasNext()) { - String remoteHost = remoteHostItr.next(); - remoteConnString =user+"@"+remoteHost+":"+pickUpDirectory; - - List<String> commands = new ArrayList<String>(); - commands.add(rsyncCmd); - StringTokenizer optionTks = new StringTokenizer( rsyncOptionsList, "|" ); - while (optionTks.hasMoreTokens()){ - commands.add(optionTks.nextToken()); - } - commands.add(fileName); // src directory/fileName - commands.add(remoteConnString); // target username/host/path - LOGGER.debug("Commands: " + commands.toString()); - int rsyncResult = doCommand(commands); - if ( rsyncResult == 0 ) { - LOGGER.info("rsync completed for "+remoteHost); - }else { - LOGGER.error("rsync failed for "+ remoteHost+ " with response code "+rsyncResult ); - } - } - } catch ( Exception e) { - LOGGER.error("no server found processing serverList for host " + host + ": " + e.getMessage() + " (AAI_4000)"); - } - } - - /** - * Gets the remote host list. - * - * @param serverList the server list - * @param host the host - * @return the remote host list - */ - private ArrayList<String> getRemoteHostList(StringTokenizer serverList, String host) { - ArrayList<String> remoteHostList = new ArrayList<String>(); - String remoteHost = null; - while ( serverList.hasMoreTokens() ) { - remoteHost = serverList.nextToken(); - if (!host.equalsIgnoreCase(remoteHost)){ - remoteHostList.add(remoteHost); - } - } - return remoteHostList; - } - - /** - * Gets the host. - * - * @return the host - * @throws AAIException the AAI exception - */ - private String getHost() throws AAIException { - String aaiServerList = AAIConfig.get(DEFAULT_CHECK + "serverlist"); - String hostname = null; - try { - InetAddress ip = InetAddress.getLocalHost(); - if ( ip != null ) { - hostname = ip.getHostName(); - if ( hostname != null ) { - if ( !( aaiServerList.contains(hostname) ) ) - LOGGER.warn("Host name not found in server list " + hostname); - } else - LOGGER.warn("InetAddress returned null hostname"); - } - - } catch (UnknownHostException e) { - LOGGER.warn("InetAddress getLocalHost exception " + e.getMessage()); - } - - return hostname; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/Entity.java b/aai-core/src/main/java/org/openecomp/aai/util/Entity.java deleted file mode 100644 index c1324043..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/Entity.java +++ /dev/null @@ -1,196 +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.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "equipment-role", - "action", - "key-value-list", - "self-link" -}) -public class Entity { - - @JsonProperty("equipment-role") - private String equipmentRole; - @JsonProperty("action") - private String action; - @JsonProperty("key-value-list") - private List<KeyValueList> keyValueList = new ArrayList<KeyValueList>(); - @JsonProperty("self-link") - private String selfLink; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * - * @return - * The equipmentRole - */ - @JsonProperty("equipment-role") - public String getEquipmentRole() { - return equipmentRole; - } - - /** - * - * @param equipmentRole - * The equipment-role - */ - @JsonProperty("equipment-role") - public void setEquipmentRole(String equipmentRole) { - this.equipmentRole = equipmentRole; - } - - public Entity withEquipmentRole(String equipmentRole) { - this.equipmentRole = equipmentRole; - return this; - } - - /** - * - * @return - * The action - */ - @JsonProperty("action") - public String getAction() { - return action; - } - - /** - * - * @param action - * The action - */ - @JsonProperty("action") - public void setAction(String action) { - this.action = action; - } - - public Entity withAction(String action) { - this.action = action; - return this; - } - - /** - * - * @return - * The keyValueList - */ - @JsonProperty("key-value-list") - public List<KeyValueList> getKeyValueList() { - return keyValueList; - } - - /** - * - * @param keyValueList - * The key-value-list - */ - @JsonProperty("key-value-list") - public void setKeyValueList(List<KeyValueList> keyValueList) { - this.keyValueList = keyValueList; - } - - public Entity withKeyValueList(List<KeyValueList> keyValueList) { - this.keyValueList = keyValueList; - return this; - } - - /** - * - * @return - * The selfLink - */ - @JsonProperty("self-link") - public String getSelfLink() { - return selfLink; - } - - /** - * - * @param selfLink - * The self-link - */ - @JsonProperty("self-link") - public void setSelfLink(String selfLink) { - this.selfLink = selfLink; - } - - public Entity withSelfLink(String selfLink) { - this.selfLink = selfLink; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public Entity withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(equipmentRole).append(action).append(keyValueList).append(selfLink).append(additionalProperties).toHashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof Entity) == false) { - return false; - } - Entity rhs = ((Entity) other); - return new EqualsBuilder().append(equipmentRole, rhs.equipmentRole).append(action, rhs.action).append(keyValueList, rhs.keyValueList).append(selfLink, rhs.selfLink).append(additionalProperties, rhs.additionalProperties).isEquals(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/EntityList.java b/aai-core/src/main/java/org/openecomp/aai/util/EntityList.java deleted file mode 100644 index 6bf06054..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/EntityList.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 java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "entity" -}) -public class EntityList { - - @JsonProperty("entity") - private List<Entity> entity = new ArrayList<Entity>(); - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * - * @return - * The entity - */ - @JsonProperty("entity") - public List<Entity> getEntity() { - return entity; - } - - /** - * - * @param entity - * The entity - */ - @JsonProperty("entity") - public void setEntity(List<Entity> entity) { - this.entity = entity; - } - - public EntityList withEntity(List<Entity> entity) { - this.entity = entity; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public EntityList withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(entity).append(additionalProperties).toHashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof EntityList) == false) { - return false; - } - EntityList rhs = ((EntityList) other); - return new EqualsBuilder().append(entity, rhs.entity).append(additionalProperties, rhs.additionalProperties).isEquals(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/FileWatcher.java b/aai-core/src/main/java/org/openecomp/aai/util/FileWatcher.java deleted file mode 100644 index 84e7a1a3..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/FileWatcher.java +++ /dev/null @@ -1,59 +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.util.*; -import java.io.*; - -public abstract class FileWatcher extends TimerTask { - private long timeStamp; - private File file; - - /** - * Instantiates a new file watcher. - * - * @param file the file - */ - public FileWatcher( File file ) { - this.file = file; - this.timeStamp = file.lastModified(); - } - - /** - * runs a timer task - * @see java.util.TimerTask.run - */ - public final void run() { - long timeStamp = file.lastModified(); - - if( (timeStamp - this.timeStamp) > 500 ) { - this.timeStamp = timeStamp; - onChange(file); - } - } - - /** - * On change. - * - * @param file the file - */ - protected abstract void onChange( File file ); -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java b/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java deleted file mode 100644 index d1489992..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/FormatDate.java +++ /dev/null @@ -1,46 +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.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; - -public class FormatDate { - - private final String timeZone; - private final String pattern; - public FormatDate(String pattern) { - this.pattern = pattern; - this.timeZone = "GMT"; - } - public FormatDate(String pattern, String timeZone) { - this.pattern = pattern; - this.timeZone = timeZone; - } - - public String getDateTime() { - - final DateTimeFormatter formatter = - DateTimeFormatter.ofPattern(pattern); - return formatter.format(ZonedDateTime.now(ZoneId.of(timeZone))); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/GenerateXsd.java b/aai-core/src/main/java/org/openecomp/aai/util/GenerateXsd.java deleted file mode 100644 index 15ea8a32..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/GenerateXsd.java +++ /dev/null @@ -1,1697 +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.google.common.base.Joiner; -import com.jayway.jsonpath.JsonPath; -import org.openecomp.aai.introspection.Version; -import org.openecomp.aai.serialization.db.EdgeProperty; -import org.w3c.dom.*; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.*; -import java.io.*; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; - - - -public class GenerateXsd { - - static String apiVersion = null; - static String apiVersionFmt = null; - static boolean useAnnotationsInXsd = false; - static String responsesUrl = null; - static String responsesLabel = null; - static String jsonEdges = null; - - static Map<String, String> generatedJavaType; - static Map<String, String> appliedPaths; - static NodeList javaTypeNodes; - - - public static final int VALUE_NONE = 0; - public static final int VALUE_DESCRIPTION = 1; - public static final int VALUE_INDEXED_PROPS = 2; - - private static final String generateTypeXSD = "xsd"; - private static final String generateTypeYAML = "yaml"; - - private static final String root = "../aai-schema/src/main/resources"; - private static final String xsd_dir = root + "/aai_schema"; - private static final String yaml_dir = root + "/aai_swagger_yaml"; - - private static int annotationsStartVersion = 9; // minimum version to support annotations in xsd - private static int swaggerSupportStartsVersion = 7; // minimum version to support swagger documentation - - private static XPath xpath = XPathFactory.newInstance().newXPath(); - - - private enum LineageType { - PARENT, CHILD, UNRELATED; - } - private class EdgeDescription { - - private String ruleKey; - private LineageType type = LineageType.UNRELATED; - private String direction; - private String multiplicity; - private boolean hasDelTarget = false; - - public String getRuleKey() { - return ruleKey; - } - public String getMultiplicity() { - return multiplicity; - } - public String getDirection() { - return direction; - } - public void setRuleKey(String val) { - this.ruleKey=val; - } - public void setType(LineageType val) { - this.type=val; - } - public void setDirection(String val) { - this.direction = val; - } - public void setMultiplicity(String val) { - this.multiplicity=val; - } - public void setHasDelTarget(String val) { - hasDelTarget = Boolean.parseBoolean(val); - } - - public String getRelationshipDescription(String fromTo, String otherNodeName) { - - String result = ""; - - if ("FROM".equals(fromTo)) { - if ("OUT".equals(direction)) { - if (LineageType.PARENT == type) { - result = " (is composed of "+otherNodeName; - } - } - else { - if (LineageType.CHILD == type) { - result = " (comprises "+otherNodeName; - } - else if (LineageType.PARENT == type) { - result = " (comprises "+otherNodeName; - } - } - } else { - if ("OUT".equals(direction)) { - if (LineageType.PARENT == type) { - result = " (comprises "+otherNodeName; - } - } else { - if (LineageType.PARENT == type) { - result = " (is composed of "+otherNodeName; - } - } - } - -// if (type != null) { -// if (LineageType.PARENT.equals(type) && "FROM".equals(fromTo)) { -// if ("OUT".equals(direction)) { -// result = " (is composed of "+otherNodeName; -// } else { -// result = " (comprises "+otherNodeName; -// } -// } else { -// result = " (comprises " + otherNodeName; -// // if (!(multiplicity.startsWith("One"))) { -// // System.err.println("Surprised to find multiplicity "+multiplicity+" with comprises for "+ruleKey); -// // } -// } -// } - if ("TO".equals(fromTo)) { - if (result.length() == 0) result = result + " ("; - else result = result + ", "; - - result = result + mapMultiplicity(fromTo); - if (hasDelTarget) result = result + ", will delete target node"; - } - - if (result.length() > 0) result = result + ")"; - - return result; - } - - private String mapMultiplicity(String fromTo) { - String result = multiplicity; -// Below logic works if an IN switches multiplicity, which it doesn't today. -// if ("TO".equals(fromTo)) { -// if (direction.equals("OUT")) { -// result = multiplicity; -// } else { -// result = switchMultiplicity(multiplicity); -// } -// } else { -// if (direction.equals("OUT")) { -// result = multiplicity; -// } else { -// result = switchMultiplicity(multiplicity); -// } -// } - return result; - } - -// private String switchMultiplicity(String val) throws IllegalArgumentException -// { -// String result = null; -// switch (val) { -// case "Many2Many": -// case "One2One": -// result = val; -// break; -// case "Many2One": -// result = "One2Many"; -// break; -// case "One2Many": -// result = "Many2One"; -// break; -// default: -// throw new IllegalArgumentException("Multiplicity cannot be "+val); -// } -// System.out.println("Switched Multiplicity from "+val+" to "+result); -// return result; -// } - } - - private static boolean validVersion(String versionToGen) { - - if ("ALL".equalsIgnoreCase(versionToGen)) { - return true; - } - - for (Version v : Version.values()) { - if (v.name().equals(versionToGen)) { - return true; - } - } - - return false; - } - - private static boolean versionUsesAnnotations( String version) { - if (new Integer(version.substring(1)).intValue() >= annotationsStartVersion ) { - return true; - } - return false; - } - - private static boolean versionSupportsSwagger( String version) { - if (new Integer(version.substring(1)).intValue() >= swaggerSupportStartsVersion ) { - return true; - } - return false; - } - - public static void main(String[] args) throws IOException { - String versionToGen = System.getProperty("gen_version").toLowerCase(); - String fileTypeToGen = System.getProperty("gen_type").toLowerCase(); - if ( fileTypeToGen == null ) { - fileTypeToGen = generateTypeXSD; - } - - if ( !fileTypeToGen.equals( generateTypeXSD ) && !fileTypeToGen.equals( generateTypeYAML )) { - System.err.println("Invalid gen_type passed. " + fileTypeToGen); - System.exit(1); - } - - - if ( versionToGen == null ) { - System.err.println("Version is required, ie v<n> or ALL."); - System.exit(1); - } - - responsesUrl = System.getProperty("yamlresponses_url"); - String responsesLabel = System.getProperty("yamlresponses_label"); - List<Version> versionsToGen = new ArrayList<>(); - - - if (!"ALL".equalsIgnoreCase(versionToGen) && !versionToGen.matches("v\\d+") && !validVersion(versionToGen)) { - System.err.println("Invalid version passed. " + versionToGen); - System.exit(1); - } - - if ("ALL".equalsIgnoreCase(versionToGen)) { - versionsToGen = Arrays.asList(Version.values()); - Collections.sort(versionsToGen); - Collections.reverse(versionsToGen); - } else { - versionsToGen.add(Version.valueOf(versionToGen)); - } - - if ( fileTypeToGen.equals(generateTypeYAML) ) { - if ( responsesUrl == null || responsesUrl.length() < 1 - || responsesLabel == null || responsesLabel.length() < 1 ) { - System.err.println("generating swagger yaml file requires yamlresponses_url and yamlresponses_label properties" ); - System.exit(1); - } - responsesUrl = "description: "+ responsesLabel+ "(" + responsesUrl + ").\n"; - } - String oxmPath = root + "/oxm/"; - - String outfileName; - File outfile; - String fileContent; - - for (Version v : versionsToGen) { - apiVersion = v.toString(); - System.out.println("Generating " + apiVersion + " " + fileTypeToGen); - File oxm_file = new File(oxmPath + "aai_oxm_" + apiVersion + ".xml"); - apiVersionFmt = "." + apiVersion + "."; - generatedJavaType = new HashMap<String, String>(); - appliedPaths = new HashMap<String, String>(); - if ( fileTypeToGen.equals(generateTypeXSD) ) { - useAnnotationsInXsd = versionUsesAnnotations(apiVersion); - outfileName = xsd_dir + "/aai_schema_" + apiVersion + "." + generateTypeXSD; - fileContent = processOxmFile(oxm_file, v); - } else if ( versionSupportsSwagger(apiVersion )) { - outfileName = yaml_dir + "/aai_swagger_" + apiVersion + "." + generateTypeYAML; - fileContent = generateSwaggerFromOxmFile( oxm_file); - } else { - continue; - } - outfile = new File(outfileName); - File parentDir = outfile.getParentFile(); - if(! parentDir.exists()) - parentDir.mkdirs(); - - try { - outfile.createNewFile(); - } catch (IOException e) { - System.out.println( "Exception creating output file " + outfileName); - e.printStackTrace(); - } - BufferedWriter bw = null; - try { - Charset charset = Charset.forName("UTF-8"); - Path path = Paths.get(outfileName); - bw = Files.newBufferedWriter(path, charset); - bw.write(fileContent); - } catch ( IOException e) { - System.out.println( "Exception writing output file " + outfileName); - e.printStackTrace(); - } finally { - if ( bw != null ) { - bw.close(); - } - } - System.out.println( "GeneratedXSD successful, saved in " + outfileName); - } - - } - - - public static String processJavaTypeElement( String javaTypeName, Element javaTypeElement) { - - String xmlRootElementName = null; - - NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - StringBuffer sb = new StringBuffer(); - if ( parentNodes.getLength() == 0 ) { - //System.out.println( "no java-attributes for java-type " + javaTypeName); - return ""; - - } - - NamedNodeMap attributes; - - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int i = 0; i < attributes.getLength(); ++i ) { - Attr attr = (Attr) attributes.item(i); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) - xmlRootElementName = attrValue; - } - /* - if ( javaTypeName.equals("RelationshipList")) { - System.out.println( "Skipping " + javaTypeName); - generatedJavaType.put(javaTypeName, null); - return ""; - } - */ - - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - NodeList childNodes; - Element childElement; - String xmlElementWrapper; - - Element xmlElementElement; - String addType; - String elementName, elementType, elementIsKey, elementIsRequired, elementContainerType; - StringBuffer sb1 = new StringBuffer(); - if ( xmlElementNodes.getLength() > 0 ) { - sb1.append(" <xs:element name=\"" + xmlRootElementName + "\">\n"); - sb1.append(" <xs:complexType>\n"); - NodeList properties = GenerateXsd.locateXmlProperties(javaTypeElement); - if (properties != null && useAnnotationsInXsd) { - //System.out.println("properties found for: " + xmlRootElementName); - sb1.append(" <xs:annotation>\r\n"); - insertAnnotation(properties, false, "class", sb1, " "); - - sb1.append(" </xs:annotation>\r\n"); - } /*else { - System.out.println("no properties found for: " + xmlRootElementName); - }*/ - sb1.append(" <xs:sequence>\n"); - for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { - - xmlElementElement = (Element)xmlElementNodes.item(i); - childNodes = xmlElementElement.getElementsByTagName("xml-element-wrapper"); - - xmlElementWrapper = null; - if ( childNodes.getLength() > 0 ) { - childElement = (Element)childNodes.item(0); - // get name - attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) { - xmlElementWrapper = attrValue; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - } - - } - attributes = xmlElementElement.getAttributes(); - addType = null; - - - elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - Attr attr = (Attr) attributes.item(j); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) { - elementName = attrValue; - } - if ( attrName.equals("type")) { - elementType = attrValue; - if ( attrValue.contains(apiVersionFmt) ) { - addType = attrValue.substring(attrValue.lastIndexOf('.')+1); - if ( !generatedJavaType.containsKey(addType) ) { - generatedJavaType.put(addType, attrValue); - sb.append(processJavaTypeElement( addType, getJavaTypeElement(addType) )); - } - } - - } - - if ( attrName.equals("xml-key")) { - elementIsKey = attrValue; - } - if ( attrName.equals("required")) { - elementIsRequired = attrValue; - } - if ( attrName.equals("container-type")) { - elementContainerType = attrValue; - } - } - - if ( xmlElementWrapper != null ) { - sb1.append(" <xs:element name=\"" + xmlElementWrapper +"\""); - if ( elementIsRequired == null || !elementIsRequired.equals("true")||addType != null) { - sb1.append(" minOccurs=\"0\""); - } - sb1.append(">\n"); - sb1.append(" <xs:complexType>\n"); - properties = GenerateXsd.locateXmlProperties(javaTypeElement); - if (properties != null && useAnnotationsInXsd) { - sb1.append(" <xs:annotation>\r\n"); - insertAnnotation(properties, false, "class", sb1, " "); - sb1.append(" </xs:annotation>\r\n"); - } /*else { - System.out.println("no properties found for: " + xmlElementWrapper); - }*/ - sb1.append(" <xs:sequence>\n"); - sb1.append(" "); - } - if ("Nodes".equals(addType)) { - //System.out.println ("Skipping nodes, temporary testing"); - continue; - } - if ( addType != null ) { - //sb1.append(" <xs:element ref=\"tns:" + elementName +"\""); - sb1.append(" <xs:element ref=\"tns:" + getXmlRootElementName(addType) +"\""); - } else { - sb1.append(" <xs:element name=\"" + elementName +"\""); - } - if ( elementType.equals("java.lang.String")) - sb1.append(" type=\"xs:string\""); - //if ( elementType.equals("java.lang.String")) - //sb1.append(" type=\"xs:string\""); - if ( elementType.equals("java.lang.Long")) - sb1.append(" type=\"xs:unsignedInt\""); - if ( elementType.equals("java.lang.Integer")) - sb1.append(" type=\"xs:int\""); - if ( elementType.equals("java.lang.Boolean")) - sb1.append(" type=\"xs:boolean\""); - //if ( elementIsRequired != null && elementIsRequired.equals("true")||addType != null) { - if ( elementIsRequired == null || !elementIsRequired.equals("true")||addType != null) { - sb1.append(" minOccurs=\"0\""); - } - if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) { - sb1.append(" maxOccurs=\"unbounded\""); - } - properties = GenerateXsd.locateXmlProperties(xmlElementElement); - if (properties != null || elementIsKey != null) { - sb1.append(">\n"); - if ( useAnnotationsInXsd ) { - sb1.append(" <xs:annotation>\r\n"); - insertAnnotation(properties, elementIsKey != null, "field", sb1, " "); - sb1.append(" </xs:annotation>\r\n"); - } - if (xmlElementWrapper== null) { - sb1.append(" </xs:element>\n"); - } - } else { - sb1.append("/>\n"); - } - if ( xmlElementWrapper != null ) { - sb1.append(" </xs:sequence>\n"); - sb1.append(" </xs:complexType>\n"); - sb1.append(" </xs:element>\n"); - } - } - /* - if ( xmlRootElementName.equals("notify") || - xmlRootElementName.equals("relationship") || - xmlRootElementName.equals("relationship-data") || - xmlRootElementName.equals("related-to-property") ) - - sb1.append(" <xs:any namespace=\"##other\" processContents=\"lax\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n"); - */ - sb1.append(" </xs:sequence>\n"); - sb1.append(" </xs:complexType>\n"); - sb1.append(" </xs:element>\n"); - } - /* - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int i = 0; i < attributes.getLength(); ++i ) { - Attr attr = (Attr) attributes.item(i); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrValue.equals("name")) - xmlRootElementName = attrValue; - } - */ - - if ( xmlElementNodes.getLength() < 1 ) { - sb.append(" <xs:element name=\"" + xmlRootElementName + "\">\n"); - sb.append(" <xs:complexType>\n"); - sb.append(" <xs:sequence/>\n"); - sb.append(" </xs:complexType>\n"); - sb.append(" </xs:element>\n"); - generatedJavaType.put(javaTypeName, null); - return sb.toString(); - } - - sb.append( sb1 ); - - return sb.toString(); - } - - private static void insertAnnotation(NodeList items, boolean isKey, String target, StringBuffer sb1, String indentation) { - if (items != null || isKey) { - List<String> metadata = new ArrayList<>(); - - String name = ""; - String value = ""; - Element item = null; - if (isKey) { - metadata.add("isKey=true"); - } - if (items != null) { - for (int i = 0; i < items.getLength(); i++) { - item = (Element)items.item(i); - name = item.getAttribute("name"); - value = item.getAttribute("value"); - if (name.equals("abstract")) { - name = "isAbstract"; - } else if (name.equals("extends")) { - name = "extendsFrom"; - } - metadata.add(name + "=\"" + value.replaceAll("&", "&") + "\""); - //System.out.println("property name: " + name); - - } - } - sb1.append( - indentation + " <xs:appinfo>\r\n" + - indentation + " <annox:annotate target=\""+target+"\">@org.openecomp.aai.annotations.Metadata(" + Joiner.on(",").join(metadata) + ")</annox:annotate>\r\n" + - indentation + " </xs:appinfo>\r\n"); - } - - } - - private static Element getJavaTypeElement( String javaTypeName ) - { - - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) - return javaTypeElement; - } - } - System.out.println( "oxm file format error, missing java-type " + javaTypeName); - return (Element) null; - } - - private static Element getJavaTypeElementSwagger( String javaTypeName ) - { - - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) - return javaTypeElement; - } - } - System.out.println( "oxm file format error, missing java-type " + javaTypeName); - return (Element) null; - } - private static String getXmlRootElementName( String javaTypeName ) - { - - String attrName, attrValue; - Attr attr; - Element javaTypeElement; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals(javaTypeName)) { - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - attr = (Attr) attributes.item(k); - attrName = attr.getNodeName(); - - attrValue = attr.getNodeValue(); - //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) - return (attrValue); - } - } - } - } - System.out.println( "oxm file format error, missing java-type " + javaTypeName); - return null; - } - - - public static String processOxmFile( File oxmFile, Version v ) - { - StringBuilder sb = new StringBuilder(); - sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"); - String namespace = "org.openecomp"; - if ( useAnnotationsInXsd ) { - sb.append("<xs:schema elementFormDefault=\"qualified\" version=\"1.0\" targetNamespace=\"http://" + namespace + ".aai.inventory/" - + apiVersion + "\" xmlns:tns=\"http://" + namespace + ".aai.inventory/" + apiVersion + "\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" - + "\n" - + "xmlns:jaxb=\"http://java.sun.com/xml/ns/jaxb\"\r\n" + - " jaxb:version=\"2.1\" \r\n" + - " xmlns:annox=\"http://annox.dev.java.net\" \r\n" + - " jaxb:extensionBindingPrefixes=\"annox\">\n\n"); - } else { - sb.append("<xs:schema elementFormDefault=\"qualified\" version=\"1.0\" targetNamespace=\"http://" + namespace + ".aai.inventory/" - + apiVersion + "\" xmlns:tns=\"http://" + namespace + ".aai.inventory/" + apiVersion + "\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n\n"); - } - - try { - - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(oxmFile); - - NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); - Element bindingElement; - NodeList javaTypesNodes; - Element javaTypesElement; - - Element javaTypeElement; - - - if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { - System.out.println( "missing <binding-nodes> in " + oxmFile ); - return null; - } - - bindingElement = (Element) bindingsNodes.item(0); - javaTypesNodes = bindingElement.getElementsByTagName("java-types"); - if ( javaTypesNodes.getLength() < 1 ) { - System.out.println( "missing <binding-nodes><java-types> in " + oxmFile ); - return null; - } - javaTypesElement = (Element) javaTypesNodes.item(0); - javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); - if ( javaTypeNodes.getLength() < 1 ) { - System.out.println( "missing <binding-nodes><java-types><java-type> in " + oxmFile ); - return null; - } - - String javaTypeName; - String attrName, attrValue; - Attr attr; - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - javaTypeName = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) - javaTypeName = attrValue; - } - if ( javaTypeName == null ) { - System.out.println( "<java-type> has no name attribute in " + oxmFile ); - return null; - } - if ("Nodes".equals(javaTypeName)) { - //System.out.println("skipping Nodes entry (temporary feature)"); - continue; - } - if ( !generatedJavaType.containsKey(javaTypeName) ) { - generatedJavaType.put(javaTypeName, null); - sb.append(processJavaTypeElement( javaTypeName, javaTypeElement )); - } - } - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - sb.append("</xs:schema>\n"); - return sb.toString(); - } - - private static boolean isStandardType( String elementType ) - { - switch ( elementType ) { - case "java.lang.String": - case "java.lang.Long": - case "java.lang.Integer": - case"java.lang.Boolean": - return true; - } - return false; - } - - private static Vector<String> getIndexedProps( String attrValue ) - { - if ( attrValue == null ) - return null; - StringTokenizer st = new StringTokenizer( attrValue, ","); - if ( st.countTokens() == 0 ) - return null; - Vector<String> result = new Vector<String>(); - while ( st.hasMoreTokens()) { - result.add(st.nextToken()); - } - return result; - } - - /** - * Guaranteed to at least return non null but empty collection of edge descriptions - * @param nodeName name of the vertex whose edge relationships to return - * @return collection of node neighbors based on DbEdgeRules - **/ - private static Collection<EdgeDescription> getEdgeRulesFromJson( String path, boolean skipMatch ) - { - - ArrayList<EdgeDescription> result = new ArrayList<>(); - Iterator<Map<String, Object>> edgeRulesIterator; - try { - - GenerateXsd x = new GenerateXsd(); - - List<Map<String, Object>> inEdges = JsonPath.parse(jsonEdges).read(path); - - edgeRulesIterator = inEdges.iterator(); - Map<String, Object> edgeMap; - String fromNode; - String toNode; - String ruleKey; - String direction; - String multiplicity; - String isParent; - String hasDelTarget; - EdgeDescription edgeDes; - - while( edgeRulesIterator.hasNext() ){ - edgeMap = edgeRulesIterator.next(); - fromNode = (String)edgeMap.get("from"); - toNode = (String)edgeMap.get("to"); - if ( skipMatch ) { - if ( fromNode.equals(toNode)) { - continue; - } - } - edgeDes = x.new EdgeDescription(); - edgeDes.setRuleKey(fromNode + "|" + toNode); - direction = (String)edgeMap.get("direction"); - edgeDes.setDirection(direction); - multiplicity = (String)edgeMap.get("multiplicity"); - edgeDes.setMultiplicity(multiplicity); - isParent = (String)edgeMap.get(EdgeProperty.CONTAINS.toString()); - if ( "${direction}".equals(isParent)) { - edgeDes.setType(LineageType.PARENT); - } else { - edgeDes.setType(LineageType.UNRELATED); - } - hasDelTarget = (String)edgeMap.get(EdgeProperty.DELETE_OTHER_V.toString()); - edgeDes.setHasDelTarget(hasDelTarget); - result.add(edgeDes); - - } - } catch (Exception ex) { - ex.printStackTrace(); - } - return result; - - } - - /** - * Guaranteed to at least return non null but empty collection of edge descriptions - * @param nodeName name of the vertex whose edge relationships to return - * @return collection of node neighbors based on DbEdgeRules - **/ - private static Collection<EdgeDescription> getEdgeRules( String nodeName ) - { - String fromRulesPath = "$['rules'][?(@['from']=='" + nodeName + "')]"; - String toRulesPath = "$['rules'][?(@['to']=='" + nodeName + "')]"; - Collection<EdgeDescription> fromEdges = getEdgeRulesFromJson( fromRulesPath, false ); - Collection<EdgeDescription> edges = getEdgeRulesFromJson( toRulesPath, true ); - edges.addAll(fromEdges); - return edges; - } - - public static String processJavaTypeElementSwagger( String javaTypeName, Element javaTypeElement, - StringBuffer pathSb, StringBuffer definitionsSb, String path, String tag, String opId, - String getItemName, StringBuffer pathParams, String queryParams, String validEdges) { - - String xmlRootElementName = null; - - //Map<String, String> addJavaType = new HashMap<String, String>(); - String useTag = null; - String useOpId = null; - - if ( tag != null ) { - switch ( tag ) { - case "Network": - case "ServiceDesignAndCreation": - case "Business": - case "LicenseManagement": - case "CloudInfrastructure": - case "ExternalSystem": - break; - default: - return null; - } - } - /* - if ( path == null ) - System.out.println( "processJavaTypeElementSwagger called with null path for javaTypeName " + javaTypeName); - */ - /* - if ( path == null || !(path.contains("cloud-infrastructure"))) - switch ( javaTypeName) { - case "Inventory": - useTag = null; - break; - - case "CloudInfrastructure": - case "Search": - case "Actions": - case "ServiceDesignAndCreation": - case "LicenseManagement": - case "Network": - if ( tag == null ) - useTag = javaTypeName; - - break; - default: - return null; - - } - */ - - if ( !javaTypeName.equals("Inventory") ) { - if ( javaTypeName.equals("AaiInternal")) - return null; - if ( opId == null ) - useOpId = javaTypeName; - else - useOpId = opId + javaTypeName; - if ( tag == null ) - useTag = javaTypeName; - } - - /* - if ( javaTypeName.equals("GenericVnf")) - System.out.println( "Processing " + javaTypeName); - else if ( javaTypeName.equals("Service")) - System.out.println( "Processing " + javaTypeName); - else if ( javaTypeName.equals("SitePair")) - System.out.println( "Processing " + javaTypeName); - */ - NodeList parentNodes = javaTypeElement.getElementsByTagName("java-attributes"); - - if ( parentNodes.getLength() == 0 ) { - //System.out.println( "no java-attributes for java-type " + javaTypeName); - return ""; - - } - - NamedNodeMap attributes; - - NodeList valNodes = javaTypeElement.getElementsByTagName("xml-root-element"); - Element valElement = (Element) valNodes.item(0); - attributes = valElement.getAttributes(); - for ( int i = 0; i < attributes.getLength(); ++i ) { - Attr attr = (Attr) attributes.item(i); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("Found xml-root-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) - xmlRootElementName = attrValue; - } - /* - if ( xmlRootElementName.equals("oam-networks")) - System.out.println( "xmlRootElement oam-networks with getItemData [" + getItemName + "]"); - */ - //already processed - /* - if ( generatedJavaType.containsKey(xmlRootElementName) ) { - return null; - } - */ - NodeList childNodes; - Element childElement; - NodeList xmlPropNodes = javaTypeElement.getElementsByTagName("xml-properties"); - Element xmlPropElement; - String pathDescriptionProperty = null; - - - Vector<String> indexedProps = null; - - /*System.out.println( "javaTypeName " + javaTypeName + " has xml-properties length " + xmlPropNodes.getLength()); - if ( path != null && path.equals("/network/generic-vnfs")) - System.out.println("path is " + "/network/generic-vnfs with getItemName " + getItemName); - */ - if ( xmlPropNodes.getLength() > 0 ) { - - for ( int i = 0; i < xmlPropNodes.getLength(); ++i ) { - xmlPropElement = (Element)xmlPropNodes.item(i); - if ( !xmlPropElement.getParentNode().isSameNode(javaTypeElement)) - continue; - childNodes = xmlPropElement.getElementsByTagName("xml-property"); - - if ( childNodes.getLength() > 0 ) { - for ( int j = 0; j < childNodes.getLength(); ++j ) { - childElement = (Element)childNodes.item(j); - // get name - int useValue = VALUE_NONE; - attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName == null || attrValue == null ) - continue; - if ( attrName.equals("name") && attrValue.equals("description")) { - useValue = VALUE_DESCRIPTION; - } - if ( useValue == VALUE_DESCRIPTION && attrName.equals("value")) { - pathDescriptionProperty = attrValue; - //break; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - if ( attrValue.equals("indexedProps")) { - useValue = VALUE_INDEXED_PROPS; - } - if ( useValue == VALUE_INDEXED_PROPS && attrName.equals("value")) { - indexedProps = getIndexedProps( attrValue ); - } - } - } - } - } - } - //System.out.println("javaTypeName " + javaTypeName + " description " + pathDescriptionProperty); - - /* - if ( javaTypeName.equals("RelationshipList")) { - System.out.println( "Skipping " + javaTypeName); - generatedJavaType.put(javaTypeName, null); - return ""; - } - */ - - Element parentElement = (Element)parentNodes.item(0); - NodeList xmlElementNodes = parentElement.getElementsByTagName("xml-element"); - - - String attrDescription = null; - - Element xmlElementElement; - String addType = null; - String elementType = null, elementIsKey = null, elementIsRequired, elementContainerType = null; - String elementName = null; - StringBuffer sbParameters = new StringBuffer(); - - StringBuffer sbRequired = new StringBuffer(); - int requiredCnt = 0; - int propertyCnt = 0; - StringBuffer sbProperties = new StringBuffer(); - StringBuffer sbIndexedParams = new StringBuffer(); - - - StringTokenizer st; - if ( xmlRootElementName.equals("inventory")) - path = ""; - else if ( path == null ) - //path = "/aai/" + apiVersion; - path = "/" + xmlRootElementName; - else - path += "/" + xmlRootElementName; - st = new StringTokenizer(path, "/"); - /* - if ( path.equals("/business/customers/customer/{global-customer-id}/service-subscriptions/service-subscription")) - System.out.println("processing path /business/customers/customer/{global-customer-id}/service-subscriptions with tag " + tag); - */ - boolean genPath = false; - /* - if ( path != null && path.equals("/network/generic-vnfs/generic-vnf")) - System.out.println("path is " + "/network/generic-vnfs/generic-vnf"); - */ - if ( st.countTokens() > 1 && getItemName == null ) { - if ( appliedPaths.containsKey(path)) - return null; - appliedPaths.put(path, null); - genPath = true; - if ( path.contains("/relationship/") ) { // filter paths with relationship-list - genPath = false; - } - if ( path.endsWith("/relationship-list")) { - genPath = false; - } - - } - - Vector<String> addTypeV = null; - if ( xmlElementNodes.getLength() > 0 ) { - - for ( int i = 0; i < xmlElementNodes.getLength(); ++i ) { - xmlElementElement = (Element)xmlElementNodes.item(i); - if ( !xmlElementElement.getParentNode().isSameNode(parentElement)) - continue; - /*childNodes = xmlElementElement.getElementsByTagName("xml-element-wrapper"); - if ( childNodes.getLength() > 0 ) { - childElement = (Element)childNodes.item(0); - // get name - attributes = childElement.getAttributes(); - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) { - xmlElementWrapper = attrValue; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - } - - } - */ - valNodes = xmlElementElement.getElementsByTagName("xml-properties"); - attrDescription = null; - if ( valNodes.getLength() > 0 ) { - for ( int j = 0; j < valNodes.getLength(); ++j ) { - valElement = (Element)valNodes.item(j); - if ( !valElement.getParentNode().isSameNode(xmlElementElement)) - continue; - childNodes = valElement.getElementsByTagName("xml-property"); - if ( childNodes.getLength() > 0 ) { - childElement = (Element)childNodes.item(0); - // get name - attributes = childElement.getAttributes(); - attrDescription = null; - boolean useValue = false; - for ( int k = 0; k < attributes.getLength(); ++k ) { - Attr attr = (Attr) attributes.item(k); - String attrName = attr.getNodeName(); - String attrValue = attr.getNodeValue(); - if ( attrName.equals("name") && attrValue.equals("description")) { - useValue = true; - } - if ( useValue && attrName.equals("value")) { - attrDescription = attrValue; - //System.out.println("found xml-element-wrapper " + xmlElementWrapper); - } - } - - } - } - } - - attributes = xmlElementElement.getAttributes(); - addTypeV = null; // vector of 1 - addType = null; - - elementName = elementType = elementIsKey = elementIsRequired = elementContainerType = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - Attr attr = (Attr) attributes.item(j); - String attrName = attr.getNodeName(); - - String attrValue = attr.getNodeValue(); - //System.out.println("For " + xmlRootElementName + " Found xml-element attribute: " + attrName + " with value: " + attrValue); - if ( attrName.equals("name")) { - elementName = attrValue; - - } - if ( attrName.equals("type") && getItemName == null ) { - elementType = attrValue; - if ( attrValue.contains(apiVersionFmt) ) { - addType = attrValue.substring(attrValue.lastIndexOf('.')+1); - if ( addTypeV == null ) - addTypeV = new Vector<String>(); - addTypeV.add(addType); - } - - } - if ( attrName.equals("xml-key")) { - elementIsKey = attrValue; - path += "/{" + elementName + "}"; - } - if ( attrName.equals("required")) { - elementIsRequired = attrValue; - } - if ( attrName.equals("container-type")) { - elementContainerType = attrValue; - } - } - if ( getItemName != null ) { - if ( getItemName.equals("array") ) { - if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) { - //System.out.println( " returning array " + elementName ); - return elementName; - } - - } else { // not an array check - if ( elementContainerType == null || !elementContainerType.equals("java.util.ArrayList")) { - //System.out.println( " returning object " + elementName ); - return elementName; - } - - } - //System.out.println( " returning null" ); - return null; - } - if ( elementIsRequired != null ) { - if ( requiredCnt == 0 ) - sbRequired.append(" required:\n"); - ++requiredCnt; - if ( addTypeV != null ) { - for ( int k = 0; k < addTypeV.size(); ++i ) { - sbRequired.append(" - " + getXmlRootElementName(addTypeV.elementAt(k)) + ":\n"); - } - } else - sbRequired.append(" - " + elementName + "\n"); - - } - - if ( elementIsKey != null ) { - sbParameters.append((" - name: " + elementName + "\n")); - sbParameters.append((" in: path\n")); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbParameters.append((" description: " + attrDescription + "\n")); - sbParameters.append((" required: true\n")); - if ( elementType.equals("java.lang.String")) - sbParameters.append(" type: string\n"); - if ( elementType.equals("java.lang.Long")) { - sbParameters.append(" type: integer\n"); - sbParameters.append(" format: int64\n"); - } - if ( elementType.equals("java.lang.Integer")) { - sbParameters.append(" type: integer\n"); - sbParameters.append(" format: int32\n"); - } - if ( elementType.equals("java.lang.Boolean")) - sbParameters.append(" type: boolean\n"); - - - } else if ( indexedProps != null - && indexedProps.contains(elementName ) ) { - sbIndexedParams.append((" - name: " + elementName + "\n")); - sbIndexedParams.append((" in: query\n")); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbIndexedParams.append((" description: " + attrDescription + "\n")); - sbIndexedParams.append((" required: false\n")); - if ( elementType.equals("java.lang.String")) - sbIndexedParams.append(" type: string\n"); - if ( elementType.equals("java.lang.Long")) { - sbIndexedParams.append(" type: integer\n"); - sbIndexedParams.append(" format: int64\n"); - } - if ( elementType.equals("java.lang.Integer")) { - sbIndexedParams.append(" type: integer\n"); - sbIndexedParams.append(" format: int32\n"); - } - if ( elementType.equals("java.lang.Boolean")) - sbIndexedParams.append(" type: boolean\n"); - } - - /* - if ( elementName != null && elementName.equals("inventory-item")) - System.out.println( "processing inventory-item elementName"); - */ - - if ( isStandardType(elementType)) { - sbProperties.append(" " + elementName + ":\n"); - ++propertyCnt; - sbProperties.append(" type: "); - - if ( elementType.equals("java.lang.String")) - sbProperties.append("string\n"); - else if ( elementType.equals("java.lang.Long")) { - sbProperties.append("integer\n"); - sbProperties.append(" format: int64\n"); - } - else if ( elementType.equals("java.lang.Integer")){ - sbProperties.append("integer\n"); - sbProperties.append(" format: int32\n"); - } - else if ( elementType.equals("java.lang.Boolean")) - sbProperties.append("boolean\n"); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbProperties.append(" description: " + attrDescription + "\n"); - } - - //if ( addType != null && elementContainerType != null && elementContainerType.equals("java.util.ArrayList") ) { - - if ( addTypeV != null ) { - StringBuffer newPathParams = null; - if ( pathParams != null ) { - newPathParams = new StringBuffer(); - newPathParams.append(pathParams); - } - if ( sbParameters.toString().length() > 0 ) { - if ( newPathParams == null ) - newPathParams = new StringBuffer(); - newPathParams.append(sbParameters); - } - String newQueryParams = null; - if ( sbIndexedParams.toString().length() > 0 ) { - if ( queryParams == null ) - newQueryParams = sbIndexedParams.toString(); - else - newQueryParams = queryParams + sbIndexedParams.toString(); - } else { - newQueryParams = queryParams; - } - for ( int k = 0; k < addTypeV.size(); ++k ) { - addType = addTypeV.elementAt(k); - - if ( opId == null || !opId.contains(addType)) { - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, null, - newPathParams, newQueryParams, validEdges); - } - // need item name of array - String itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - "array", null, null, null ); - - if ( itemName != null ) { - if ( addType.equals("AaiInternal") ) { - //System.out.println( "addType AaiInternal, skip properties"); - - } else if ( getItemName == null) { - ++propertyCnt; - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items:\n"); - sbProperties.append(" $ref: \"#/definitions/" + itemName + "\"\n"); - if ( attrDescription != null && attrDescription.length() > 0 ) - sbProperties.append(" description: " + attrDescription + "\n"); - } - } else { - /*itemName = processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, "other" ); - if ( itemName != null ) { - */ - if ( elementContainerType != null && elementContainerType.equals("java.util.ArrayList")) { - // need properties for getXmlRootElementName(addType) - newPathParams = null; - if ( pathParams != null ) { - newPathParams = new StringBuffer(); - newPathParams.append(pathParams); - } - if ( sbParameters.toString().length() > 0 ) { - if ( newPathParams == null ) - newPathParams = new StringBuffer(); - newPathParams.append(sbParameters); - } - newQueryParams = null; - if ( sbIndexedParams.toString().length() > 0 ) { - if ( queryParams == null ) - newQueryParams = sbIndexedParams.toString(); - else - newQueryParams = queryParams + sbIndexedParams.toString(); - } else { - newQueryParams = queryParams; - } - processJavaTypeElementSwagger( addType, getJavaTypeElementSwagger(addType), - pathSb, definitionsSb, path, tag == null ? useTag : tag, useOpId, - null, newPathParams, newQueryParams, validEdges ); - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: array\n items: \n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - } else { - sbProperties.append(" " + getXmlRootElementName(addType) + ":\n"); - sbProperties.append(" type: object\n"); - sbProperties.append(" $ref: \"#/definitions/" + getXmlRootElementName(addType) + "\"\n"); - } - if ( attrDescription != null && attrDescription.length() > 0 ) - sbProperties.append(" description: " + attrDescription + "\n"); - ++propertyCnt; - /*} - else { - System.out.println(" unable to define swagger object for " + addType); - } - */ - } - //if ( getItemName == null) looking for missing properties - //generatedJavaType.put(addType, null); - } - } - } - } - if ( genPath ) { - /* - if ( useOpId.equals("CloudInfrastructureComplexesComplexCtagPools")) - System.out.println( "adding path CloudInfrastructureComplexesComplexCtagPools"); - */ - - if ( !path.endsWith("/relationship") ) { - pathSb.append(" " + path + ":\n" ); - pathSb.append(" get:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - pathSb.append(" summary: returns " + xmlRootElementName + "\n"); - - pathSb.append(" description: returns " + xmlRootElementName + "\n"); - pathSb.append(" operationId: get" + useOpId + "\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful operation\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + responsesUrl); - /* - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful operation\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); - pathSb.append(" \"404\":\n"); - pathSb.append(" description: resource was not found\n"); - pathSb.append(" \"400\":\n"); - pathSb.append(" description: bad request\n"); - */ - if ( path.indexOf('{') > 0 ) { - - if ( sbParameters.toString().length() > 0 ) { - if ( pathParams == null ) - pathParams = new StringBuffer(); - pathParams.append(sbParameters); - } - if ( pathParams != null) { - pathSb.append(" parameters:\n"); - pathSb.append(pathParams); - } else - System.out.println( "null pathParams for " + useOpId); - if ( sbIndexedParams.toString().length() > 0 ) { - if ( queryParams == null ) - queryParams = sbIndexedParams.toString(); - else - queryParams = queryParams + sbIndexedParams.toString(); - } - if ( queryParams != null ) { - if ( pathParams == null ) { - pathSb.append(" parameters:\n"); - } - pathSb.append(queryParams); - } - } - } - boolean skipPutDelete = false; // no put or delete for "all" - if ( !path.endsWith("/relationship") ) { - if ( !path.endsWith("}") ){ - skipPutDelete = true; - } - - } - if ( path.indexOf('{') > 0 && !opId.startsWith("Search") &&!skipPutDelete) { - // add PUT - if ( path.endsWith("/relationship") ) { - pathSb.append(" " + path + ":\n" ); - } - pathSb.append(" put:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - - if ( path.endsWith("/relationship") ) { - pathSb.append(" summary: see node definition for valid relationships\n"); - } else { - pathSb.append(" summary: create or update an existing " + xmlRootElementName + "\n"); - pathSb.append(" description: create or update an existing " + xmlRootElementName + "\n"); - } - pathSb.append(" operationId: createOrUpdate" + useOpId + "\n"); - pathSb.append(" consumes:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" responses:\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + responsesUrl); - /* - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: existing resource has been modified and there is a response buffer\n"); - pathSb.append(" \"201\":\n"); - pathSb.append(" description: new resource is created\n"); - pathSb.append(" \"202\":\n"); - pathSb.append(" description: action requested but may have taken other actions as well, which are returned in the response payload\n"); - pathSb.append(" \"204\":\n"); - pathSb.append(" description: existing resource has been modified and there is no response buffer\n"); - pathSb.append(" \"400\":\n"); - pathSb.append(" description: Bad Request will be returned if headers are missing\n"); - pathSb.append(" \"404\":\n"); - pathSb.append(" description: Not Found will be returned if an unknown URL is used\n"); - */ - pathSb.append(" parameters:\n"); - //pathSb.append(" - in: path\n"); - pathSb.append(pathParams); // for nesting - pathSb.append(" - name: body\n"); - pathSb.append(" in: body\n"); - pathSb.append(" description: " + xmlRootElementName + " object that needs to be created or updated\n"); - pathSb.append(" required: true\n"); - pathSb.append(" schema:\n"); - pathSb.append(" $ref: \"#/definitions/" + xmlRootElementName + "\"\n"); - /* - if ( queryParams != null ) { - pathSb.append(queryParams); - } - */ - // add DELETE - pathSb.append(" delete:\n"); - pathSb.append(" tags:\n"); - pathSb.append(" - " + tag + "\n"); - pathSb.append(" summary: delete an existing " + xmlRootElementName + "\n"); - - pathSb.append(" description: delete an existing " + xmlRootElementName + "\n"); - - pathSb.append(" operationId: delete" + useOpId + "\n"); - pathSb.append(" consumes:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" produces:\n"); - pathSb.append(" - application/json\n"); - pathSb.append(" - application/xml\n"); - pathSb.append(" responses:\n"); - pathSb.append(" \"default\":\n"); - pathSb.append(" " + responsesUrl); - /* - pathSb.append(" responses:\n"); - pathSb.append(" \"200\":\n"); - pathSb.append(" description: successful, the response includes an entity describing the status\n"); - pathSb.append(" \"204\":\n"); - pathSb.append(" description: successful, action has been enacted but the response does not include an entity\n"); - pathSb.append(" \"400\":\n"); - pathSb.append(" description: Bad Request will be returned if headers are missing\n"); - pathSb.append(" \"404\":\n"); - pathSb.append(" description: Not Found will be returned if an unknown URL is used\n"); - */ - pathSb.append(" parameters:\n"); - //pathSb.append(" - in: path\n"); - pathSb.append(pathParams); // for nesting - if ( !path.endsWith("/relationship") ) { - pathSb.append(" - name: resource-version\n"); - - pathSb.append(" in: query\n"); - pathSb.append(" description: resource-version for concurrency\n"); - pathSb.append(" required: true\n"); - pathSb.append(" type: string\n"); - } - /* - if ( queryParams != null ) { - pathSb.append(queryParams); - } - */ - } - - } - if ( generatedJavaType.containsKey(xmlRootElementName) ) { - return null; - } - - definitionsSb.append(" " + xmlRootElementName + ":\n"); - Collection<EdgeDescription> edges = getEdgeRules(xmlRootElementName ); - if ( edges.size() > 0 ) { - StringBuffer sbEdge = new StringBuffer(); - sbEdge.append(" ###### Related Nodes\n"); - for (EdgeDescription ed : edges) { - if ( ed.getRuleKey().startsWith(xmlRootElementName)) { - sbEdge.append(" - TO ").append(ed.getRuleKey().substring(ed.getRuleKey().indexOf("|")+1)); - sbEdge.append(ed.getRelationshipDescription("TO", xmlRootElementName)); - sbEdge.append("\n"); - } - } - for (EdgeDescription ed : edges) { - if ( ed.getRuleKey().endsWith(xmlRootElementName)) { - sbEdge.append(" - FROM ").append(ed.getRuleKey().substring(0, ed.getRuleKey().indexOf("|"))); - sbEdge.append(ed.getRelationshipDescription("FROM", xmlRootElementName)); - sbEdge.append("\n"); - } - } - validEdges = sbEdge.toString(); - } - - // Handle description property. Might have a description OR valid edges OR both OR neither. - // Only put a description: tag if there is at least one. - if (pathDescriptionProperty != null || validEdges != null) { - definitionsSb.append(" description: |\n"); - - if ( pathDescriptionProperty != null ) - definitionsSb.append(" " + pathDescriptionProperty + "\n" ); - if (validEdges != null) - definitionsSb.append(validEdges); - } - - if ( requiredCnt > 0 ) - definitionsSb.append(sbRequired); - if ( propertyCnt > 0 ) { - definitionsSb.append(" properties:\n"); - definitionsSb.append(sbProperties); - } - generatedJavaType.put(xmlRootElementName, null); - return null; - } - - public static String generateSwaggerFromOxmFile( File oxmFile ) - { - - StringBuffer sb = new StringBuffer(); - sb.append("swagger: \"2.0\"\ninfo:\n description: |\n Copyright © 2017 AT&T Intellectual Property. All rights reserved.\n\n Licensed under the Creative Commons License, Attribution 4.0 Intl. (the "License"); you may not use this documentation except in compliance with the License.\n\n You may obtain a copy of the License at\n\n (https://creativecommons.org/licenses/by/4.0/)\n\n 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.\n\n ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property.\n\n This document is best viewed with Firefox or Chrome. Nodes can be found by appending /#/definitions/node-type-to-find to the path to this document. Edge definitions can be found with the node definitions.\n version: \"" + apiVersion +"\"\n"); - sb.append(" title: Active and Available Inventory REST API\n"); - sb.append(" license:\n name: Apache 2.0\n url: http://www.apache.org/licenses/LICENSE-2.0.html\n"); - sb.append(" contact:\n name:\n url:\n email:\n"); - sb.append("host:\nbasePath: /aai/" + apiVersion + "\n"); - sb.append("schemes:\n - https\npaths:\n"); - /* - sb.append("responses:\n"); - sb.append(" \"200\":\n"); - sb.append(" description: successful operation\n"); - sb.append(" \"404\":\n"); - sb.append(" description: resource was not found\n"); - sb.append(" \"400\":\n"); - sb.append(" description: bad request\n"); - */ - try { - File initialFile = new File("src/main/resources/dbedgerules/DbEdgeRules_" + apiVersion + ".json"); - InputStream is = new FileInputStream(initialFile); - - Scanner scanner = new Scanner(is); - jsonEdges = scanner.useDelimiter("\\Z").next(); - scanner.close(); - is.close(); - - DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); - dbFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); - Document doc = dBuilder.parse(oxmFile); - - NodeList bindingsNodes = doc.getElementsByTagName("xml-bindings"); - Element bindingElement; - NodeList javaTypesNodes; - Element javaTypesElement; - - Element javaTypeElement; - - - if ( bindingsNodes == null || bindingsNodes.getLength() == 0 ) { - System.out.println( "missing <binding-nodes> in " + oxmFile ); - return null; - } - - bindingElement = (Element) bindingsNodes.item(0); - javaTypesNodes = bindingElement.getElementsByTagName("java-types"); - if ( javaTypesNodes.getLength() < 1 ) { - System.out.println( "missing <binding-nodes><java-types> in " + oxmFile ); - return null; - } - javaTypesElement = (Element) javaTypesNodes.item(0); - - javaTypeNodes = javaTypesElement.getElementsByTagName("java-type"); - if ( javaTypeNodes.getLength() < 1 ) { - System.out.println( "missing <binding-nodes><java-types><java-type> in " + oxmFile ); - return null; - } - - String javaTypeName; - String attrName, attrValue; - Attr attr; - StringBuffer pathSb = new StringBuffer(); - - StringBuffer definitionsSb = new StringBuffer("definitions:\n"); - - for ( int i = 0; i < javaTypeNodes.getLength(); ++ i ) { - javaTypeElement = (Element) javaTypeNodes.item(i); - NamedNodeMap attributes = javaTypeElement.getAttributes(); - javaTypeName = null; - for ( int j = 0; j < attributes.getLength(); ++j ) { - attr = (Attr) attributes.item(j); - attrName = attr.getNodeName(); - attrValue = attr.getNodeValue(); - if ( attrName.equals("name")) - javaTypeName = attrValue; - } - if ( javaTypeName == null ) { - System.out.println( "<java-type> has no name attribute in " + oxmFile ); - return null; - } - if ( !generatedJavaType.containsKey(getXmlRootElementName(javaTypeName)) ) { - - //generatedJavaType.put(javaTypeName, null); - //if ( javaTypeName.equals("search")||javaTypeName.equals("actions")) - - processJavaTypeElementSwagger( javaTypeName, javaTypeElement, pathSb, - definitionsSb, null, null, null, null, null, null, null); - } - } - sb.append(pathSb); - //System.out.println( "definitions block\n" + definitionsSb.toString()); - sb.append(definitionsSb.toString()); - //sb.append(definitionsSb); - - } catch (Exception e) { - e.printStackTrace(); - return null; - } - //System.out.println("generated " + sb.toString()); - return sb.toString(); - } - - private static NodeList locateXmlProperties(Element element) { - XPathExpression expr; - NodeList result = null; - try { - expr = xpath.compile("xml-properties"); - if (expr != null) { - Object nodeset = expr.evaluate(element, XPathConstants.NODESET); - if (nodeset != null) { - NodeList nodes = (NodeList) nodeset; - if (nodes.getLength() > 0) { - Element xmlProperty = (Element)nodes.item(0); - result = xmlProperty.getElementsByTagName("xml-property"); - } - } - } - } catch (XPathExpressionException e) { - e.printStackTrace(); - } - return result; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/HbaseSaltPrefixer.java b/aai-core/src/main/java/org/openecomp/aai/util/HbaseSaltPrefixer.java deleted file mode 100644 index ba1575c4..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/HbaseSaltPrefixer.java +++ /dev/null @@ -1,60 +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; - -/* - * logging to hbase encountered hotspotting issues, so per - * http://archive.cloudera.com/cdh5/cdh/5/hbase-0.98.6-cdh5.3.8/book/rowkey.design.html - * we decided to salt the rowkeys - * as these keys are generated in a couple places, I made a class to contain that logic - */ -public class HbaseSaltPrefixer { - private int NUM_REGION_BUCKETS = 3; //the number of hbase region servers per cluster - - private static class SingletonHolder{ - private static final HbaseSaltPrefixer INSTANCE = new HbaseSaltPrefixer(); - } - - /** - * Instantiates a new hbase salt prefixer. - */ - private HbaseSaltPrefixer(){} - - /** - * Gets the single instance of HbaseSaltPrefixer. - * - * @return single instance of HbaseSaltPrefixer - */ - public static HbaseSaltPrefixer getInstance() { - return SingletonHolder.INSTANCE; - } - - /** - * Prepend salt. - * - * @param key the key - * @return the string - */ - public String prependSalt(String key) { - int salt = Math.abs(key.hashCode()) % NUM_REGION_BUCKETS; - return salt + "-" + key; - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/HttpsAuthClient.java b/aai-core/src/main/java/org/openecomp/aai/util/HttpsAuthClient.java deleted file mode 100644 index 664620e2..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/HttpsAuthClient.java +++ /dev/null @@ -1,135 +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.io.FileInputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.config.ClientConfig; -import com.sun.jersey.api.client.config.DefaultClientConfig; -import com.sun.jersey.api.client.filter.LoggingFilter; -import com.sun.jersey.api.json.JSONConfiguration; -import com.sun.jersey.client.urlconnection.HTTPSProperties; - -public class HttpsAuthClient{ - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - try { - String url = AAIConfig.get(AAIConstants.AAI_SERVER_URL) + "business/customers"; - System.out.println("Making Jersey https call..."); - Client client = HttpsAuthClient.getClient(); - - ClientResponse res = client.resource(url) - .accept("application/json") - .header("X-TransactionId", "PROV001") - .header("X-FromAppId", "AAI") - .type("application/json") - .get(ClientResponse.class); - -// System.out.println("Jersey result: "); -// System.out.println(res.getEntity(String.class).toString()); - - } catch (KeyManagementException e) { - e.printStackTrace(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - - /** - * Gets the client. - * - * @return the client - * @throws KeyManagementException the key management exception - */ - public static Client getClient() throws KeyManagementException { - - ClientConfig config = new DefaultClientConfig(); - config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - config.getClasses().add(org.openecomp.aai.restcore.CustomJacksonJaxBJsonProvider.class); - - SSLContext ctx = null; - try { - String truststore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_FILENAME); - String truststore_password = AAIConfig.get(AAIConstants.AAI_TRUSTSTORE_PASSWD); - String keystore_path = AAIConstants.AAI_HOME_ETC_AUTH + AAIConfig.get(AAIConstants.AAI_KEYSTORE_FILENAME); - String keystore_password = AAIConfig.get(AAIConstants.AAI_KEYSTORE_PASSWD); - - System.setProperty("javax.net.ssl.trustStore", truststore_path); - System.setProperty("javax.net.ssl.trustStorePassword", truststore_password); - HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ - public boolean verify(String string,SSLSession ssls) { - return true; - } - }); - - ctx = SSLContext.getInstance("TLSv1.2"); - KeyManagerFactory kmf = null; - try { - kmf = KeyManagerFactory.getInstance("SunX509"); - FileInputStream fin = new FileInputStream(keystore_path); - KeyStore ks = KeyStore.getInstance("PKCS12"); - char[] pwd = keystore_password.toCharArray(); - ks.load(fin, pwd); - kmf.init(ks, pwd); - } catch (Exception e) { - System.out.println("Error setting up kmf: exiting"); - e.printStackTrace(); - System.exit(1); - } - - ctx.init(kmf.getKeyManagers(), null, null); - config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, - new HTTPSProperties( new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return true; - } - }, ctx)); - } catch (Exception e) { - System.out.println("Error setting up config: exiting"); - e.printStackTrace(); - System.exit(1); - } - - Client client = Client.create(config); - // uncomment this line to get more logging for the request/response - // client.addFilter(new LoggingFilter(System.out)); - - return client; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/KeyValueList.java b/aai-core/src/main/java/org/openecomp/aai/util/KeyValueList.java deleted file mode 100644 index 9628f99b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/KeyValueList.java +++ /dev/null @@ -1,138 +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.util.HashMap; -import java.util.Map; -import javax.annotation.Generated; -import com.fasterxml.jackson.annotation.JsonAnyGetter; -import com.fasterxml.jackson.annotation.JsonAnySetter; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; - -@JsonInclude(JsonInclude.Include.NON_NULL) -@Generated("org.jsonschema2pojo") -@JsonPropertyOrder({ - "key", - "value" -}) -public class KeyValueList { - - @JsonProperty("key") - private String key; - @JsonProperty("value") - private String value; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<String, Object>(); - - /** - * - * @return - * The key - */ - @JsonProperty("key") - public String getKey() { - return key; - } - - /** - * - * @param key - * The key - */ - @JsonProperty("key") - public void setKey(String key) { - this.key = key; - } - - public KeyValueList withKey(String key) { - this.key = key; - return this; - } - - /** - * - * @return - * The value - */ - @JsonProperty("value") - public String getValue() { - return value; - } - - /** - * - * @param value - * The value - */ - @JsonProperty("value") - public void setValue(String value) { - this.value = value; - } - - public KeyValueList withValue(String value) { - this.value = value; - return this; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this); - } - - @JsonAnyGetter - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - @JsonAnySetter - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - - public KeyValueList withAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - return this; - } - - @Override - public int hashCode() { - return new HashCodeBuilder().append(key).append(value).append(additionalProperties).toHashCode(); - } - - @Override - public boolean equals(Object other) { - if (other == this) { - return true; - } - if ((other instanceof KeyValueList) == false) { - return false; - } - KeyValueList rhs = ((KeyValueList) other); - return new EqualsBuilder().append(key, rhs.key).append(value, rhs.value).append(additionalProperties, rhs.additionalProperties).isEquals(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/MapperUtil.java b/aai-core/src/main/java/org/openecomp/aai/util/MapperUtil.java deleted file mode 100644 index 0579964d..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/MapperUtil.java +++ /dev/null @@ -1,115 +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 org.openecomp.aai.exceptions.AAIException; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; - -public class MapperUtil { - - - /** - * Read as object of. - * - * @param <T> the generic type - * @param clazz the clazz - * @param value the value - * @return the t - * @throws AAIException the AAI exception - */ - public static <T> T readAsObjectOf(Class<T> clazz, String value) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - return MAPPER.readValue(value, clazz); - } catch (Exception e) { - throw new AAIException("AAI_4007", e); - } - } - - /** - * Read with dashes as object of. - * - * @param <T> the generic type - * @param clazz the clazz - * @param value the value - * @return the t - * @throws AAIException the AAI exception - */ - public static <T> T readWithDashesAsObjectOf(Class<T> clazz, String value) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - MAPPER.registerModule(new JaxbAnnotationModule()); - MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - MAPPER.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); - - return MAPPER.readValue(value, clazz); - } catch (Exception e) { - throw new AAIException("AAI_4007", e); - } - } - - /** - * Write as JSON string. - * - * @param obj the obj - * @return the string - * @throws AAIException the AAI exception - */ - public static String writeAsJSONString(Object obj) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - String s = MAPPER.writeValueAsString(obj); - return s; - //readValue(value, clazz); - } catch (Exception e) { - throw new AAIException("AAI_4008", e); - } - } - - /** - * Write as JSON string with dashes. - * - * @param obj the obj - * @return the string - * @throws AAIException the AAI exception - */ - public static String writeAsJSONStringWithDashes(Object obj) throws AAIException { - com.fasterxml.jackson.databind.ObjectMapper MAPPER = new ObjectMapper(); - try { - MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); - - MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); - MAPPER.configure(SerializationFeature.INDENT_OUTPUT, false); - MAPPER.configure(SerializationFeature.WRAP_ROOT_VALUE, false); - - MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - MAPPER.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false); - - MAPPER.registerModule(new JaxbAnnotationModule()); - String s = MAPPER.writeValueAsString(obj); - return s; - } catch (Exception e) { - throw new AAIException("AAI_4008", e); - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java b/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java deleted file mode 100644 index 8840f412..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/PojoUtils.java +++ /dev/null @@ -1,82 +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.io.IOException; - -import org.apache.commons.io.output.ByteArrayOutputStream; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonGenerationException; -import com.fasterxml.jackson.databind.DeserializationFeature; -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; - -public class PojoUtils { - /** - * 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(); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/Request.java b/aai-core/src/main/java/org/openecomp/aai/util/Request.java deleted file mode 100644 index 327fab74..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/Request.java +++ /dev/null @@ -1,160 +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.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; - -import javax.ws.rs.core.UriBuilder; - -import org.openecomp.aai.exceptions.AAIException; - -public class Request<T> { - - public static final String V2 = "v2"; - public static final String V3 = "v3"; - public static final String V4 = "v4"; - public static final String V5 = "v5"; - public final String fromAppId; - public final String transactionId; - public final String path; - public final RestObject<T> restObj; - public final boolean oldServer; - public final String apiVersion; - - - /** - * Instantiates a new request. - * - * @param builder the builder - */ - public Request(RequestBuilder<T> builder) { - - fromAppId = builder.fromAppId; - transactionId = builder.transactionId; - restObj = builder.restObj; - oldServer = builder.oldServer; - apiVersion = builder.apiVersion; - - if (!oldServer) { - path = apiVersion + "/" + builder.path; - } else { - path = builder.path; - } - - - } - - public static class RequestBuilder<T> { - private String fromAppId; - private String transactionId; - private String path; - private RestObject<T> restObj; - private boolean oldServer; - private String apiVersion = Request.V4; - - - /** - * Sets the from app id. - * - * @param fromAppId the from app id - * @return the request builder - */ - public RequestBuilder<T> setFromAppId(String fromAppId) { - this.fromAppId = fromAppId; - return this; - } - - /** - * Sets the transaction id. - * - * @param transactionId the transaction id - * @return the request builder - */ - public RequestBuilder<T> setTransactionId(String transactionId) { - this.transactionId = transactionId; - return this; - - } - - /** - * Sets the path. - * - * @param path the path - * @return the request builder - */ - public RequestBuilder<T> setPath(String path) { - - this.path = path; - return this; - - } - - /** - * Sets the restcore obj. - * - * @param restObj the restcore obj - * @return the request builder - */ - public RequestBuilder<T> setRestObj(RestObject<T> restObj) { - this.restObj = restObj; - return this; - - } - - /** - * Sets the old server. - * - * @param oldServer the old server - * @return the request builder - */ - public RequestBuilder<T> setOldServer(boolean oldServer) { - this.oldServer = oldServer; - return this; - - } - - /** - * Sets the api version. - * - * @param apiVersion the api version - * @return the request builder - */ - public RequestBuilder<T> setApiVersion(String apiVersion) { - this.apiVersion = apiVersion; - return this; - } - - /** - * Builds the. - * - * @return the request - */ - public Request<T> build() { - return new Request<T>(this); - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/RestObject.java b/aai-core/src/main/java/org/openecomp/aai/util/RestObject.java deleted file mode 100644 index a1cc2a14..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/RestObject.java +++ /dev/null @@ -1,46 +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; - -public class RestObject<T> { - - /** - * Generic version of the RestObject class. - * @param <T> the type of the value being called for the Rest object interface - */ - // T stands for "Type" - private T t; - - /** - * Sets the. - * - * @param t the t - */ - public void set(T t) { this.t = t; } - - /** - * Gets the. - * - * @return the t - */ - public T get() { return t; } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/RestURLEncoder.java b/aai-core/src/main/java/org/openecomp/aai/util/RestURLEncoder.java deleted file mode 100644 index 46a1f48e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/RestURLEncoder.java +++ /dev/null @@ -1,41 +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.io.UnsupportedEncodingException; -import org.springframework.web.util.UriUtils; - - -public class RestURLEncoder { - - - /** - * Encode URL. - * - * @param nodeKey the node key - * @return the string - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - public static final String encodeURL (String nodeKey) throws UnsupportedEncodingException { - return UriUtils.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20"); - } -} - diff --git a/aai-core/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java b/aai-core/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java deleted file mode 100644 index 29fa69dc..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/StoreNotificationEvent.java +++ /dev/null @@ -1,336 +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.io.StringWriter; -import java.util.Iterator; -import java.util.UUID; - -import javax.xml.bind.Marshaller; - -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; -import org.openecomp.aai.introspection.Introspector; -import org.openecomp.aai.introspection.Loader; -import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; - -public class StoreNotificationEvent { - - private AAIDmaapEventJMSProducer messageProducer; - private String fromAppId = ""; - private String transId = ""; - private final String transactionId; - private final String sourceOfTruth; - /** - * Instantiates a new store notification event. - */ - public StoreNotificationEvent(String transactionId, String sourceOfTruth) { - this.messageProducer = new AAIDmaapEventJMSProducer(); - this.transactionId = transactionId; - this.sourceOfTruth = sourceOfTruth; - } - - /** - * Store event. - * - * @param eh - * the eh - * @param obj - * the obj - * @throws AAIException - * the AAI exception - */ - public void storeEvent(NotificationEvent.EventHeader eh, Object obj) throws AAIException { - - if (obj == null) { - throw new AAIException("AAI_7350"); - } - - org.openecomp.aai.domain.notificationEvent.ObjectFactory factory = new org.openecomp.aai.domain.notificationEvent.ObjectFactory(); - - org.openecomp.aai.domain.notificationEvent.NotificationEvent ne = factory.createNotificationEvent(); - - if (eh.getId() == null) { - eh.setId(genDate2() + "-" + UUID.randomUUID().toString()); - } - if (eh.getTimestamp() == null) { - eh.setTimestamp(genDate()); - } - - // there's no default, but i think we want to put this in hbase? - - if (eh.getEntityLink() == null) { - eh.setEntityLink("UNK"); - } - - if (eh.getAction() == null) { - eh.setAction("UNK"); - } - - if (eh.getEventType() == null) { - eh.setEventType(AAIConfig.get("aai.notificationEvent.default.eventType", "UNK")); - } - - if (eh.getDomain() == null) { - eh.setDomain(AAIConfig.get("aai.notificationEvent.default.domain", "UNK")); - } - - if (eh.getSourceName() == null) { - eh.setSourceName(AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK")); - } - - if (eh.getSequenceNumber() == null) { - eh.setSequenceNumber(AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK")); - } - - if (eh.getSeverity() == null) { - eh.setSeverity(AAIConfig.get("aai.notificationEvent.default.severity", "UNK")); - } - - if (eh.getVersion() == null) { - eh.setVersion(AAIConfig.get("aai.notificationEvent.default.version", "UNK")); - } - - ne.setCambriaPartition(AAIConstants.UEB_PUB_PARTITION_AAI); - ne.setEventHeader(eh); - ne.setEntity(obj); - - try { - PojoUtils pu = new PojoUtils(); - String entityJson = pu.getJsonFromObject(ne); - sendToDmaapJmsQueue(entityJson); - } catch (Exception e) { - throw new AAIException("AAI_7350", e); - } - } - - /** - * Store dynamic event. - * - * @param notificationJaxbContext - * the notification jaxb context - * @param notificationVersion - * the notification version - * @param eventHeader - * the event header - * @param obj - * the obj - * @throws AAIException - * the AAI exception - */ - public void storeDynamicEvent(DynamicJAXBContext notificationJaxbContext, String notificationVersion, DynamicEntity eventHeader, DynamicEntity obj) throws AAIException { - - if (obj == null) { - throw new AAIException("AAI_7350"); - } - - DynamicEntity notificationEvent = notificationJaxbContext.getDynamicType("inventory.aai.onap.org." + notificationVersion + ".NotificationEvent").newDynamicEntity(); - - if (eventHeader.get("id") == null) { - eventHeader.set("id", genDate2() + "-" + UUID.randomUUID().toString()); - } - - if (eventHeader.get("timestamp") == null) { - eventHeader.set("timestamp", genDate()); - } - - if (eventHeader.get("entityLink") == null) { - eventHeader.set("entityLink", "UNK"); - } - - if (eventHeader.get("action") == null) { - eventHeader.set("action", "UNK"); - } - - if (eventHeader.get("eventType") == null) { - eventHeader.set("eventType", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK")); - } - - if (eventHeader.get("domain") == null) { - eventHeader.set("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK")); - } - - if (eventHeader.get("sourceName") == null) { - eventHeader.set("sourceName", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK")); - } - - if (eventHeader.get("sequenceNumber") == null) { - eventHeader.set("sequenceNumber", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK")); - } - - if (eventHeader.get("severity") == null) { - eventHeader.set("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK")); - } - - if (eventHeader.get("version") == null) { - eventHeader.set("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK")); - } - - if (notificationEvent.get("cambriaPartition") == null) { - notificationEvent.set("cambriaPartition", AAIConstants.UEB_PUB_PARTITION_AAI); - } - - notificationEvent.set("eventHeader", eventHeader); - notificationEvent.set("entity", obj); - - try { - StringWriter result = new StringWriter(); - - Marshaller marshaller = notificationJaxbContext.createMarshaller(); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json"); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_INCLUDE_ROOT, false); - marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, false); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false); - marshaller.marshal(notificationEvent, result); - - this.sendToDmaapJmsQueue(result.toString()); - - } catch (Exception e) { - throw new AAIException("AAI_7350", e); - } - } - - public void storeEvent(Loader loader, Introspector eventHeader, Introspector obj) throws AAIException { - if (obj == null) { - throw new AAIException("AAI_7350"); - } - - try { - final Introspector notificationEvent = loader.introspectorFromName("notification-event"); - - if (eventHeader.getValue("id") == null) { - eventHeader.setValue("id", genDate2() + "-" + UUID.randomUUID().toString()); - } - - if (eventHeader.getValue("timestamp") == null) { - eventHeader.setValue("timestamp", genDate()); - } - - if (eventHeader.getValue("entity-link") == null) { - eventHeader.setValue("entity-link", "UNK"); - } - - if (eventHeader.getValue("action") == null) { - eventHeader.setValue("action", "UNK"); - } - - if (eventHeader.getValue("event-type") == null) { - eventHeader.setValue("event-type", AAIConfig.get("aai.notificationEvent.default.eventType", "UNK")); - } - - if (eventHeader.getValue("domain") == null) { - eventHeader.setValue("domain", AAIConfig.get("aai.notificationEvent.default.domain", "UNK")); - } - - if (eventHeader.getValue("source-name") == null) { - eventHeader.setValue("source-name", AAIConfig.get("aai.notificationEvent.default.sourceName", "UNK")); - } - - if (eventHeader.getValue("sequence-number") == null) { - eventHeader.setValue("sequence-number", AAIConfig.get("aai.notificationEvent.default.sequenceNumber", "UNK")); - } - - if (eventHeader.getValue("severity") == null) { - eventHeader.setValue("severity", AAIConfig.get("aai.notificationEvent.default.severity", "UNK")); - } - - if (eventHeader.getValue("version") == null) { - eventHeader.setValue("version", AAIConfig.get("aai.notificationEvent.default.version", "UNK")); - } - - if (notificationEvent.getValue("cambria-partition") == null) { - notificationEvent.setValue("cambria-partition", AAIConstants.UEB_PUB_PARTITION_AAI); - } - - notificationEvent.setValue("event-header", eventHeader.getUnderlyingObject()); - notificationEvent.setValue("entity", obj.getUnderlyingObject()); - - String entityJson = notificationEvent.marshal(false); - sendToDmaapJmsQueue(entityJson); - } catch (JSONException e) { - throw new AAIException("AAI_7350", e); - } catch (AAIUnknownObjectException e) { - throw new AAIException("AAI_7350", e); - } - } - - private void sendToDmaapJmsQueue(String entityString) throws JSONException { - - JSONObject entityJsonObject = new JSONObject(entityString); - - JSONObject entityJsonObjectUpdated = new JSONObject(); - JSONObject finalJson = new JSONObject(); - - JSONObject entityHeader = entityJsonObject.getJSONObject("event-header"); - String cambriaPartition = entityJsonObject.getString("cambria.partition"); - - entityJsonObject.remove("event-header"); - entityJsonObject.remove("cambria.partition"); - - 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()) { - entity = entityJsonObject.getJSONObject(iter.next()); - } - - entityJsonObjectUpdated.put("entity", entity); - - finalJson.put("event-topic", "AAI-EVENT"); - finalJson.put("transId", transId); - finalJson.put("fromAppId", fromAppId); - finalJson.put("fullId", ""); - finalJson.put("aaiEventPayload", entityJsonObjectUpdated); - - messageProducer.sendMessageToDefaultDestination(finalJson); - } - - /** - * Gen date. - * - * @return the string - */ - public static String genDate() { - FormatDate fd = new FormatDate("YYYYMMdd-HH:mm:ss:SSS"); - return fd.getDateTime(); - } - - /** - * Gen date 2. - * - * @return the string - */ - public static String genDate2() { - FormatDate fd = new FormatDate("YYYYMMddHHmmss"); - return fd.getDateTime(); - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/UniquePropertyCheck.java b/aai-core/src/main/java/org/openecomp/aai/util/UniquePropertyCheck.java deleted file mode 100644 index a2b77506..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/UniquePropertyCheck.java +++ /dev/null @@ -1,267 +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.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; - -import org.apache.tinkerpop.gremlin.structure.Direction; -import org.apache.tinkerpop.gremlin.structure.Edge; -import org.apache.tinkerpop.gremlin.structure.Graph; -import org.apache.tinkerpop.gremlin.structure.Vertex; -import org.apache.tinkerpop.gremlin.structure.VertexProperty; -import org.openecomp.aai.exceptions.AAIException; -import org.slf4j.MDC; - -import com.att.eelf.configuration.Configuration; -import com.att.eelf.configuration.EELFLogger; -import com.att.eelf.configuration.EELFManager; -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; - - - -public class UniquePropertyCheck { - - - private static final String FROMAPPID = "AAI-UTILS"; - private static final String TRANSID = UUID.randomUUID().toString(); - private static final String COMPONENT = "UniquePropertyCheck"; - - /** - * The main method. - * - * @param args the arguments - */ - public static void main(String[] args) { - - - Properties props = System.getProperties(); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_NAME, "uniquePropertyCheck-logback.xml"); - props.setProperty(Configuration.PROPERTY_LOGGING_FILE_PATH, AAIConstants.AAI_HOME_ETC_APP_PROPERTIES); - EELFLogger logger = EELFManager.getInstance().getLogger(UniquePropertyCheck.class.getSimpleName()); - MDC.put("logFilenameAppender", UniquePropertyCheck.class.getSimpleName()); - - if( args == null || args.length != 1 ){ - String msg = "usage: UniquePropertyCheck propertyName \n"; - System.out.println(msg); - logAndPrint(logger, msg ); - System.exit(1); - } - String propertyName = args[0]; - Graph graph = null; - - try { - AAIConfig.init(); - System.out.println(" ---- NOTE --- about to open graph (takes a little while)--------\n"); - TitanGraph tGraph = TitanFactory.open(AAIConstants.REALTIME_DB_CONFIG); - - if( tGraph == null ) { - logAndPrint(logger, " Error: Could not get TitanGraph "); - System.exit(1); - } - - graph = tGraph.newTransaction(); - if( graph == null ){ - logAndPrint(logger, "could not get graph object in UniquePropertyCheck() \n"); - System.exit(0); - } - } - catch (AAIException e1) { - String msg = "Threw Exception: [" + e1.toString() + "]"; - logAndPrint(logger, msg); - System.exit(0); - } - catch (Exception e2) { - String msg = "Threw Exception: [" + e2.toString() + "]"; - logAndPrint(logger, msg); - System.exit(0); - } - - runTheCheckForUniqueness( TRANSID, FROMAPPID, graph, propertyName, logger ); - System.exit(0); - - }// End main() - - - /** - * Run the check for uniqueness. - * - * @param transId the trans id - * @param fromAppId the from app id - * @param graph the graph - * @param propertyName the property name - * @param logger the logger - * @return the boolean - */ - public static Boolean runTheCheckForUniqueness( String transId, String fromAppId, Graph graph, - String propertyName, EELFLogger logger ){ - - // Note - property can be found in more than one nodetype - // our uniqueness constraints are always across the entire db - so this - // tool looks across all nodeTypes that the property is found in. - Boolean foundDupesFlag = false; - - HashMap <String,String> valuesAndVidHash = new HashMap <String, String> (); - HashMap <String,String> dupeHash = new HashMap <String, String> (); - - int propCount = 0; - int dupeCount = 0; - Iterator<Vertex> vertItor = graph.traversal().V().has(propertyName); - while( vertItor.hasNext() ){ - propCount++; - Vertex v = vertItor.next(); - String thisVid = v.id().toString(); - Object val = (v.<Object>property(propertyName)).orElse(null); - if( valuesAndVidHash.containsKey(val) ){ - // We've seen this one before- track it in our dupe hash - dupeCount++; - if( dupeHash.containsKey(val) ){ - // This is not the first one being added to the dupe hash for this value - String updatedDupeList = dupeHash.get(val) + "|" + thisVid; - dupeHash.put(val.toString(), updatedDupeList); - } - else { - // This is the first time we see this value repeating - String firstTwoVids = valuesAndVidHash.get(val) + "|" + thisVid; - dupeHash.put(val.toString(), firstTwoVids); - } - } - else { - valuesAndVidHash.put(val.toString(), thisVid); - } - } - - - String info = "\n Found this property [" + propertyName + "] " + propCount + " times in our db."; - logAndPrint(logger, info); - info = " Found " + dupeCount + " cases of duplicate values for this property.\n\n"; - logAndPrint(logger, info); - - try { - if( ! dupeHash.isEmpty() ){ - Iterator <?> dupeItr = dupeHash.entrySet().iterator(); - while( dupeItr.hasNext() ){ - Map.Entry pair = (Map.Entry) dupeItr.next(); - String dupeValue = pair.getKey().toString();; - String vidsStr = pair.getValue().toString(); - String[] vidArr = vidsStr.split("\\|"); - logAndPrint(logger, "\n\n -------------- Found " + vidArr.length - + " nodes with " + propertyName + " of this value: [" + dupeValue + "]. Node details: "); - - for( int i = 0; i < vidArr.length; i++ ){ - String vidString = vidArr[i]; - Long idLong = Long.valueOf(vidString); - Vertex tvx = graph.traversal().V(idLong).next(); - showPropertiesAndEdges( TRANSID, FROMAPPID, tvx, logger ); - } - } - } - } - catch( Exception e2 ){ - logAndPrint(logger, "Threw Exception: [" + e2.toString() + "]"); - } - finally { - if( graph != null ){ - graph.tx().rollback(); - } - } - - return foundDupesFlag; - - }// end of runTheCheckForUniqueness() - - - /** - * 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, Vertex tVert, - EELFLogger logger ){ - - if( tVert == null ){ - logAndPrint(logger, "Null node passed to showPropertiesAndEdges."); - } - else { - String nodeType = ""; - Object ob = tVert.<String>property("aai-node-type").orElse(null); - 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() ){ - Edge ed = eI.next(); - String lab = ed.label(); - Vertex vtx; - if (tVert.equals(ed.inVertex())) { - vtx = ed.outVertex(); - } else { - vtx = ed.inVertex(); - } - 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-core/src/main/java/org/openecomp/aai/util/swagger/Api.java b/aai-core/src/main/java/org/openecomp/aai/util/swagger/Api.java deleted file mode 100644 index 241be43a..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/swagger/Api.java +++ /dev/null @@ -1,310 +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.swagger; - -import java.util.List; -import java.util.Map; - -public class Api { - - private String path; - - private List<HttpVerb> httpMethods; - - private String tag; - - public List<HttpVerb> getHttpMethods() { - return httpMethods; - } - - public void setHttpMethods(List<HttpVerb> httpMethods) { - this.httpMethods = httpMethods; - } - - public String getTag(){ - - if(this.tag != null){ - return this.tag; - } - - if(this.httpMethods != null){ - if(this.httpMethods.size() != 0){ - if(this.httpMethods.get(0).getTags() != null){ - if(this.httpMethods.get(0).getTags().size() != 0){ - this.tag = this.httpMethods.get(0).getTags().get(0); - } - } - } - } - - if(this.tag == null){ - this.tag = ""; - } - - return this.tag; - } - - @Override - public String toString() { - return "Api{" + - "path='" + path + '\'' + - ", httpMethods=" + httpMethods + - '}'; - } - - public void setPath(String path) { - this.path = path; - } - - public String getPath() { - return this.path; - } - - public String getOperation(){ - - if(this.path != null){ - return this.path.replaceAll("[^a-zA-Z0-9\\-]", "-") + "-"; - } - - return ""; - } - - public static class HttpVerb { - - private List<String> tags; - - private String type; - - private String summary; - - private String operationId; - - private List<String> consumes; - - private boolean consumerEnabled; - - private List<String> produces; - - private List<Response> responses; - - private List<Map<String, Object>> parameters; - - private Map<String, Object> bodyParameters; - - private boolean bodyParametersEnabled; - - private boolean parametersEnabled; - - private String schemaLink; - - private String schemaType; - - private boolean hasReturnSchema; - - private String returnSchemaLink; - - private String returnSchemaObject; - - public void setConsumerEnabled(boolean consumerEnabled){ - this.consumerEnabled = consumerEnabled; - } - - public boolean isConsumerEnabled() { - return consumerEnabled; - } - - - public List<String> getTags() { - return tags; - } - - public void setTags(List<String> tags) { - this.tags = tags; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getSummary() { - return summary; - } - - public void setSummary(String summary) { - this.summary = summary; - } - - public String getOperationId() { - return operationId; - } - - public void setOperationId(String operationId) { - this.operationId = operationId; - } - - public List<String> getConsumes() { - return consumes; - } - - public void setConsumes(List<String> consumes) { - this.consumes = consumes; - } - - public List<String> getProduces() { - return produces; - } - - public void setProduces(List<String> produces) { - this.produces = produces; - } - - public List<Response> getResponses() { - return responses; - } - - public void setResponses(List<Response> responses) { - this.responses = responses; - } - - public List<Map<String, Object>> getParameters() { - return parameters; - } - - public void setParameters(List<Map<String, Object>> parameters) { - this.parameters = parameters; - } - - @Override - public String toString() { - return "HttpVerb{" + - "tags=" + tags + - ", type='" + type + '\'' + - ", summary='" + summary + '\'' + - ", operationId='" + operationId + '\'' + - ", consumes=" + consumes + - ", produces=" + produces + - ", responses=" + responses + - ", parameters=" + parameters + - '}'; - } - - public void setParametersEnabled(boolean b) { - this.parametersEnabled = b; - } - - public boolean isParametersEnabled() { - return parametersEnabled; - } - - public boolean isBodyParametersEnabled() { - return bodyParametersEnabled; - } - - public void setBodyParametersEnabled(boolean bodyParametersEnabled) { - this.bodyParametersEnabled = bodyParametersEnabled; - } - - public Map<String, Object> getBodyParameters() { - return bodyParameters; - } - - public void setBodyParameters(Map<String, Object> bodyParameters) { - this.bodyParameters = bodyParameters; - } - - public String getSchemaLink() { - return schemaLink; - } - - public void setSchemaLink(String schemaLink) { - this.schemaLink = schemaLink; - } - - public String getSchemaType() { - return schemaType; - } - - public void setSchemaType(String schemaType) { - this.schemaType = schemaType; - } - - public boolean isHasReturnSchema() { - return hasReturnSchema; - } - - public void setHasReturnSchema(boolean hasReturnSchema) { - this.hasReturnSchema = hasReturnSchema; - } - - public String getReturnSchemaLink() { - return returnSchemaLink; - } - - public void setReturnSchemaLink(String returnSchemaLink) { - this.returnSchemaLink = returnSchemaLink; - } - - public String getReturnSchemaObject() { - return returnSchemaObject; - } - - public void setReturnSchemaObject(String returnSchemaObject) { - this.returnSchemaObject = returnSchemaObject; - } - - public static class Response { - - private String responseCode; - - private String description; - - public String getResponseCode() { - return responseCode; - } - - public void setResponseCode(String responseCode) { - this.responseCode = responseCode; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - return "Response{" + - "responseCode='" + responseCode + '\'' + - ", description='" + description + '\'' + - '}'; - } - } - - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/swagger/Definition.java b/aai-core/src/main/java/org/openecomp/aai/util/swagger/Definition.java deleted file mode 100644 index 31c38c56..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/swagger/Definition.java +++ /dev/null @@ -1,199 +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.swagger; - -import java.util.List; - -public class Definition { - - private String definitionName; - - private String definitionDescription; - - private List<Property> propertyList; - - private List<Property> schemaPropertyList; - - private List<Property> regularPropertyList; - - private boolean hasDescription; - - public String getDefinitionName() { - return definitionName; - } - - public void setDefinitionName(String definitionName) { - this.definitionName = definitionName; - } - - public List<Property> getPropertyList() { - return propertyList; - } - - public void setPropertyList(List<Property> propertyList) { - this.propertyList = propertyList; - } - - public String getDefinitionDescription() { - return definitionDescription; - } - - public void setDefinitionDescription(String definitionDescription) { - this.definitionDescription = definitionDescription; - } - - @Override - public String toString() { - return "Definition{" + - "definitionName='" + definitionName + '\'' + - ", definitionDescription='" + definitionDescription + '\'' + - ", propertyList=" + propertyList + - '}'; - } - - public boolean isHasDescription() { - return hasDescription; - } - - public void setHasDescription(boolean hasDescription) { - this.hasDescription = hasDescription; - } - - public List<Property> getSchemaPropertyList() { - return schemaPropertyList; - } - - public void setSchemaPropertyList(List<Property> schemaPropertyList) { - this.schemaPropertyList = schemaPropertyList; - } - - public List<Property> getRegularPropertyList() { - return regularPropertyList; - } - - public void setRegularPropertyList(List<Property> regularPropertyList) { - this.regularPropertyList = regularPropertyList; - } - - public static class Property { - - private String propertyName; - - private String propertyDescription; - - private boolean hasPropertyDescription; - - private String propertyType; - - private boolean hasType; - - private String propertyReference; - - private String propertyReferenceObjectName; - - private boolean isRequired; - - private boolean hasPropertyReference; - - public Property(){} - - public String getPropertyName() { - return propertyName; - } - - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - public String getPropertyType() { - return propertyType; - } - - public void setPropertyType(String propertyType) { - this.propertyType = propertyType; - } - - public String getPropertyReference() { - return propertyReference; - } - - public void setPropertyReference(String propertyReference) { - this.propertyReference = propertyReference; - } - - @Override - public String toString() { - return "Property{" + - "propertyName='" + propertyName + '\'' + - ", propertyType='" + propertyType + '\'' + - ", propertyReference='" + propertyReference + '\'' + - '}'; - } - - public boolean isHasType() { - return hasType; - } - - public void setHasType(boolean hasType) { - this.hasType = hasType; - } - - public boolean isRequired() { - return isRequired; - } - - public void setRequired(boolean required) { - isRequired = required; - } - - public boolean isHasPropertyReference() { - return hasPropertyReference; - } - - public void setHasPropertyReference(boolean hasPropertyReference) { - this.hasPropertyReference = hasPropertyReference; - } - - public String getPropertyReferenceObjectName() { - return propertyReferenceObjectName; - } - - public void setPropertyReferenceObjectName(String propertyReferenceObjectName) { - this.propertyReferenceObjectName = propertyReferenceObjectName; - } - - public String getPropertyDescription() { - return propertyDescription; - } - - public void setPropertyDescription(String propertyDescription) { - this.propertyDescription = propertyDescription; - } - - public boolean isHasPropertyDescription() { - return hasPropertyDescription; - } - - public void setHasPropertyDescription(boolean hasPropertyDescription) { - this.hasPropertyDescription = hasPropertyDescription; - } - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/util/swagger/GenerateSwagger.java b/aai-core/src/main/java/org/openecomp/aai/util/swagger/GenerateSwagger.java deleted file mode 100644 index 5731485e..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/util/swagger/GenerateSwagger.java +++ /dev/null @@ -1,432 +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.swagger; - -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml; -import com.fasterxml.jackson.dataformat.yaml.snakeyaml.constructor.SafeConstructor; -import freemarker.template.Configuration; -import freemarker.template.Template; -import freemarker.template.TemplateException; - -import java.io.*; -import java.util.*; -import java.util.stream.Collectors; - -public class GenerateSwagger { - - public static final String LINE_SEPARATOR = System.getProperty("line.separator"); - public static final String DEFAULT_WIKI = ""; - - public static final String DEFAULT_SCHEMA_DIR = "../aai-schema"; - public static final String CURRENT_VERSION = "v11"; - - public static void main(String[] args) throws IOException, TemplateException { - - String schemaDir = System.getProperty("aai.schema.dir"); - String versionToGenerate = System.getProperty("aai.generate.version"); - String wikiLink = System.getProperty("aai.wiki.link"); - - if(schemaDir == null){ - System.out.println("Warning: Schema directory is not set so using default schema dir: " + DEFAULT_SCHEMA_DIR); - schemaDir = DEFAULT_SCHEMA_DIR; - } - - if(versionToGenerate == null){ - System.out.println("Warning: Version to generate is not set so using default version: " + CURRENT_VERSION); - versionToGenerate = CURRENT_VERSION; - } - - if(wikiLink == null){ - System.out.println("Warning: aai.wiki.link property is not set so using default"); - wikiLink = DEFAULT_WIKI; - } - - String yamlFile = schemaDir + "/src/main/resources/aai_swagger_yaml/aai_swagger_" + versionToGenerate + ".yaml"; - File swaggerYamlFile = new File(yamlFile); - - if(!swaggerYamlFile.exists()){ - System.err.println("Unable to find the swagger yaml file: " + swaggerYamlFile); - System.exit(1); - } - - Yaml yaml = new Yaml(new SafeConstructor()); - Map<String, Object> swaggerMap = null; - - try (BufferedReader reader = new BufferedReader(new FileReader(swaggerYamlFile))){ - swaggerMap = (Map<String, Object>) yaml.load(reader); - } catch(IOException ex){ - ex.printStackTrace(); - } - - if(null == swaggerMap) { - throw new IOException(); - } - - Map<String, Object> map = (Map<String, Object>) swaggerMap.get("paths"); - Map<String, Object> schemaDefinitionmap = (Map<String, Object>) swaggerMap.get("definitions"); - Map<String, Object> infoMap = (Map<String, Object>) swaggerMap.get("info"); - Map<String, List<Api>> tagMap = new LinkedHashMap<>(); - - List<Api> apis = convertToApi(map); - apis.forEach((api) -> { - if(!tagMap.containsKey(api.getTag())){ - List<Api> newApis = new ArrayList<>(); - newApis.add(api); - tagMap.put(api.getTag(), newApis); - } else { - tagMap.get(api.getTag()).add(api); - } - }); - - Map<String, List<Api>> sortedTagMap = new TreeMap<>(tagMap); - sortedTagMap.forEach((key, value) -> { - value.sort(Comparator.comparing(Api::getPath)); - }); - - Map<String, Object> resultMap = new HashMap<>(); - - List<Definition> definitionList = convertToDefinition(schemaDefinitionmap); - - definitionList = definitionList - .stream().sorted(Comparator.comparing(Definition::getDefinitionName)).collect(Collectors.toList()); - - resultMap.put("aaiApis", tagMap); - resultMap.put("sortedAaiApis", sortedTagMap); - resultMap.put("wikiLink", wikiLink); - resultMap.put("definitions", definitionList); - if (infoMap.containsKey("description")) { - String infoDescription = infoMap.get("description").toString(); - - infoDescription = Arrays.stream(infoDescription.split("\n")) - .map(line -> { - line = line.trim(); - String hyperLink = ""; - if(line.trim().contains("https://")){ - int startIndex = line.indexOf("https://"); - int endIndex = line.lastIndexOf("/"); - hyperLink = line.substring(startIndex, endIndex); - return String.format("<a href=\"%s\">%s</a><br/>", hyperLink, line); - } - return String.format("%s<br/>", line); - }) - - .collect(Collectors.joining(LINE_SEPARATOR)); - - resultMap.put("description", infoDescription); - } - - Configuration configuration = new Configuration(); - configuration.setClassForTemplateLoading(Api.class, "/"); - configuration.setDirectoryForTemplateLoading(new File("src/main/resources/")); - - Template template = configuration.getTemplate("swagger.html.ftl"); - - String outputDirStr = schemaDir + "/src/main/resources/aai_swagger_html"; - - File outputDir = new File(outputDirStr); - - if(!outputDir.exists()){ - boolean resp = outputDir.mkdir(); - if(!resp){ - System.err.println("Unable to create the directory: " + outputDirStr); - System.exit(1); - } - } else if(outputDir.isFile()){ - System.err.println("Unable to create the directory: " + outputDirStr + " since a filename with that string exists"); - System.exit(1); - } - - Writer file = new FileWriter(new File(outputDirStr + "/aai_swagger_" + versionToGenerate + ".html")); - template.process(resultMap, file); - } - - public static List<Api> convertToApi(Map<String, Object> pathMap){ - - if(pathMap == null) - throw new IllegalArgumentException(); - - List<Api> apis = new ArrayList<>(); - - pathMap.forEach( (pathKey, pathValue) -> { - - Api api = new Api(); - Map<String, Object> httpVerbMap = (Map<String, Object>) pathValue; - List<Api.HttpVerb> httpVerbs = new ArrayList<>(); - - api.setPath(pathKey); - - httpVerbMap.forEach((httpVerbKey, httpVerbValue) -> { - - Api.HttpVerb httpVerb = new Api.HttpVerb(); - - Map<String, Object> httpVerbValueMap = (Map<String,Object>)httpVerbValue; - - httpVerb.setType(httpVerbKey); - - if(httpVerbValueMap.containsKey("tags")){ - httpVerb.setTags((List<String>)httpVerbValueMap.get("tags")); - } - - if(httpVerbValueMap.containsKey("summary")){ - httpVerb.setSummary((String)httpVerbValueMap.get("summary")); - } - - if(httpVerbValueMap.containsKey("operationId")){ - httpVerb.setOperationId((String)httpVerbValueMap.get("operationId")); - } - - if(httpVerbValueMap.containsKey("consumes")){ - httpVerb.setConsumes((List<String>)httpVerbValueMap.get("consumes")); - if(httpVerb.getConsumes() != null){ - httpVerb.setConsumerEnabled(true); - } - } - - if(httpVerbValueMap.containsKey("produces")){ - httpVerb.setProduces((List<String>)httpVerbValueMap.get("produces")); - } - - if(httpVerbValueMap.containsKey("parameters")){ - List<Map<String, Object>> parameters = (List<Map<String, Object>>) httpVerbValueMap.get("parameters"); - List<Map<String, Object>> requestParameters = parameters - .stream() - .filter((parameter) -> !parameter.get("name").equals("body")) - .collect(Collectors.toList()); - httpVerb.setParameters(requestParameters); - if(httpVerb.getParameters() != null){ - httpVerb.setParametersEnabled(true); - } - - List<Map<String, Object>> requestBodyList = parameters - .stream() - .filter((parameter) -> parameter.get("name").equals("body")) - .collect(Collectors.toList()); - - Map<String, Object> requestBody = null; - - if(requestBodyList != null && requestBodyList.size() == 1){ - requestBody = requestBodyList.get(0); - httpVerb.setBodyParametersEnabled(true); - httpVerb.setBodyParameters(requestBody); - - if(requestBody != null && requestBody.containsKey("schema")){ - Map<String, Object> schemaMap = (Map<String, Object>)requestBody.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ - String schemaLink = schemaMap.get("$ref").toString(); - httpVerb.setSchemaLink(schemaLink); - int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ - httpVerb.setSchemaType(schemaLink.substring(retCode)); - } - } - } - } - } - - if(httpVerbValueMap.containsKey("responses")){ - - List<Api.HttpVerb.Response> responses = new ArrayList<Api.HttpVerb.Response>(); - - Map<String, Object> responsesMap = (Map<String, Object>) httpVerbValueMap.get("responses"); - - responsesMap - .entrySet() - .stream() - .filter((res) -> !"default".equalsIgnoreCase(res.getKey())) - .forEach((responseMap) -> { - - Map<String, Object> responseValueMap = (Map<String, Object>)responseMap.getValue(); - - Api.HttpVerb.Response response = new Api.HttpVerb.Response(); - - response.setResponseCode(responseMap.getKey()); - response.setDescription((String) responseValueMap.get("description")); - - if(responseValueMap != null && responseValueMap.containsKey("schema")){ - Map<String, Object> schemaMap = (Map<String, Object>)responseValueMap.get("schema"); - if(schemaMap != null && schemaMap.containsKey("$ref")){ - String schemaLink = schemaMap.get("$ref").toString(); - httpVerb.setHasReturnSchema(true); - httpVerb.setReturnSchemaLink(schemaLink); - int retCode = schemaLink.lastIndexOf('/'); - if(retCode != -1 && retCode != schemaLink.length()){ - httpVerb.setReturnSchemaObject(schemaLink.substring(retCode)); - } - } - } - - responses.add(response); - } - ); - - httpVerb.setResponses(responses); - } - - httpVerbs.add(httpVerb); - }); - - api.setHttpMethods(httpVerbs); - apis.add(api); - }); - - return apis; - } - - public static List<Definition> convertToDefinition(Map<String, Object> definitionMap) { - - if(definitionMap == null) - throw new IllegalArgumentException(); - - List<Definition> defintionsList = new ArrayList<>(); - - definitionMap - .entrySet() - .forEach((entry) -> { - - Definition definition = new Definition(); - String key = entry.getKey(); - Map<String, Object> valueMap = (Map<String, Object>) entry.getValue(); - - definition.setDefinitionName(key); - - if(valueMap.containsKey("description")){ - String description = valueMap.get("description").toString(); - description = formatDescription(description); - definition.setDefinitionDescription(description); - definition.setHasDescription(true); - } - - List<Definition.Property> definitionProperties = new ArrayList<>(); - - List<String> requiredProperties = (valueMap.get("required") == null) ? new ArrayList<>() : (List<String>) valueMap.get("required"); - - Set<String> requiredPropsSet = requiredProperties.stream().collect(Collectors.toSet()); - - valueMap - .entrySet() - .stream() - .filter( (e) -> "properties".equals(e.getKey())) - .forEach((propertyEntries) -> { - Map<String, Object> propertyRealEntries = (Map<String, Object>) propertyEntries.getValue(); - propertyRealEntries - .entrySet() - .forEach((propertyEntry) -> { - Definition.Property definitionProperty = new Definition.Property(); - String propertyKey = propertyEntry.getKey(); - if(requiredPropsSet.contains(propertyKey)){ - definitionProperty.setRequired(true); - } - definitionProperty.setPropertyName(propertyKey); - Map<String, Object> definitionPropertyMap = (Map<String, Object>) propertyEntry.getValue(); - - if(definitionPropertyMap.containsKey("description")){ - definitionProperty.setPropertyDescription(definitionPropertyMap.get("description").toString()); - definitionProperty.setHasPropertyDescription(true); - } - if(definitionPropertyMap.containsKey("type")){ - String type = definitionPropertyMap.get("type").toString(); - definitionProperty.setPropertyType(type); - definitionProperty.setHasType(true); - if ("array".equals(type)) { - definitionProperty.setPropertyType("object[]"); - if(!definitionPropertyMap.containsKey("items")){ - throw new RuntimeException("Unable to find the property items even though the type is array for " + propertyEntry.getKey()); - } else { - Map<String, Object> itemMap = (Map<String, Object>) definitionPropertyMap.get("items"); - if(itemMap.containsKey("$ref")){ - definitionProperty.setHasPropertyReference(true); - String refItem = itemMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if(retCode != -1 && retCode != refItem.length()){ - definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); - } - } - } else { - if(definitionPropertyMap.containsKey("$ref")){ - definitionProperty.setHasPropertyReference(true); - String refItem = definitionPropertyMap.get("$ref").toString(); - int retCode = refItem.lastIndexOf('/'); - if(retCode != -1 && retCode != refItem.length()){ - definitionProperty.setPropertyReferenceObjectName(refItem.substring(retCode + 1)); - } - definitionProperty.setPropertyReference(refItem); - } - } - } - definitionProperties.add(definitionProperty); - }); - }); - - definition.setPropertyList(definitionProperties); - - List<Definition.Property> schemaProperties = definitionProperties. - stream() - .filter((o) -> o.isHasPropertyReference()) - .collect(Collectors.toList()); - - List<Definition.Property> regularProperties = definitionProperties. - stream() - .filter((o) -> !o.isHasPropertyReference()) - .collect(Collectors.toList()); - - definition.setRegularPropertyList(regularProperties); - definition.setSchemaPropertyList(schemaProperties); - - defintionsList.add(definition); - }); - return defintionsList; - } - - public static String formatDescription(String description){ - - description = Arrays.stream(description.split("\n")) - .map((line) -> { - line = line.trim(); - if(line.contains("######")){ - line = line.replaceAll("#", ""); - line = line.trim(); - String headerId = line.toLowerCase().replaceAll("\\s", "-"); - - if(line.contains("Related Nodes")){ - return String.format("<h6 id=\"%s\">%s</h6>%s<ul>", headerId, line, LINE_SEPARATOR); - } else { - return String.format("<h6 id=\"%s\">%s</h6>", headerId, line); - } - } else if(line.startsWith("-")){ - line = line.replaceFirst("-", ""); - line = line.trim(); - return String.format("<li>%s</li>", line); - } else { - return String.format("<p>%s</p>", line); - } - }) - .collect(Collectors.joining(LINE_SEPARATOR)); - - if(description.contains("<ul>")){ - description = description + "</ul>"; - } - - return description; - } - -} diff --git a/aai-core/src/main/java/org/openecomp/aai/workarounds/LegacyURITransformer.java b/aai-core/src/main/java/org/openecomp/aai/workarounds/LegacyURITransformer.java deleted file mode 100644 index f79bae60..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/workarounds/LegacyURITransformer.java +++ /dev/null @@ -1,93 +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.workarounds; - -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class LegacyURITransformer { - - private final Pattern legacyUriPattern = Pattern.compile("/aai/servers/(?<version>v[23])/(?<tenantKey>.*?)/vservers/(?<vserverKey>[^/]*?$)"); - private final Pattern currentUriPattern = Pattern.compile("/aai/(?<version>v\\d+)/cloud-infrastructure/tenants/tenant/(?<tenantKey>.*?)/vservers/vserver/(?<vserverKey>[^/]*?$)"); - /** - * Instantiates a new legacy URL transformer. - */ - private LegacyURITransformer() { - - } - - private static class Helper { - private static final LegacyURITransformer INSTANCE = new LegacyURITransformer(); - } - - /** - * Gets the single instance of LegacyURLTransformer. - * - * @return single instance of LegacyURLTransformer - */ - public static LegacyURITransformer getInstance() { - return Helper.INSTANCE; - } - - /** - * Gets the legacy URL. - * - * @param url the url - * @return the legacy URL - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - public URI getLegacyURI(URI url) throws URISyntaxException { - String replacement = "/aai/servers/${version}/${tenantKey}/vservers/${vserverKey}"; - String result = url.toString(); - Matcher m = currentUriPattern.matcher(result); - if (m.find()) { - result = m.replaceFirst(replacement); - - } - - return new URI(result); - - } - - /** - * Gets the current URL. - * - * @param url the url - * @return the current URL - * @throws URISyntaxException - * @throws MalformedURLException the malformed URL exception - */ - public URI getCurrentURI(URI url) throws URISyntaxException { - String replacement = "/aai/${version}/cloud-infrastructure/tenants/tenant/${tenantKey}/vservers/vserver/${vserverKey}"; - String result = url.toString(); - Matcher m = legacyUriPattern.matcher(result); - if (m.find()) { - result = m.replaceFirst(replacement); - - } - - return new URI(result); - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/workarounds/NamingExceptions.java b/aai-core/src/main/java/org/openecomp/aai/workarounds/NamingExceptions.java deleted file mode 100644 index 7ce063ed..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/workarounds/NamingExceptions.java +++ /dev/null @@ -1,79 +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.workarounds; - -public class NamingExceptions { - - /** - * Instantiates a new naming exceptions. - */ - private NamingExceptions() { - - } - - private static class Helper { - private static final NamingExceptions INSTANCE = new NamingExceptions(); - } - - /** - * Gets the single instance of NamingExceptions. - * - * @return single instance of NamingExceptions - */ - public static NamingExceptions getInstance() { - return Helper.INSTANCE; - } - - /** - * Gets the object name. - * - * @param name the name - * @return the object name - */ - public String getObjectName(String name) { - - String result = name; - - if (name.equals("cvlan-tag")) { - result = "cvlan-tag-entry"; - } - - return result; - } - - /** - * Gets the DB name. - * - * @param name the name - * @return the DB name - */ - public String getDBName(String name) { - - String result = name; - - if (name.equals("cvlan-tag-entry")) { - result = "cvlan-tag"; - } - - return result; - - } -} diff --git a/aai-core/src/main/java/org/openecomp/aai/workarounds/RemoveDME2QueryParams.java b/aai-core/src/main/java/org/openecomp/aai/workarounds/RemoveDME2QueryParams.java deleted file mode 100644 index b829639b..00000000 --- a/aai-core/src/main/java/org/openecomp/aai/workarounds/RemoveDME2QueryParams.java +++ /dev/null @@ -1,65 +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.workarounds; - -import javax.ws.rs.core.MultivaluedMap; - -public class RemoveDME2QueryParams { - - private final String[] blacklist = {"version", "envContext", "routeOffer"}; - - - /** - * Should remove query params. - * - * @param params the params - * @return true, if successful - */ - public boolean shouldRemoveQueryParams(MultivaluedMap<String, String> params) { - boolean remove = true; - - for (String param : blacklist) { - if (!params.containsKey(param)) { - remove = false; - break; - } - } - - return remove; - - } - - /** - * Removes the query params. - * - * @param params the params - */ - public void removeQueryParams(MultivaluedMap<String, String> params) { - - - for (String param : blacklist) { - params.remove(param); - } - - - } - -} |