[gerrit]
-host=gerrit.openecomp.org
+host=gerrit.onap.org
port=29418
project=aai/model-loader
<testRouteOffer>workstation</testRouteOffer>
<testEnv>DEV</testEnv>
- <!-- Ecomp Version -->
- <ecomp.version>1.0.0</ecomp.version>
-
<dependency.scope>provided</dependency.scope>
<checkstyle.config.location>google_checks.xml</checkstyle.config.location>
<maven.compiler.source>1.8</maven.compiler.source>
<dependency>
<groupId>org.openecomp.aai.logging-service</groupId>
<artifactId>common-logging</artifactId>
- <version>${ecomp.version}</version>
+ <version>1.0.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<dependency>
<groupId>org.openecomp.sdc</groupId>
<artifactId>sdc-distribution-client</artifactId>
- <version>${ecomp.version}</version>
+ <version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.config;\r
-\r
-import org.eclipse.jetty.util.security.Password;\r
-import org.openecomp.sdc.api.consumer.IConfiguration;\r
-\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-import java.util.Properties;\r
-\r
-public class ModelLoaderConfig implements IConfiguration {\r
- \r
- // Configuration file structure\r
- public static final String PREFIX_MODEL_LOADER_CONFIG = "ml";\r
- public static final String PREFIX_DISTRIBUTION_CLIENT = \r
- PREFIX_MODEL_LOADER_CONFIG + ".distribution.";\r
- public static final String PREFIX_AAI = PREFIX_MODEL_LOADER_CONFIG + ".aai.";\r
- public static final String PREFIX_DEBUG = PREFIX_MODEL_LOADER_CONFIG + ".debug.";\r
-\r
- // Configuration file properties\r
- protected static final String PROP_ML_DISTRIBUTION_ACTIVE_SERVER_TLS_AUTH = \r
- PREFIX_DISTRIBUTION_CLIENT + "ACTIVE_SERVER_TLS_AUTH";\r
- protected static final String PROP_ML_DISTRIBUTION_ASDC_ADDRESS = PREFIX_DISTRIBUTION_CLIENT\r
- + "ASDC_ADDRESS";\r
- protected static final String PROP_ML_DISTRIBUTION_CONSUMER_GROUP = PREFIX_DISTRIBUTION_CLIENT\r
- + "CONSUMER_GROUP";\r
- protected static final String PROP_ML_DISTRIBUTION_CONSUMER_ID = PREFIX_DISTRIBUTION_CLIENT\r
- + "CONSUMER_ID";\r
- protected static final String PROP_ML_DISTRIBUTION_ENVIRONMENT_NAME = PREFIX_DISTRIBUTION_CLIENT\r
- + "ENVIRONMENT_NAME";\r
- protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD = PREFIX_DISTRIBUTION_CLIENT\r
- + "KEYSTORE_PASSWORD";\r
- protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_FILE = PREFIX_DISTRIBUTION_CLIENT\r
- + "KEYSTORE_FILE";\r
- protected static final String PROP_ML_DISTRIBUTION_PASSWORD = PREFIX_DISTRIBUTION_CLIENT\r
- + "PASSWORD";\r
- protected static final String PROP_ML_DISTRIBUTION_POLLING_INTERVAL = PREFIX_DISTRIBUTION_CLIENT\r
- + "POLLING_INTERVAL";\r
- protected static final String PROP_ML_DISTRIBUTION_POLLING_TIMEOUT = PREFIX_DISTRIBUTION_CLIENT\r
- + "POLLING_TIMEOUT";\r
- protected static final String PROP_ML_DISTRIBUTION_USER = PREFIX_DISTRIBUTION_CLIENT + "USER";\r
- protected static final String PROP_ML_DISTRIBUTION_ARTIFACT_TYPES = PREFIX_DISTRIBUTION_CLIENT\r
- + "ARTIFACT_TYPES";\r
-\r
- protected static final String PROP_AAI_BASE_URL = PREFIX_AAI + "BASE_URL";\r
- protected static final String PROP_AAI_KEYSTORE_FILE = PREFIX_AAI + "KEYSTORE_FILE";\r
- protected static final String PROP_AAI_KEYSTORE_PASSWORD = PREFIX_AAI + "KEYSTORE_PASSWORD";\r
- protected static final String PROP_AAI_MODEL_RESOURCE_URL = PREFIX_AAI + "MODEL_URL";\r
- protected static final String PROP_AAI_NAMED_QUERY_RESOURCE_URL = PREFIX_AAI + "NAMED_QUERY_URL";\r
- protected static final String PROP_AAI_VNF_IMAGE_RESOURCE_URL = PREFIX_AAI + "VNF_IMAGE_URL";\r
- protected static final String PROP_AAI_AUTHENTICATION_USER = PREFIX_AAI + "AUTH_USER";\r
- protected static final String PROP_AAI_AUTHENTICATION_PASSWORD = PREFIX_AAI + "AUTH_PASSWORD";\r
-\r
- protected static final String PROP_DEBUG_INGEST_SIMULATOR = PREFIX_DEBUG + "INGEST_SIMULATOR";\r
-\r
- private Properties modelLoaderProperties = null;\r
-\r
- private String certLocation = ".";\r
-\r
- private List<String> artifactTypes = null;\r
-\r
- /**\r
- * This is the class constructor.\r
- * \r
- * @param modelLoaderProperties properties needed to be configured for the model loader\r
- * @param certLocation location of the certificate\r
- */\r
- public ModelLoaderConfig(Properties modelLoaderProperties, String certLocation) {\r
- this.modelLoaderProperties = modelLoaderProperties;\r
- this.certLocation = certLocation;\r
-\r
- // Get list of artifacts\r
- artifactTypes = new ArrayList<String>();\r
- if (modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ARTIFACT_TYPES) != null) {\r
- String[] artTypeList = modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ARTIFACT_TYPES)\r
- .split(",");\r
- for (String artType : artTypeList) {\r
- artifactTypes.add(artType);\r
- }\r
- }\r
- }\r
-\r
- @Override\r
- public boolean activateServerTLSAuth() {\r
- String value = modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ACTIVE_SERVER_TLS_AUTH);\r
- return value == null ? false : Boolean.parseBoolean(value);\r
- }\r
-\r
- @Override\r
- public String getAsdcAddress() {\r
- return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ASDC_ADDRESS);\r
- }\r
-\r
- @Override\r
- public String getConsumerGroup() {\r
- return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_CONSUMER_GROUP);\r
- }\r
-\r
- @Override\r
- public String getConsumerID() {\r
- return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_CONSUMER_ID);\r
- }\r
-\r
- @Override\r
- public String getEnvironmentName() {\r
- return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ENVIRONMENT_NAME);\r
- }\r
-\r
- @Override\r
- public String getKeyStorePassword() {\r
- return Password\r
- .deobfuscate(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD));\r
- }\r
-\r
- @Override\r
- public String getKeyStorePath() {\r
- return certLocation + modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_KEYSTORE_FILE);\r
- }\r
-\r
- @Override\r
- public String getPassword() {\r
- return Password.deobfuscate(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_PASSWORD));\r
- }\r
-\r
- @Override\r
- public int getPollingInterval() {\r
- return Integer\r
- .parseInt(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_POLLING_INTERVAL));\r
- }\r
-\r
- @Override\r
- public int getPollingTimeout() {\r
- return Integer\r
- .parseInt(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_POLLING_TIMEOUT));\r
- }\r
-\r
- @Override\r
- public List<String> getRelevantArtifactTypes() {\r
- return artifactTypes;\r
- }\r
-\r
- @Override\r
- public String getUser() {\r
- return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_USER);\r
- }\r
-\r
- public String getAaiKeyStorePath() {\r
- return certLocation + "/" + modelLoaderProperties.getProperty(PROP_AAI_KEYSTORE_FILE);\r
- }\r
-\r
- public String getAaiKeyStorePassword() {\r
- return Password.deobfuscate(modelLoaderProperties.getProperty(PROP_AAI_KEYSTORE_PASSWORD));\r
- }\r
-\r
- public String getAaiBaseUrl() {\r
- return modelLoaderProperties.getProperty(PROP_AAI_BASE_URL);\r
- }\r
-\r
- public String getAaiModelUrl() {\r
- return modelLoaderProperties.getProperty(PROP_AAI_MODEL_RESOURCE_URL);\r
- }\r
-\r
- public String getAaiNamedQueryUrl() {\r
- return modelLoaderProperties.getProperty(PROP_AAI_NAMED_QUERY_RESOURCE_URL);\r
- }\r
-\r
- public String getAaiVnfImageUrl() {\r
- return modelLoaderProperties.getProperty(PROP_AAI_VNF_IMAGE_RESOURCE_URL);\r
- }\r
-\r
- public String getAaiAuthenticationUser() {\r
- return modelLoaderProperties.getProperty(PROP_AAI_AUTHENTICATION_USER);\r
- }\r
-\r
- /**\r
- * @return password for AAI authentication that has been reverse-engineered\r
- * from its obfuscated form.\r
- */\r
- public String getAaiAuthenticationPassword() {\r
- String password = Password\r
- .deobfuscate(modelLoaderProperties.getProperty(PROP_AAI_AUTHENTICATION_PASSWORD));\r
-\r
- if ((password != null) && (password.equals(""))) {\r
- return null;\r
- }\r
-\r
- return password;\r
- }\r
-\r
- /**\r
- * @return a boolean value indicating whether the simulator is enabled.\r
- */\r
- public boolean getIngestSimulatorEnabled() {\r
- String propValue = modelLoaderProperties.getProperty(PROP_DEBUG_INGEST_SIMULATOR);\r
-\r
- if (propValue == null) {\r
- return false;\r
- }\r
-\r
- if (propValue.compareToIgnoreCase("enabled") == 0) {\r
- return true;\r
- }\r
-\r
- return false;\r
- }\r
-\r
- public boolean isFilterInEmptyResources() {\r
- return false;\r
- }\r
-\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.config;
+
+import org.eclipse.jetty.util.security.Password;
+import org.openecomp.sdc.api.consumer.IConfiguration;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Properties;
+
+public class ModelLoaderConfig implements IConfiguration {
+
+ // Configuration file structure
+ public static final String PREFIX_MODEL_LOADER_CONFIG = "ml";
+ public static final String PREFIX_DISTRIBUTION_CLIENT =
+ PREFIX_MODEL_LOADER_CONFIG + ".distribution.";
+ public static final String PREFIX_AAI = PREFIX_MODEL_LOADER_CONFIG + ".aai.";
+ public static final String PREFIX_DEBUG = PREFIX_MODEL_LOADER_CONFIG + ".debug.";
+
+ // Configuration file properties
+ protected static final String PROP_ML_DISTRIBUTION_ACTIVE_SERVER_TLS_AUTH =
+ PREFIX_DISTRIBUTION_CLIENT + "ACTIVE_SERVER_TLS_AUTH";
+ protected static final String PROP_ML_DISTRIBUTION_ASDC_ADDRESS = PREFIX_DISTRIBUTION_CLIENT
+ + "ASDC_ADDRESS";
+ protected static final String PROP_ML_DISTRIBUTION_CONSUMER_GROUP = PREFIX_DISTRIBUTION_CLIENT
+ + "CONSUMER_GROUP";
+ protected static final String PROP_ML_DISTRIBUTION_CONSUMER_ID = PREFIX_DISTRIBUTION_CLIENT
+ + "CONSUMER_ID";
+ protected static final String PROP_ML_DISTRIBUTION_ENVIRONMENT_NAME = PREFIX_DISTRIBUTION_CLIENT
+ + "ENVIRONMENT_NAME";
+ protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD = PREFIX_DISTRIBUTION_CLIENT
+ + "KEYSTORE_PASSWORD";
+ protected static final String PROP_ML_DISTRIBUTION_KEYSTORE_FILE = PREFIX_DISTRIBUTION_CLIENT
+ + "KEYSTORE_FILE";
+ protected static final String PROP_ML_DISTRIBUTION_PASSWORD = PREFIX_DISTRIBUTION_CLIENT
+ + "PASSWORD";
+ protected static final String PROP_ML_DISTRIBUTION_POLLING_INTERVAL = PREFIX_DISTRIBUTION_CLIENT
+ + "POLLING_INTERVAL";
+ protected static final String PROP_ML_DISTRIBUTION_POLLING_TIMEOUT = PREFIX_DISTRIBUTION_CLIENT
+ + "POLLING_TIMEOUT";
+ protected static final String PROP_ML_DISTRIBUTION_USER = PREFIX_DISTRIBUTION_CLIENT + "USER";
+ protected static final String PROP_ML_DISTRIBUTION_ARTIFACT_TYPES = PREFIX_DISTRIBUTION_CLIENT
+ + "ARTIFACT_TYPES";
+
+ protected static final String PROP_AAI_BASE_URL = PREFIX_AAI + "BASE_URL";
+ protected static final String PROP_AAI_KEYSTORE_FILE = PREFIX_AAI + "KEYSTORE_FILE";
+ protected static final String PROP_AAI_KEYSTORE_PASSWORD = PREFIX_AAI + "KEYSTORE_PASSWORD";
+ protected static final String PROP_AAI_MODEL_RESOURCE_URL = PREFIX_AAI + "MODEL_URL";
+ protected static final String PROP_AAI_NAMED_QUERY_RESOURCE_URL = PREFIX_AAI + "NAMED_QUERY_URL";
+ protected static final String PROP_AAI_VNF_IMAGE_RESOURCE_URL = PREFIX_AAI + "VNF_IMAGE_URL";
+ protected static final String PROP_AAI_AUTHENTICATION_USER = PREFIX_AAI + "AUTH_USER";
+ protected static final String PROP_AAI_AUTHENTICATION_PASSWORD = PREFIX_AAI + "AUTH_PASSWORD";
+
+ protected static final String PROP_DEBUG_INGEST_SIMULATOR = PREFIX_DEBUG + "INGEST_SIMULATOR";
+
+ private Properties modelLoaderProperties = null;
+
+ private String certLocation = ".";
+
+ private List<String> artifactTypes = null;
+
+ /**
+ * This is the class constructor.
+ *
+ * @param modelLoaderProperties properties needed to be configured for the model loader
+ * @param certLocation location of the certificate
+ */
+ public ModelLoaderConfig(Properties modelLoaderProperties, String certLocation) {
+ this.modelLoaderProperties = modelLoaderProperties;
+ this.certLocation = certLocation;
+
+ // Get list of artifacts
+ artifactTypes = new ArrayList<String>();
+ if (modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ARTIFACT_TYPES) != null) {
+ String[] artTypeList = modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ARTIFACT_TYPES)
+ .split(",");
+ for (String artType : artTypeList) {
+ artifactTypes.add(artType);
+ }
+ }
+ }
+
+ @Override
+ public boolean activateServerTLSAuth() {
+ String value = modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ACTIVE_SERVER_TLS_AUTH);
+ return value == null ? false : Boolean.parseBoolean(value);
+ }
+
+ @Override
+ public String getAsdcAddress() {
+ return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ASDC_ADDRESS);
+ }
+
+ @Override
+ public String getConsumerGroup() {
+ return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_CONSUMER_GROUP);
+ }
+
+ @Override
+ public String getConsumerID() {
+ return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_CONSUMER_ID);
+ }
+
+ @Override
+ public String getEnvironmentName() {
+ return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_ENVIRONMENT_NAME);
+ }
+
+ @Override
+ public String getKeyStorePassword() {
+ return Password
+ .deobfuscate(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD));
+ }
+
+ @Override
+ public String getKeyStorePath() {
+ return certLocation + modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_KEYSTORE_FILE);
+ }
+
+ @Override
+ public String getPassword() {
+ return Password.deobfuscate(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_PASSWORD));
+ }
+
+ @Override
+ public int getPollingInterval() {
+ return Integer
+ .parseInt(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_POLLING_INTERVAL));
+ }
+
+ @Override
+ public int getPollingTimeout() {
+ return Integer
+ .parseInt(modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_POLLING_TIMEOUT));
+ }
+
+ @Override
+ public List<String> getRelevantArtifactTypes() {
+ return artifactTypes;
+ }
+
+ @Override
+ public String getUser() {
+ return modelLoaderProperties.getProperty(PROP_ML_DISTRIBUTION_USER);
+ }
+
+ public String getAaiKeyStorePath() {
+ return certLocation + "/" + modelLoaderProperties.getProperty(PROP_AAI_KEYSTORE_FILE);
+ }
+
+ public String getAaiKeyStorePassword() {
+ return Password.deobfuscate(modelLoaderProperties.getProperty(PROP_AAI_KEYSTORE_PASSWORD));
+ }
+
+ public String getAaiBaseUrl() {
+ return modelLoaderProperties.getProperty(PROP_AAI_BASE_URL);
+ }
+
+ public String getAaiModelUrl(String version) {
+ return modelLoaderProperties.getProperty(PROP_AAI_MODEL_RESOURCE_URL).replace("v*", version);
+ }
+
+ public String getAaiNamedQueryUrl(String version) {
+ return modelLoaderProperties.getProperty(PROP_AAI_NAMED_QUERY_RESOURCE_URL).replace("v*", version);
+ }
+
+ public String getAaiVnfImageUrl() {
+ return modelLoaderProperties.getProperty(PROP_AAI_VNF_IMAGE_RESOURCE_URL);
+ }
+
+ public String getAaiAuthenticationUser() {
+ return modelLoaderProperties.getProperty(PROP_AAI_AUTHENTICATION_USER);
+ }
+
+ /**
+ * @return password for AAI authentication that has been reverse-engineered
+ * from its obfuscated form.
+ */
+ public String getAaiAuthenticationPassword() {
+ String password = Password
+ .deobfuscate(modelLoaderProperties.getProperty(PROP_AAI_AUTHENTICATION_PASSWORD));
+
+ if ((password != null) && (password.equals(""))) {
+ return null;
+ }
+
+ return password;
+ }
+
+ /**
+ * @return a boolean value indicating whether the simulator is enabled.
+ */
+ public boolean getIngestSimulatorEnabled() {
+ String propValue = modelLoaderProperties.getProperty(PROP_DEBUG_INGEST_SIMULATOR);
+
+ if (propValue == null) {
+ return false;
+ }
+
+ if (propValue.compareToIgnoreCase("enabled") == 0) {
+ return true;
+ }
+
+ return false;
+ }
+
+ public boolean isFilterInEmptyResources() {
+ return false;
+ }
+
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.entity.model;\r
-\r
-import org.openecomp.modelloader.entity.Artifact;\r
-import org.w3c.dom.Node;\r
-\r
-import java.util.HashSet;\r
-import java.util.Set;\r
-\r
-public class ModelArtifact extends Artifact {\r
-\r
- String modelVerId;\r
- String modelInvariantId;\r
- String nameVersionId;\r
- String modelModelVerCombinedKey;\r
- String modelVerModelVersionId;\r
- String modelModelInvariantId;\r
- String modelNamespace;\r
- Set<String> referencedModelIds = new HashSet<String>(); \r
- Node modelVer;\r
- boolean isV9Artifact = true;\r
- \r
- public boolean isV9Artifact() {\r
- return isV9Artifact;\r
- }\r
- \r
- public void setV9Artifact(boolean isV9Artifact) {\r
- this.isV9Artifact = isV9Artifact;\r
- }\r
-\r
- public String getModelVerModelVersionId() {\r
- return modelVerModelVersionId;\r
- }\r
- \r
- public void setModelVerModelVersionId(String modelVerModelVersionId) {\r
- this.modelVerModelVersionId = modelVerModelVersionId;\r
- }\r
- \r
- public String getModelModelInvariantId() {\r
- return modelModelInvariantId;\r
- }\r
- \r
- public void setModelModelInvariantId(String modelModelInvariantId) {\r
- this.modelModelInvariantId = modelModelInvariantId;\r
- }\r
- \r
- public String getNameVersionId() {\r
- return nameVersionId;\r
- }\r
-\r
- public void setNameVersionId(String nameVersionId) {\r
- this.nameVersionId = nameVersionId;\r
- }\r
- \r
- public String getModelNamespace() {\r
- return modelNamespace;\r
- }\r
- \r
- public void setModelNamespace(String modelNamespace) {\r
- this.modelNamespace = modelNamespace;\r
- }\r
-\r
- public Set<String> getDependentModelIds() {\r
- return referencedModelIds;\r
- }\r
-\r
- public void addDependentModelId(String dependentModelId) {\r
- this.referencedModelIds.add(dependentModelId);\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- StringBuilder sb = new StringBuilder();\r
- sb.append("ModelInvariantId=" + modelInvariantId + "(" + getType().toString() + ") ==> ");\r
- for (String dep : referencedModelIds) {\r
- sb.append(dep + " ");\r
- }\r
-\r
- return sb.toString();\r
- }\r
-\r
- public String getModelVerId() {\r
- return modelVerId;\r
- }\r
- \r
- public void setModelVerId(String modelVerId) {\r
- this.modelVerId = modelVerId;\r
- }\r
- \r
- public String getModelInvariantId() {\r
- return modelInvariantId;\r
- }\r
- \r
- public void setModelInvariantId(String modelInvariantId) {\r
- this.modelInvariantId = modelInvariantId;\r
- }\r
- \r
- public Node getModelVer() {\r
- return modelVer;\r
- }\r
- \r
- public void setModelVer(Node modelVer) {\r
- this.modelVer = modelVer;\r
- }\r
- \r
- public String getModelModelVerCombinedKey() {\r
- return getModelInvariantId() + "|" + getModelVerId();\r
- }\r
- \r
- public void setModelModelVerCombinedKey(String modelModelVerCombinedKey) {\r
- this.modelModelVerCombinedKey = getModelInvariantId() + "|" + getModelVerId();\r
- }\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.entity.model;
+
+import org.openecomp.modelloader.entity.Artifact;
+import org.w3c.dom.Node;
+
+import java.util.HashSet;
+import java.util.Set;
+
+public class ModelArtifact extends Artifact {
+
+ String modelVerId;
+ String modelInvariantId;
+ String nameVersionId;
+ String modelVerModelVersionId;
+ String modelModelInvariantId;
+ String modelNamespace;
+ String modelNamespaceVersion;
+ Set<String> referencedModelIds = new HashSet<String>();
+ Node modelVer;
+ boolean isV9Artifact = true;
+
+ public boolean isV9Artifact() {
+ return isV9Artifact;
+ }
+
+ public void setV9Artifact(boolean isV9Artifact) {
+ this.isV9Artifact = isV9Artifact;
+ }
+
+ public String getModelVerModelVersionId() {
+ return modelVerModelVersionId;
+ }
+
+ public void setModelVerModelVersionId(String modelVerModelVersionId) {
+ this.modelVerModelVersionId = modelVerModelVersionId;
+ }
+
+ public String getModelModelInvariantId() {
+ return modelModelInvariantId;
+ }
+
+ public void setModelModelInvariantId(String modelModelInvariantId) {
+ this.modelModelInvariantId = modelModelInvariantId;
+ }
+
+ public String getNameVersionId() {
+ return nameVersionId;
+ }
+
+ public void setNameVersionId(String nameVersionId) {
+ this.nameVersionId = nameVersionId;
+ }
+
+ public String getModelNamespace() {
+ return modelNamespace;
+ }
+
+ public void setModelNamespace(String modelNamespace) {
+ this.modelNamespace = modelNamespace;
+
+ // Get the version from the namespace (in format 'http://org.openecomp.aai.inventory/v9')
+ String[] parts = modelNamespace.split("/");
+ modelNamespaceVersion = parts[parts.length-1].trim();
+ }
+
+ public String getModelNamespaceVersion() {
+ return modelNamespaceVersion;
+ }
+
+ public Set<String> getDependentModelIds() {
+ return referencedModelIds;
+ }
+
+ public void addDependentModelId(String dependentModelId) {
+ this.referencedModelIds.add(dependentModelId);
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append("ModelInvariantId=" + modelInvariantId + "(" + getType().toString() + ") ==> ");
+ for (String dep : referencedModelIds) {
+ sb.append(dep + " ");
+ }
+
+ return sb.toString();
+ }
+
+ public String getModelVerId() {
+ return modelVerId;
+ }
+
+ public void setModelVerId(String modelVerId) {
+ this.modelVerId = modelVerId;
+ }
+
+ public String getModelInvariantId() {
+ return modelInvariantId;
+ }
+
+ public void setModelInvariantId(String modelInvariantId) {
+ this.modelInvariantId = modelInvariantId;
+ }
+
+ public Node getModelVer() {
+ return modelVer;
+ }
+
+ public void setModelVer(Node modelVer) {
+ this.modelVer = modelVer;
+ }
+
+ public String getModelModelVerCombinedKey() {
+ if ( (getModelInvariantId() == null) && (getModelVerId() == null) ) {
+ return getNameVersionId();
+ }
+ return getModelInvariantId() + "|" + getModelVerId();
+ }
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.entity.model;\r
-\r
-import com.sun.jersey.api.client.ClientResponse;\r
-\r
-import org.openecomp.cl.api.Logger;\r
-import org.openecomp.cl.eelf.LoggerFactory;\r
-import org.openecomp.modelloader.config.ModelLoaderConfig;\r
-import org.openecomp.modelloader.entity.Artifact;\r
-import org.openecomp.modelloader.entity.ArtifactHandler;\r
-import org.openecomp.modelloader.entity.ArtifactType;\r
-import org.openecomp.modelloader.restclient.AaiRestClient;\r
-import org.openecomp.modelloader.service.ModelLoaderMsgs;\r
-\r
-import org.w3c.dom.Node;\r
-\r
-import java.io.StringWriter;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import javax.ws.rs.core.Response;\r
-import javax.xml.transform.OutputKeys;\r
-import javax.xml.transform.Transformer;\r
-import javax.xml.transform.TransformerException;\r
-import javax.xml.transform.TransformerFactory;\r
-import javax.xml.transform.dom.DOMSource;\r
-import javax.xml.transform.stream.StreamResult;\r
-\r
-\r
-public class ModelArtifactHandler extends ArtifactHandler {\r
-\r
- private static final String AAI_MODEL_VER = "/model-vers/model-ver";\r
- private static Logger logger = LoggerFactory.getInstance().getLogger(ArtifactHandler.class.getName());\r
-\r
-\r
- public ModelArtifactHandler(ModelLoaderConfig config) {\r
- super(config);\r
- }\r
-\r
- @Override\r
- public boolean pushArtifacts(List<Artifact> artifacts, String distributionID) {\r
- ModelSorter modelSorter = new ModelSorter();\r
- List<Artifact> sortedModelArtifacts = modelSorter.sort(artifacts);\r
-\r
- // Push the ordered list of model artifacts to A&AI. If one fails, we need to roll back\r
- // the changes.\r
- List<ModelArtifact> completedModels = new ArrayList<ModelArtifact>();\r
- AaiRestClient aaiClient = new AaiRestClient(config);\r
-\r
- for (Artifact art : sortedModelArtifacts) {\r
- ModelArtifact model = (ModelArtifact)art;\r
-\r
- boolean version = model.isV9Artifact();\r
- //Non - V9 version for models\r
- if(version == false){\r
- ClientResponse getResponse = aaiClient.getResource(getModelVerURL(model), distributionID, AaiRestClient.MimeType.XML);\r
- if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {\r
- logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, " Artifact format not valid for " + \r
- model.getType().toString() + "- model-invariant-id[model-id]: " + \r
- model.getModelInvariantId() + " and model-version-id[model-name-version-id]: "+ \r
- model.getModelVerId()+ " . Rolling back distribution.");\r
- return false;\r
- }\r
- else{\r
- completedModels.add(model);\r
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + \r
- " " + model.getModelInvariantId() + " successfully ingested.");\r
- }\r
- }\r
- else\r
- {\r
- ClientResponse getResponse = aaiClient.getResource(getURL(model), distributionID, AaiRestClient.MimeType.XML);\r
- if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {\r
- // Only attempt the PUT if the model doesn't already exist\r
- ClientResponse putResponse = aaiClient.putResource(getURL(model), model.getPayload(), distributionID, AaiRestClient.MimeType.XML);\r
- if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {\r
- completedModels.add(model);\r
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + \r
- " " + model.getModelInvariantId() + " successfully ingested.");\r
- }\r
- else {\r
- logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + \r
- model.getType().toString() + " " + model.getModelInvariantId() + ". Rolling back distribution.");\r
-\r
- for (ModelArtifact modelToDelete : completedModels) {\r
- // Best effort to delete. Nothing we can do in the event this fails.\r
- aaiClient.getAndDeleteResource(getURL(modelToDelete), distributionID);\r
- }\r
-\r
- return false;\r
- }\r
- }\r
- else {\r
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " + model.getModelInvariantId() + \r
- " already exists. Skipping ingestion.");\r
- getResponse = aaiClient.getResource(getModelVerURL(model), distributionID, AaiRestClient.MimeType.XML);\r
- if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {\r
- // Only attempt the PUT if the model-ver doesn't already exist\r
- ClientResponse putResponse = null;\r
-\r
- try {\r
- putResponse = aaiClient.putResource(getModelVerURL(model), nodeToString(model.getModelVer()), distributionID, AaiRestClient.MimeType.XML);\r
- } catch (TransformerException e) {\r
- // TODO Auto-generated catch block\r
- e.printStackTrace();\r
- }\r
- if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {\r
- completedModels.add(model);\r
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " + \r
- model.getNameVersionId() + " successfully ingested.");\r
- }\r
- else {\r
- logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " + \r
- model.getType().toString() + " " + model.getNameVersionId() + ". Rolling back distribution.");\r
-\r
- for (ModelArtifact modelToDelete : completedModels) {\r
- // Best effort to delete. Nothing we can do in the event this fails.\r
- aaiClient.getAndDeleteResource(getModelVerURL(modelToDelete), distributionID);\r
- }\r
-\r
- return false;\r
- }\r
- }\r
- else {\r
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " + \r
- model.getModelInvariantId() + " already exists. Skipping ingestion.");\r
- }\r
- }\r
- }\r
- }\r
-\r
- return true;\r
- }\r
-\r
-\r
- private String nodeToString(Node node) throws TransformerException {\r
- StringWriter sw = new StringWriter();\r
- Transformer t = TransformerFactory.newInstance().newTransformer();\r
- t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");\r
- t.transform(new DOMSource(node), new StreamResult(sw));\r
- System.out.println(sw.toString());\r
- return sw.toString();\r
- }\r
-\r
- private String getURL(ModelArtifact model) {\r
- String baseURL = config.getAaiBaseUrl().trim();\r
- String subURL = null;\r
- if (model.getType().equals(ArtifactType.MODEL)) {\r
- subURL = config.getAaiModelUrl().trim();\r
- }\r
- else {\r
- subURL = config.getAaiNamedQueryUrl().trim();\r
- }\r
-\r
- if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {\r
- baseURL = baseURL + "/";\r
- }\r
-\r
- if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {\r
- baseURL = baseURL.substring(0, baseURL.length()-1);\r
- }\r
-\r
- if (!subURL.endsWith("/")) {\r
- subURL = subURL + "/";\r
- }\r
-\r
- String url = baseURL + subURL + model.getModelInvariantId();\r
- return url;\r
- }\r
-\r
- private String getModelVerURL(ModelArtifact model) {\r
- String baseURL = config.getAaiBaseUrl().trim();\r
- String subURL = null;\r
- if (model.getType().equals(ArtifactType.MODEL)) {\r
- subURL = config.getAaiModelUrl().trim() + model.getModelInvariantId() + AAI_MODEL_VER;\r
- }\r
- else {\r
- subURL = config.getAaiNamedQueryUrl().trim();\r
- }\r
-\r
- if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {\r
- baseURL = baseURL + "/";\r
- }\r
-\r
- if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {\r
- baseURL = baseURL.substring(0, baseURL.length()-1);\r
- }\r
-\r
- if (!subURL.endsWith("/")) {\r
- subURL = subURL + "/";\r
- }\r
-\r
- String url = baseURL + subURL + model.getModelVerId();\r
- System.out.println(url);\r
- return url;\r
- }\r
-\r
- // This method is used for the test REST interface to load models without an ASDC\r
- public void loadModelTest(byte[] payload) {\r
- List<Artifact> modelArtifacts = new ArrayList<Artifact>();\r
- ModelArtifactParser parser = new ModelArtifactParser();\r
- modelArtifacts.addAll(parser.parse(payload, "Test-Artifact"));\r
- ModelSorter modelSorter = new ModelSorter();\r
- List<Artifact> sortedModelArtifacts = modelSorter.sort(modelArtifacts);\r
- pushArtifacts(sortedModelArtifacts, "Test-Distribution");\r
- }\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.entity.model;
+
+import com.sun.jersey.api.client.ClientResponse;
+
+import org.openecomp.cl.api.Logger;
+import org.openecomp.cl.eelf.LoggerFactory;
+import org.openecomp.modelloader.config.ModelLoaderConfig;
+import org.openecomp.modelloader.entity.Artifact;
+import org.openecomp.modelloader.entity.ArtifactHandler;
+import org.openecomp.modelloader.entity.ArtifactType;
+import org.openecomp.modelloader.restclient.AaiRestClient;
+import org.openecomp.modelloader.service.ModelLoaderMsgs;
+
+import org.w3c.dom.Node;
+
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ws.rs.core.Response;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+public class ModelArtifactHandler extends ArtifactHandler {
+
+ private static final String AAI_MODEL_VER = "/model-vers/model-ver";
+ private static Logger logger = LoggerFactory.getInstance().getLogger(ArtifactHandler.class.getName());
+
+
+ public ModelArtifactHandler(ModelLoaderConfig config) {
+ super(config);
+ }
+
+ @Override
+ public boolean pushArtifacts(List<Artifact> artifacts, String distributionID) {
+ ModelSorter modelSorter = new ModelSorter();
+ List<Artifact> sortedModelArtifacts = modelSorter.sort(artifacts);
+
+ // Push the ordered list of model artifacts to A&AI. If one fails, we need to roll back
+ // the changes.
+ List<ModelArtifact> completedModels = new ArrayList<ModelArtifact>();
+ AaiRestClient aaiClient = new AaiRestClient(config);
+
+ for (Artifact art : sortedModelArtifacts) {
+ ModelArtifact model = (ModelArtifact)art;
+
+ boolean version = model.isV9Artifact();
+ //Non - V9 version for models
+ if(version == false){
+ ClientResponse getResponse = aaiClient.getResource(getModelVerURL(model), distributionID, AaiRestClient.MimeType.XML);
+ if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
+ logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, " Artifact format not valid for " +
+ model.getType().toString() + "- model-invariant-id[model-id]: " +
+ model.getModelInvariantId() + " and model-version-id[model-name-version-id]: "+
+ model.getModelVerId()+ " . Rolling back distribution.");
+ return false;
+ }
+ else{
+ completedModels.add(model);
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() +
+ " " + model.getModelInvariantId() + " successfully ingested.");
+ }
+ }
+ else
+ {
+ ClientResponse getResponse = aaiClient.getResource(getURL(model), distributionID, AaiRestClient.MimeType.XML);
+ if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
+ // Only attempt the PUT if the model doesn't already exist
+ ClientResponse putResponse = aaiClient.putResource(getURL(model), model.getPayload(), distributionID, AaiRestClient.MimeType.XML);
+ if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
+ completedModels.add(model);
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() +
+ " " + model.getModelInvariantId() + " successfully ingested.");
+ }
+ else {
+ logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " +
+ model.getType().toString() + " " + model.getModelInvariantId() + ". Rolling back distribution.");
+
+ for (ModelArtifact modelToDelete : completedModels) {
+ // Best effort to delete. Nothing we can do in the event this fails.
+ aaiClient.getAndDeleteResource(getURL(modelToDelete), distributionID);
+ }
+
+ return false;
+ }
+ }
+ else {
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " + model.getModelInvariantId() +
+ " already exists. Skipping ingestion.");
+ getResponse = aaiClient.getResource(getModelVerURL(model), distributionID, AaiRestClient.MimeType.XML);
+ if ( (getResponse == null) || (getResponse.getStatus() != Response.Status.OK.getStatusCode()) ) {
+ // Only attempt the PUT if the model-ver doesn't already exist
+ ClientResponse putResponse = null;
+
+ try {
+ putResponse = aaiClient.putResource(getModelVerURL(model), nodeToString(model.getModelVer()), distributionID, AaiRestClient.MimeType.XML);
+ } catch (TransformerException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ if ( (putResponse != null) && (putResponse.getStatus() == Response.Status.CREATED.getStatusCode()) ) {
+ completedModels.add(model);
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " +
+ model.getNameVersionId() + " successfully ingested.");
+ }
+ else {
+ logger.error(ModelLoaderMsgs.DISTRIBUTION_EVENT_ERROR, "Ingestion failed for " +
+ model.getType().toString() + " " + model.getNameVersionId() + ". Rolling back distribution.");
+
+ for (ModelArtifact modelToDelete : completedModels) {
+ // Best effort to delete. Nothing we can do in the event this fails.
+ aaiClient.getAndDeleteResource(getModelVerURL(modelToDelete), distributionID);
+ }
+
+ return false;
+ }
+ }
+ else {
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, model.getType().toString() + " " +
+ model.getModelInvariantId() + " already exists. Skipping ingestion.");
+ }
+ }
+ }
+ }
+
+ return true;
+ }
+
+
+ private String nodeToString(Node node) throws TransformerException {
+ StringWriter sw = new StringWriter();
+ Transformer t = TransformerFactory.newInstance().newTransformer();
+ t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ t.transform(new DOMSource(node), new StreamResult(sw));
+ System.out.println(sw.toString());
+ return sw.toString();
+ }
+
+ private String getURL(ModelArtifact model) {
+ String baseURL = config.getAaiBaseUrl().trim();
+ String subURL = null;
+ if (model.getType().equals(ArtifactType.MODEL)) {
+ subURL = config.getAaiModelUrl(model.getModelNamespaceVersion()).trim();
+ }
+ else {
+ subURL = config.getAaiNamedQueryUrl(model.getModelNamespaceVersion()).trim();
+ }
+
+ if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
+ baseURL = baseURL + "/";
+ }
+
+ if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
+ baseURL = baseURL.substring(0, baseURL.length()-1);
+ }
+
+ if (!subURL.endsWith("/")) {
+ subURL = subURL + "/";
+ }
+
+ String url = baseURL + subURL + model.getModelInvariantId();
+ return url;
+ }
+
+ private String getModelVerURL(ModelArtifact model) {
+ String baseURL = config.getAaiBaseUrl().trim();
+ String subURL = null;
+ if (model.getType().equals(ArtifactType.MODEL)) {
+ subURL = config.getAaiModelUrl(model.getModelNamespaceVersion()).trim() + model.getModelInvariantId() + AAI_MODEL_VER;
+ }
+ else {
+ subURL = config.getAaiNamedQueryUrl(model.getModelNamespaceVersion()).trim();
+ }
+
+ if ( (!baseURL.endsWith("/")) && (!subURL.startsWith("/")) ) {
+ baseURL = baseURL + "/";
+ }
+
+ if ( baseURL.endsWith("/") && subURL.startsWith("/") ) {
+ baseURL = baseURL.substring(0, baseURL.length()-1);
+ }
+
+ if (!subURL.endsWith("/")) {
+ subURL = subURL + "/";
+ }
+
+ String url = baseURL + subURL + model.getModelVerId();
+ System.out.println(url);
+ return url;
+ }
+
+ // This method is used for the test REST interface to load models without an ASDC
+ public void loadModelTest(byte[] payload) {
+ List<Artifact> modelArtifacts = new ArrayList<Artifact>();
+ ModelArtifactParser parser = new ModelArtifactParser();
+ modelArtifacts.addAll(parser.parse(payload, "Test-Artifact"));
+ ModelSorter modelSorter = new ModelSorter();
+ List<Artifact> sortedModelArtifacts = modelSorter.sort(modelArtifacts);
+ pushArtifacts(sortedModelArtifacts, "Test-Distribution");
+ }
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.entity.model;\r
-\r
-import org.openecomp.cl.api.Logger;\r
-import org.openecomp.cl.eelf.LoggerFactory;\r
-import org.openecomp.modelloader.entity.Artifact;\r
-import org.openecomp.modelloader.entity.ArtifactType;\r
-import org.openecomp.modelloader.service.ModelLoaderMsgs;\r
-import org.openecomp.modelloader.util.JsonXmlConverter;\r
-\r
-import org.w3c.dom.Document;\r
-import org.w3c.dom.Element;\r
-import org.w3c.dom.Node;\r
-import org.w3c.dom.NodeList;\r
-import org.xml.sax.InputSource;\r
-\r
-import java.io.StringReader;\r
-import java.io.StringWriter;\r
-import java.util.ArrayList;\r
-import java.util.List;\r
-\r
-import javax.xml.XMLConstants;\r
-import javax.xml.parsers.DocumentBuilder;\r
-import javax.xml.parsers.DocumentBuilderFactory;\r
-import javax.xml.transform.OutputKeys;\r
-import javax.xml.transform.Transformer;\r
-import javax.xml.transform.TransformerException;\r
-import javax.xml.transform.TransformerFactory;\r
-import javax.xml.transform.dom.DOMSource;\r
-import javax.xml.transform.stream.StreamResult;\r
-\r
-\r
-public class ModelArtifactParser {\r
-\r
- private static String MODELS_ELEMENT = "models";\r
- private static String MODEL_ELEMENT = "model";\r
- private static String NAMED_QUERIES_ELEMENT = "named-queries";\r
- private static String NAMED_QUERY_ELEMENT = "named-query";\r
- private static String MODEL_NAME_VERSION_ID = "model-name-version-id";\r
- private static String MODEL_VER = "model-ver";\r
- private static String MODEL_VERSION_ID = "model-version-id";\r
- private static String MODEL_INVARIANT_ID = "model-invariant-id";\r
- private static String NAMED_QUERY_VERSION_ID = "named-query-uuid";\r
- private static String RELATIONSHIP_DATA = "relationship-data";\r
- private static String RELATIONSHIP_KEY = "relationship-key";\r
- private static String RELATIONSHIP_VALUE = "relationship-value";\r
- private static String MODEL_ELEMENT_RELATIONSHIP_KEY = "model.model-invariant-id";\r
- private static String MODEL_VER_ELEMENT_RELATIONSHIP_KEY = "model-ver.model-version-id";\r
- \r
- private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifactParser.class.getName());\r
- \r
- public List<Artifact> parse(byte[] artifactPayload, String artifactName) {\r
- String payload = new String(artifactPayload);\r
- List<Artifact> modelList = new ArrayList<Artifact>();\r
-\r
- try {\r
- // Artifact could be JSON or XML\r
- if (JsonXmlConverter.isValidJson(payload)) {\r
- payload = JsonXmlConverter.convertJsonToXml(payload);\r
- }\r
-\r
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r
- DocumentBuilder builder = factory.newDocumentBuilder();\r
- InputSource is = new InputSource(new StringReader(payload));\r
- Document doc = builder.parse(is);\r
-\r
- if ( (doc.getDocumentElement().getNodeName().equalsIgnoreCase(MODEL_ELEMENT)) || \r
- (doc.getDocumentElement().getNodeName().equalsIgnoreCase(NAMED_QUERY_ELEMENT)) ) {\r
-\r
- ModelArtifact model = parseModel(doc.getDocumentElement(), payload);\r
-\r
- if (model != null) {\r
- if ( ArtifactType.MODEL.equals(model.getType())) {\r
- logger.info( ModelLoaderMsgs.DISTRIBUTION_EVENT, "Model parsed =====>>>> "\r
- + "Model-invariant-Id: "+ model.getModelInvariantId()\r
- + " Model-Version-Id: "+ model.getModelVerId());\r
- }\r
- modelList.add(model);\r
- }\r
- else {\r
- logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Unable to parse artifact " + artifactName);\r
- return null;\r
- }\r
- }\r
- else if ( (doc.getDocumentElement().getNodeName().equalsIgnoreCase(MODELS_ELEMENT)) ||\r
- (doc.getDocumentElement().getNodeName().equalsIgnoreCase(NAMED_QUERIES_ELEMENT)) ) {\r
- // The complete set of models/named-queries were contained in this artifact\r
- NodeList nodeList = doc.getDocumentElement().getChildNodes();\r
- for (int i = 0; i < nodeList.getLength(); i++) {\r
- Node childNode = nodeList.item(i);\r
- if ( (childNode.getNodeName().equalsIgnoreCase(MODEL_ELEMENT)) || \r
- (childNode.getNodeName().equalsIgnoreCase(NAMED_QUERY_ELEMENT)) ) {\r
- String modelPayload = nodeToString(childNode);\r
- ModelArtifact model = parseModel(childNode, modelPayload);\r
- if (model != null) {\r
- modelList.add(model);\r
- }\r
- else {\r
- logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Unable to parse artifact " + artifactName);\r
- modelList.clear();\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- }\r
- catch (Exception ex) {\r
- logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Unable to parse artifact " + artifactName + ": " + ex.getLocalizedMessage());\r
- }\r
-\r
- return modelList;\r
- }\r
-\r
- private void printDetails(Node modelVer) throws TransformerException {\r
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, nodeToString(modelVer));\r
- }\r
-\r
- private ModelArtifact parseModel(Node modelNode, String payload) {\r
- ModelArtifact model = new ModelArtifact();\r
- model.setPayload(payload);\r
-\r
- if (modelNode.getNodeName().equalsIgnoreCase(MODEL_ELEMENT)) {\r
- //compare with Model-ver\r
- model.setType(ArtifactType.MODEL);\r
- }\r
- else {\r
- model.setType(ArtifactType.NAMED_QUERY);\r
- }\r
-\r
- Element e = (Element)modelNode;\r
- model.setModelNamespace(e.getAttribute("xmlns"));\r
-\r
- parseNode(modelNode, model);\r
-\r
- if (model.getModelInvariantId() == null && model.getNameVersionId() == null) {\r
- return null;\r
- }\r
-\r
- return model;\r
- }\r
-\r
- private void parseNode(Node node, ModelArtifact model) {\r
-\r
- if(node.getNodeName().equalsIgnoreCase(MODEL_NAME_VERSION_ID)){\r
- model.setModelVerId(node.getTextContent().trim());\r
- model.setV9Artifact(false);\r
- }\r
- else if(node.getNodeName().equalsIgnoreCase("model-id")){\r
- model.setModelInvariantId(node.getTextContent().trim());\r
- model.setV9Artifact(false);\r
- }\r
-\r
- else if (node.getNodeName().equalsIgnoreCase(MODEL_INVARIANT_ID)) {\r
- model.setModelInvariantId(node.getTextContent().trim());\r
- }\r
- else if (node.getNodeName().equalsIgnoreCase(MODEL_VERSION_ID)) {\r
- model.setModelVerId(node.getTextContent().trim());\r
- //Change to Model Invariant Id\r
- }\r
- else if (node.getNodeName().equalsIgnoreCase(NAMED_QUERY_VERSION_ID)) {\r
- model.setNameVersionId(node.getTextContent().trim());\r
- }\r
- else if (node.getNodeName().equalsIgnoreCase(RELATIONSHIP_DATA)) {\r
- parseRelationshipNode(node, model);\r
- if(model.getModelModelInvariantId()!=null && model.getModelVerModelVersionId()!=null && !model.getModelModelInvariantId().isEmpty() && !model.getModelVerModelVersionId().isEmpty()){\r
- model.addDependentModelId(model.getModelModelInvariantId() + "|" + model.getModelVerModelVersionId());\r
- model.setModelModelInvariantId("");\r
- model.setModelVerModelVersionId("");\r
- }\r
- }\r
- else {\r
-\r
- if (node.getNodeName().equalsIgnoreCase(MODEL_VER)) {\r
- model.setModelVer(node);\r
- if ( (model.getModelNamespace() != null) && (!model.getModelNamespace().isEmpty()) ) {\r
- Element e = (Element) node;\r
- e.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns", model.getModelNamespace());\r
- System.out.println("Setting NS: " + e.getAttribute("xmlns"));\r
- }\r
- }\r
-\r
- NodeList nodeList = node.getChildNodes();\r
-\r
- for (int i = 0; i < nodeList.getLength(); i++) {\r
- Node childNode = nodeList.item(i); \r
- parseNode(childNode, model);\r
- }\r
- }\r
- }\r
-\r
- private void parseRelationshipNode(Node node, ModelArtifact model) {\r
-\r
- //invariant-id comes before model-version-id .. create a list of values\r
- String key = null;\r
- String value = null;\r
- String modelVersionIdKey=null;\r
- String modelInvariantIdIdKey=null;\r
- String modelVersionIdValue=null;\r
- String modelInvariantIdIdValue=null;\r
-\r
- NodeList nodeList = node.getChildNodes();\r
- for (int i = 0; i < nodeList.getLength(); i++) {\r
- Node childNode = nodeList.item(i);\r
-\r
-\r
- if (childNode.getNodeName().equalsIgnoreCase(RELATIONSHIP_KEY)) {\r
- key = childNode.getTextContent().trim();\r
- if(key.equalsIgnoreCase(MODEL_VER_ELEMENT_RELATIONSHIP_KEY)){\r
- modelVersionIdKey = key;\r
- }\r
- else if(key.equalsIgnoreCase(MODEL_ELEMENT_RELATIONSHIP_KEY)){\r
- modelInvariantIdIdKey = key;\r
- }\r
- }\r
- else if (childNode.getNodeName().equalsIgnoreCase(RELATIONSHIP_VALUE)) {\r
- value = childNode.getTextContent().trim();\r
- if(modelVersionIdKey!=null){\r
- modelVersionIdValue = value;\r
- model.setModelVerModelVersionId(modelVersionIdValue);\r
- }\r
- else if(modelInvariantIdIdKey!=null){\r
- modelInvariantIdIdValue = value;\r
- model.setModelModelInvariantId(modelInvariantIdIdValue);\r
- } \r
-\r
- }\r
- }\r
-\r
- if ( (key != null) && (key.equalsIgnoreCase(MODEL_ELEMENT_RELATIONSHIP_KEY )) && \r
- (model.isV9Artifact == false ||ArtifactType.NAMED_QUERY.equals(model.getType())) ) {\r
- if (value != null) {\r
- model.addDependentModelId(value);\r
- }\r
- }\r
- }\r
-\r
- private String nodeToString(Node node) throws TransformerException {\r
- StringWriter sw = new StringWriter();\r
- Transformer t = TransformerFactory.newInstance().newTransformer();\r
- t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");\r
- t.transform(new DOMSource(node), new StreamResult(sw));\r
- return sw.toString();\r
- }\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.entity.model;
+
+import org.openecomp.cl.api.Logger;
+import org.openecomp.cl.eelf.LoggerFactory;
+import org.openecomp.modelloader.entity.Artifact;
+import org.openecomp.modelloader.entity.ArtifactType;
+import org.openecomp.modelloader.service.ModelLoaderMsgs;
+import org.openecomp.modelloader.util.JsonXmlConverter;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+
+import java.io.StringReader;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.XMLConstants;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+
+public class ModelArtifactParser {
+
+ private static String MODELS_ELEMENT = "models";
+ private static String MODEL_ELEMENT = "model";
+ private static String NAMED_QUERIES_ELEMENT = "named-queries";
+ private static String NAMED_QUERY_ELEMENT = "named-query";
+ private static String MODEL_NAME_VERSION_ID = "model-name-version-id";
+ private static String MODEL_VER = "model-ver";
+ private static String MODEL_VERSION_ID = "model-version-id";
+ private static String MODEL_INVARIANT_ID = "model-invariant-id";
+ private static String NAMED_QUERY_VERSION_ID = "named-query-uuid";
+ private static String RELATIONSHIP_DATA = "relationship-data";
+ private static String RELATIONSHIP_KEY = "relationship-key";
+ private static String RELATIONSHIP_VALUE = "relationship-value";
+ private static String MODEL_ELEMENT_RELATIONSHIP_KEY = "model.model-invariant-id";
+ private static String MODEL_VER_ELEMENT_RELATIONSHIP_KEY = "model-ver.model-version-id";
+
+ private static Logger logger = LoggerFactory.getInstance().getLogger(ModelArtifactParser.class.getName());
+
+ public List<Artifact> parse(byte[] artifactPayload, String artifactName) {
+ String payload = new String(artifactPayload);
+ List<Artifact> modelList = new ArrayList<Artifact>();
+
+ try {
+ // Artifact could be JSON or XML
+ if (JsonXmlConverter.isValidJson(payload)) {
+ payload = JsonXmlConverter.convertJsonToXml(payload);
+ }
+
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ DocumentBuilder builder = factory.newDocumentBuilder();
+ InputSource is = new InputSource(new StringReader(payload));
+ Document doc = builder.parse(is);
+
+ if ( (doc.getDocumentElement().getNodeName().equalsIgnoreCase(MODEL_ELEMENT)) ||
+ (doc.getDocumentElement().getNodeName().equalsIgnoreCase(NAMED_QUERY_ELEMENT)) ) {
+
+ ModelArtifact model = parseModel(doc.getDocumentElement(), payload);
+
+ if (model != null) {
+ if ( ArtifactType.MODEL.equals(model.getType())) {
+ logger.info( ModelLoaderMsgs.DISTRIBUTION_EVENT, "Model parsed =====>>>> "
+ + "Model-invariant-Id: "+ model.getModelInvariantId()
+ + " Model-Version-Id: "+ model.getModelVerId());
+ }
+ modelList.add(model);
+ }
+ else {
+ logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Unable to parse artifact " + artifactName);
+ return null;
+ }
+ }
+ else if ( (doc.getDocumentElement().getNodeName().equalsIgnoreCase(MODELS_ELEMENT)) ||
+ (doc.getDocumentElement().getNodeName().equalsIgnoreCase(NAMED_QUERIES_ELEMENT)) ) {
+ // The complete set of models/named-queries were contained in this artifact
+ NodeList nodeList = doc.getDocumentElement().getChildNodes();
+ for (int i = 0; i < nodeList.getLength(); i++) {
+ Node childNode = nodeList.item(i);
+ if ( (childNode.getNodeName().equalsIgnoreCase(MODEL_ELEMENT)) ||
+ (childNode.getNodeName().equalsIgnoreCase(NAMED_QUERY_ELEMENT)) ) {
+ String modelPayload = nodeToString(childNode);
+ ModelArtifact model = parseModel(childNode, modelPayload);
+ if (model != null) {
+ modelList.add(model);
+ }
+ else {
+ logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Unable to parse artifact " + artifactName);
+ modelList.clear();
+ break;
+ }
+ }
+ }
+ }
+ }
+ catch (Exception ex) {
+ logger.error(ModelLoaderMsgs.ARTIFACT_PARSE_ERROR, "Unable to parse artifact " + artifactName + ": " + ex.getLocalizedMessage());
+ }
+
+ return modelList;
+ }
+
+ private void printDetails(Node modelVer) throws TransformerException {
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, nodeToString(modelVer));
+ }
+
+ private ModelArtifact parseModel(Node modelNode, String payload) {
+ ModelArtifact model = new ModelArtifact();
+ model.setPayload(payload);
+
+ if (modelNode.getNodeName().equalsIgnoreCase(MODEL_ELEMENT)) {
+ //compare with Model-ver
+ model.setType(ArtifactType.MODEL);
+ }
+ else {
+ model.setType(ArtifactType.NAMED_QUERY);
+ }
+
+ Element e = (Element)modelNode;
+ model.setModelNamespace(e.getAttribute("xmlns"));
+
+ parseNode(modelNode, model);
+
+ if (model.getModelInvariantId() == null && model.getNameVersionId() == null) {
+ return null;
+ }
+
+ return model;
+ }
+
+ private void parseNode(Node node, ModelArtifact model) {
+
+ if(node.getNodeName().equalsIgnoreCase(MODEL_NAME_VERSION_ID)){
+ model.setModelVerId(node.getTextContent().trim());
+ model.setV9Artifact(false);
+ }
+ else if(node.getNodeName().equalsIgnoreCase("model-id")){
+ model.setModelInvariantId(node.getTextContent().trim());
+ model.setV9Artifact(false);
+ }
+
+ else if (node.getNodeName().equalsIgnoreCase(MODEL_INVARIANT_ID)) {
+ model.setModelInvariantId(node.getTextContent().trim());
+ }
+ else if (node.getNodeName().equalsIgnoreCase(MODEL_VERSION_ID)) {
+ model.setModelVerId(node.getTextContent().trim());
+ //Change to Model Invariant Id
+ }
+ else if (node.getNodeName().equalsIgnoreCase(NAMED_QUERY_VERSION_ID)) {
+ model.setNameVersionId(node.getTextContent().trim());
+ }
+ else if (node.getNodeName().equalsIgnoreCase(RELATIONSHIP_DATA)) {
+ parseRelationshipNode(node, model);
+ if(model.getModelModelInvariantId()!=null && model.getModelVerModelVersionId()!=null && !model.getModelModelInvariantId().isEmpty() && !model.getModelVerModelVersionId().isEmpty()){
+ model.addDependentModelId(model.getModelModelInvariantId() + "|" + model.getModelVerModelVersionId());
+ model.setModelModelInvariantId("");
+ model.setModelVerModelVersionId("");
+ }
+ }
+ else {
+
+ if (node.getNodeName().equalsIgnoreCase(MODEL_VER)) {
+ model.setModelVer(node);
+ if ( (model.getModelNamespace() != null) && (!model.getModelNamespace().isEmpty()) ) {
+ Element e = (Element) node;
+ e.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns", model.getModelNamespace());
+ }
+ }
+
+ NodeList nodeList = node.getChildNodes();
+
+ for (int i = 0; i < nodeList.getLength(); i++) {
+ Node childNode = nodeList.item(i);
+ parseNode(childNode, model);
+ }
+ }
+ }
+
+ private void parseRelationshipNode(Node node, ModelArtifact model) {
+
+ //invariant-id comes before model-version-id .. create a list of values
+ String key = null;
+ String value = null;
+ String modelVersionIdKey=null;
+ String modelInvariantIdIdKey=null;
+ String modelVersionIdValue=null;
+ String modelInvariantIdIdValue=null;
+
+ NodeList nodeList = node.getChildNodes();
+ for (int i = 0; i < nodeList.getLength(); i++) {
+ Node childNode = nodeList.item(i);
+
+
+ if (childNode.getNodeName().equalsIgnoreCase(RELATIONSHIP_KEY)) {
+ key = childNode.getTextContent().trim();
+ if(key.equalsIgnoreCase(MODEL_VER_ELEMENT_RELATIONSHIP_KEY)){
+ modelVersionIdKey = key;
+ }
+ else if(key.equalsIgnoreCase(MODEL_ELEMENT_RELATIONSHIP_KEY)){
+ modelInvariantIdIdKey = key;
+ }
+ }
+ else if (childNode.getNodeName().equalsIgnoreCase(RELATIONSHIP_VALUE)) {
+ value = childNode.getTextContent().trim();
+ if(modelVersionIdKey!=null){
+ modelVersionIdValue = value;
+ model.setModelVerModelVersionId(modelVersionIdValue);
+ }
+ else if(modelInvariantIdIdKey!=null){
+ modelInvariantIdIdValue = value;
+ model.setModelModelInvariantId(modelInvariantIdIdValue);
+ }
+
+ }
+ }
+
+ if ( (key != null) && (key.equalsIgnoreCase(MODEL_ELEMENT_RELATIONSHIP_KEY )) &&
+ (model.isV9Artifact == false ||ArtifactType.NAMED_QUERY.equals(model.getType())) ) {
+ if (value != null) {
+ model.addDependentModelId(value);
+ }
+ }
+ }
+
+ private String nodeToString(Node node) throws TransformerException {
+ StringWriter sw = new StringWriter();
+ Transformer t = TransformerFactory.newInstance().newTransformer();
+ t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+ t.transform(new DOMSource(node), new StreamResult(sw));
+ return sw.toString();
+ }
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.entity.model;\r
-\r
-import jline.internal.Log;\r
-\r
-import org.openecomp.modelloader.entity.Artifact;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.HashMap;\r
-import java.util.HashSet;\r
-import java.util.Iterator;\r
-import java.util.List;\r
-\r
-/**\r
- * Utility class to sort the given Models according to their dependencies.\r
- * Example: Given a list of Models [A, B, C] where B depends on A, and A depends\r
- * on C, the sorted result will be [C, A, B]\r
- */\r
-public class ModelSorter {\r
-\r
- /**\r
- * Wraps a Model object to form dependencies other Models using Edges.\r
- */\r
- static class Node {\r
- private final ModelArtifact model;\r
- private final HashSet<Edge> inEdges;\r
- private final HashSet<Edge> outEdges;\r
-\r
- public Node(ModelArtifact model) {\r
- this.model = model;\r
- inEdges = new HashSet<Edge>();\r
- outEdges = new HashSet<Edge>();\r
- }\r
-\r
- public Node addEdge(Node node) {\r
- Edge edge = new Edge(this, node);\r
- outEdges.add(edge);\r
- node.inEdges.add(edge);\r
- return this;\r
- }\r
-\r
- @Override\r
- public String toString() {\r
- return model.getModelInvariantId();\r
- }\r
-\r
- @Override\r
- public boolean equals(Object other) {\r
- ModelArtifact otherModel = ((Node) other).model;\r
- return this.model.getModelInvariantId().equals(otherModel.getModelInvariantId());\r
- }\r
-\r
- @Override\r
- public int hashCode() {\r
- return this.model.getModelInvariantId().hashCode();\r
-\r
- }\r
- }\r
-\r
- /**\r
- * Represents a dependency between two Nodes.\r
- */\r
- static class Edge {\r
- public final Node from;\r
- public final Node to;\r
-\r
- public Edge(Node from, Node to) {\r
- this.from = from;\r
- this.to = to;\r
- }\r
-\r
- @Override\r
- public boolean equals(Object obj) {\r
- Edge edge = (Edge) obj;\r
- return edge.from == from && edge.to == to;\r
- }\r
- }\r
-\r
- /**\r
- * Returns the list of models sorted by order of dependency.\r
- * \r
- * @param originalList\r
- * the list that needs to be sorted\r
- * @return a list of sorted models\r
- */\r
- public List<Artifact> sort(List<Artifact> originalList) {\r
-\r
- if (originalList.size() <= 1) {\r
- return originalList;\r
- }\r
-\r
- Collection<Node> nodes = createNodes(originalList);\r
- Collection<Node> sortedNodes = sortNodes(nodes);\r
-\r
- List<Artifact> sortedModelsList = new ArrayList<Artifact>(sortedNodes.size());\r
- for (Node node : sortedNodes) {\r
- sortedModelsList.add(node.model);\r
- }\r
-\r
- return sortedModelsList;\r
- }\r
-\r
- /**\r
- * Create nodes from the list of models and their dependencies.\r
- * \r
- * @param models\r
- * what the nodes creation is based upon\r
- * @return Collection of Node objects\r
- */\r
- private Collection<Node> createNodes(Collection<Artifact> models) {\r
-\r
- // load list of models into a map, so we can later replace referenceIds with\r
- // real Models\r
- HashMap<String, ModelArtifact> versionIdToModelMap = new HashMap<String, ModelArtifact>();\r
- for (Artifact art : models) {\r
- ModelArtifact ma = (ModelArtifact) art;\r
- versionIdToModelMap.put(ma.getModelModelVerCombinedKey(), ma);\r
- }\r
-\r
- HashMap<String, Node> nodes = new HashMap<String, Node>();\r
- // create a node for each model and its referenced models\r
- for (Artifact art : models) {\r
- ModelArtifact model = (ModelArtifact) art;\r
-\r
- // node might have been created by another model referencing it\r
- Node node = nodes.get(model.getModelModelVerCombinedKey());\r
-\r
- if (null == node) {\r
- node = new Node(model);\r
- nodes.put(model.getModelModelVerCombinedKey(), node);\r
- }\r
-\r
- for (String referencedModelId : model.getDependentModelIds()) {\r
- // node might have been created by another model referencing it\r
- Node referencedNode = nodes.get(referencedModelId);\r
-\r
- if (null == referencedNode) {\r
- // create node\r
- ModelArtifact referencedModel = versionIdToModelMap.get(referencedModelId);\r
- if (referencedModel == null) {\r
- Log.debug("ignoring " + referencedModelId);\r
- continue; // referenced model not supplied, no need to sort it\r
- }\r
- referencedNode = new Node(referencedModel);\r
- nodes.put(referencedModelId, referencedNode);\r
- }\r
- referencedNode.addEdge(node);\r
- }\r
- }\r
-\r
- return nodes.values();\r
- }\r
-\r
- /**\r
- * Sorts the given Nodes by order of dependency.\r
- * \r
- * @param originalList\r
- * the collection of nodes to be sorted\r
- * @return a sorted collection of the given nodes\r
- */\r
- private Collection<Node> sortNodes(Collection<Node> unsortedNodes) {\r
-\r
- // L <- Empty list that will contain the sorted elements\r
- ArrayList<Node> nodeList = new ArrayList<Node>();\r
-\r
- // S <- Set of all nodes with no incoming edges\r
- HashSet<Node> nodeSet = new HashSet<Node>();\r
- for (Node unsortedNode : unsortedNodes) {\r
- if (unsortedNode.inEdges.size() == 0) {\r
- nodeSet.add(unsortedNode);\r
- }\r
- }\r
-\r
- // while S is non-empty do\r
- while (!nodeSet.isEmpty()) {\r
- // remove a node n from S\r
- Node node = nodeSet.iterator().next();\r
- nodeSet.remove(node);\r
-\r
- // insert n into L\r
- nodeList.add(node);\r
-\r
- // for each node m with an edge e from n to m do\r
- for (Iterator<Edge> it = node.outEdges.iterator(); it.hasNext();) {\r
- // remove edge e from the graph\r
- Edge edge = it.next();\r
- Node to = edge.to;\r
- it.remove();// Remove edge from n\r
- to.inEdges.remove(edge);// Remove edge from m\r
-\r
- // if m has no other incoming edges then insert m into S\r
- if (to.inEdges.isEmpty()) {\r
- nodeSet.add(to);\r
- }\r
- }\r
- }\r
- // Check to see if all edges are removed\r
- boolean cycle = false;\r
- for (Node node : unsortedNodes) {\r
- if (!node.inEdges.isEmpty()) {\r
- cycle = true;\r
- break;\r
- }\r
- }\r
- if (cycle) {\r
- throw new RuntimeException(\r
- "Circular dependency present between models, topological sort not possible");\r
- }\r
-\r
- return nodeList;\r
- }\r
-\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.entity.model;
+
+import jline.internal.Log;
+
+import org.openecomp.modelloader.entity.Artifact;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Utility class to sort the given Models according to their dependencies.
+ * Example: Given a list of Models [A, B, C] where B depends on A, and A depends
+ * on C, the sorted result will be [C, A, B]
+ */
+public class ModelSorter {
+
+ /**
+ * Wraps a Model object to form dependencies other Models using Edges.
+ */
+ static class Node {
+ private final ModelArtifact model;
+ private final HashSet<Edge> inEdges;
+ private final HashSet<Edge> outEdges;
+
+ public Node(ModelArtifact model) {
+ this.model = model;
+ inEdges = new HashSet<Edge>();
+ outEdges = new HashSet<Edge>();
+ }
+
+ public Node addEdge(Node node) {
+ Edge edge = new Edge(this, node);
+ outEdges.add(edge);
+ node.inEdges.add(edge);
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ if (model.getModelInvariantId() == null) {
+ return model.getNameVersionId();
+ }
+
+ return model.getModelInvariantId();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ ModelArtifact otherModel = ((Node) other).model;
+ String modelId1 = this.model.getModelInvariantId();
+ if (modelId1 == null) {
+ modelId1 = this.model.getNameVersionId();
+ }
+
+ String modelId2 = otherModel.getModelInvariantId();
+ if (modelId2 == null) {
+ modelId2 = otherModel.getNameVersionId();
+ }
+
+ return modelId1.equals(modelId2);
+ }
+
+ @Override
+ public int hashCode() {
+ if (this.model.getModelInvariantId() == null) {
+ return this.model.getNameVersionId().hashCode();
+ }
+
+ return this.model.getModelInvariantId().hashCode();
+ }
+ }
+
+ /**
+ * Represents a dependency between two Nodes.
+ */
+ static class Edge {
+ public final Node from;
+ public final Node to;
+
+ public Edge(Node from, Node to) {
+ this.from = from;
+ this.to = to;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ Edge edge = (Edge) obj;
+ return edge.from == from && edge.to == to;
+ }
+ }
+
+ /**
+ * Returns the list of models sorted by order of dependency.
+ *
+ * @param originalList
+ * the list that needs to be sorted
+ * @return a list of sorted models
+ */
+ public List<Artifact> sort(List<Artifact> originalList) {
+
+ if (originalList.size() <= 1) {
+ return originalList;
+ }
+
+ Collection<Node> nodes = createNodes(originalList);
+ Collection<Node> sortedNodes = sortNodes(nodes);
+
+ List<Artifact> sortedModelsList = new ArrayList<Artifact>(sortedNodes.size());
+ for (Node node : sortedNodes) {
+ sortedModelsList.add(node.model);
+ }
+
+ return sortedModelsList;
+ }
+
+ /**
+ * Create nodes from the list of models and their dependencies.
+ *
+ * @param models
+ * what the nodes creation is based upon
+ * @return Collection of Node objects
+ */
+ private Collection<Node> createNodes(Collection<Artifact> models) {
+
+ // load list of models into a map, so we can later replace referenceIds with
+ // real Models
+ HashMap<String, ModelArtifact> versionIdToModelMap = new HashMap<String, ModelArtifact>();
+ for (Artifact art : models) {
+ ModelArtifact ma = (ModelArtifact) art;
+ versionIdToModelMap.put(ma.getModelModelVerCombinedKey(), ma);
+ }
+
+ HashMap<String, Node> nodes = new HashMap<String, Node>();
+ // create a node for each model and its referenced models
+ for (Artifact art : models) {
+
+ ModelArtifact model = (ModelArtifact) art;
+
+ // node might have been created by another model referencing it
+ Node node = nodes.get(model.getModelModelVerCombinedKey());
+
+ if (null == node) {
+ node = new Node(model);
+ nodes.put(model.getModelModelVerCombinedKey(), node);
+ }
+
+ for (String referencedModelId : model.getDependentModelIds()) {
+ // node might have been created by another model referencing it
+ Node referencedNode = nodes.get(referencedModelId);
+
+ if (null == referencedNode) {
+ // create node
+ ModelArtifact referencedModel = versionIdToModelMap.get(referencedModelId);
+ if (referencedModel == null) {
+ Log.debug("ignoring " + referencedModelId);
+ continue; // referenced model not supplied, no need to sort it
+ }
+ referencedNode = new Node(referencedModel);
+ nodes.put(referencedModelId, referencedNode);
+ }
+ referencedNode.addEdge(node);
+ }
+ }
+
+ return nodes.values();
+ }
+
+ /**
+ * Sorts the given Nodes by order of dependency.
+ *
+ * @param originalList
+ * the collection of nodes to be sorted
+ * @return a sorted collection of the given nodes
+ */
+ private Collection<Node> sortNodes(Collection<Node> unsortedNodes) {
+ // L <- Empty list that will contain the sorted elements
+ ArrayList<Node> nodeList = new ArrayList<Node>();
+
+ // S <- Set of all nodes with no incoming edges
+ HashSet<Node> nodeSet = new HashSet<Node>();
+ for (Node unsortedNode : unsortedNodes) {
+ if (unsortedNode.inEdges.size() == 0) {
+ nodeSet.add(unsortedNode);
+ }
+ }
+
+ // while S is non-empty do
+ while (!nodeSet.isEmpty()) {
+ // remove a node n from S
+ Node node = nodeSet.iterator().next();
+ nodeSet.remove(node);
+
+ // insert n into L
+ nodeList.add(node);
+
+ // for each node m with an edge e from n to m do
+ for (Iterator<Edge> it = node.outEdges.iterator(); it.hasNext();) {
+ // remove edge e from the graph
+ Edge edge = it.next();
+ Node to = edge.to;
+ it.remove();// Remove edge from n
+ to.inEdges.remove(edge);// Remove edge from m
+
+ // if m has no other incoming edges then insert m into S
+ if (to.inEdges.isEmpty()) {
+ nodeSet.add(to);
+ }
+ }
+ }
+ // Check to see if all edges are removed
+ boolean cycle = false;
+ for (Node node : unsortedNodes) {
+ if (!node.inEdges.isEmpty()) {
+ cycle = true;
+ break;
+ }
+ }
+ if (cycle) {
+ throw new RuntimeException(
+ "Circular dependency present between models, topological sort not possible");
+ }
+
+ return nodeList;
+ }
+
+
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.service;\r
-\r
-import org.openecomp.sdc.api.IDistributionClient;\r
-import org.openecomp.sdc.api.results.IDistributionClientResult;\r
-import org.openecomp.sdc.impl.DistributionClientFactory;\r
-import org.openecomp.sdc.utils.DistributionActionResultEnum;\r
-\r
-import org.openecomp.cl.api.Logger;\r
-import org.openecomp.cl.eelf.LoggerFactory;\r
-import org.openecomp.modelloader.config.ModelLoaderConfig;\r
-import org.openecomp.modelloader.entity.model.ModelArtifactHandler;\r
-import org.openecomp.modelloader.notification.EventCallback;\r
-\r
-import java.io.FileInputStream;\r
-import java.io.IOException;\r
-import java.util.Properties;\r
-\r
-import javax.annotation.PreDestroy;\r
-import javax.servlet.http.HttpServletRequest;\r
-import javax.ws.rs.core.Response;\r
-\r
-/**\r
- * Service class in charge of managing the negotiating model loading\r
- * capabilities between AAI and an ASDC.\r
- */\r
-public class ModelLoaderService implements ModelLoaderInterface {\r
- \r
- protected static final String FILESEP = (System.getProperty("file.separator") == null) ? "/"\r
- : System.getProperty("file.separator");\r
-\r
- protected static final String CONFIG_DIR = System.getProperty("CONFIG_HOME") + FILESEP;\r
- protected static final String CONFIG_AUTH_LOCATION = CONFIG_DIR + "auth" + FILESEP;\r
- protected static final String CONFIG_FILE = CONFIG_DIR + "model-loader.properties";\r
-\r
- private IDistributionClient client;\r
- private ModelLoaderConfig config;\r
-\r
- static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());\r
-\r
- /**\r
- * Responsible for loading configuration files and calling initialization.\r
- */\r
- public ModelLoaderService() {\r
- start();\r
- }\r
-\r
- protected void start() {\r
- // Load model loader system configuration\r
- logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);\r
- Properties configProperties = new Properties();\r
- try {\r
- configProperties.load(new FileInputStream(CONFIG_FILE));\r
- } catch (IOException e) {\r
- String errorMsg = "Failed to load configuration: " + e.getMessage();\r
- logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);\r
- shutdown();\r
- }\r
-\r
- config = new ModelLoaderConfig(configProperties, CONFIG_AUTH_LOCATION);\r
- init();\r
- }\r
-\r
- @Override\r
- public void finalize() {\r
- preShutdownOperations();\r
- }\r
- \r
- /**\r
- * Responsible for stopping the connection to the distribution client before\r
- * the resource is destroyed.\r
- */\r
- protected void preShutdownOperations() {\r
- logger.info(ModelLoaderMsgs.STOPPING_CLIENT);\r
- if (client != null) {\r
- client.stop();\r
- }\r
- }\r
-\r
- /**\r
- * Responsible for loading configuration files, initializing model\r
- * distribution clients, and starting them.\r
- */\r
- protected void init() {\r
- // Initialize distribution client\r
- logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");\r
- client = DistributionClientFactory.createDistributionClient();\r
- IDistributionClientResult initResult = client.init(config, new EventCallback(client, config));\r
- if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {\r
- String errorMsg = "Failed to initialize distribution client: "\r
- + initResult.getDistributionMessageResult();\r
- logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);\r
- shutdown();\r
- }\r
-\r
- // Start distribution client\r
- logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");\r
- IDistributionClientResult startResult = client.start();\r
- if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {\r
- String errorMsg = "Failed to start distribution client: "\r
- + startResult.getDistributionMessageResult();\r
- logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);\r
- shutdown();\r
- }\r
-\r
- logger.debug(ModelLoaderMsgs.INITIALIZING,\r
- "Succcessfully loaded service: " + this.getClass().getSimpleName());\r
- }\r
-\r
- /**\r
- * Shut down the process.\r
- */\r
- private void shutdown() {\r
- preShutdownOperations();\r
-\r
- // TODO: Find a better way to shut down the model loader.\r
- try {\r
- // Give logs time to write to file\r
- Thread.sleep(2000);\r
- } catch (InterruptedException e) {\r
- // Nothing we can do at this point\r
- }\r
-\r
- Runtime.getRuntime().halt(1);\r
- }\r
-\r
- /** (non-Javadoc)\r
- * @see org.openecomp.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)\r
- */\r
- @Override\r
- public Response loadModel(String modelid) {\r
- Response response = Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();\r
-\r
- return response;\r
- }\r
-\r
- /** (non-Javadoc)\r
- * @see org.openecomp.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)\r
- */\r
- @Override\r
- public Response saveModel(String modelid, String modelname) {\r
- Response response = Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}")\r
- .build();\r
-\r
- return response;\r
- }\r
-\r
- @Override\r
- public Response ingestModel(String modelid, HttpServletRequest req, String payload)\r
- throws IOException {\r
- Response response;\r
-\r
- if (config.getIngestSimulatorEnabled()) {\r
- logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");\r
-\r
- ModelArtifactHandler handler = new ModelArtifactHandler(config);\r
- handler.loadModelTest(payload.getBytes());\r
-\r
- response = Response.ok().build();\r
- } else {\r
- logger.debug("Simulation interface disabled");\r
- response = Response.serverError().build();\r
- }\r
-\r
- return response;\r
- }\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.service;
+
+import org.openecomp.sdc.api.IDistributionClient;
+import org.openecomp.sdc.api.results.IDistributionClientResult;
+import org.openecomp.sdc.impl.DistributionClientFactory;
+import org.openecomp.sdc.utils.DistributionActionResultEnum;
+
+import org.openecomp.cl.api.Logger;
+import org.openecomp.cl.eelf.LoggerFactory;
+import org.openecomp.modelloader.config.ModelLoaderConfig;
+import org.openecomp.modelloader.entity.model.ModelArtifactHandler;
+import org.openecomp.modelloader.notification.EventCallback;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Date;
+import java.util.Properties;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Response;
+
+/**
+ * Service class in charge of managing the negotiating model loading
+ * capabilities between AAI and an ASDC.
+ */
+public class ModelLoaderService implements ModelLoaderInterface {
+
+ protected static final String FILESEP = (System.getProperty("file.separator") == null) ? "/"
+ : System.getProperty("file.separator");
+
+ protected static final String CONFIG_DIR = System.getProperty("CONFIG_HOME") + FILESEP;
+ protected static final String CONFIG_AUTH_LOCATION = CONFIG_DIR + "auth" + FILESEP;
+ protected static final String CONFIG_FILE = CONFIG_DIR + "model-loader.properties";
+
+ private IDistributionClient client;
+ private ModelLoaderConfig config;
+ private Timer timer = null;
+
+ static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
+
+ /**
+ * Responsible for loading configuration files and calling initialization.
+ */
+ public ModelLoaderService() {
+ start();
+ }
+
+ protected void start() {
+ // Load model loader system configuration
+ logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
+ Properties configProperties = new Properties();
+ try {
+ configProperties.load(new FileInputStream(CONFIG_FILE));
+ } catch (IOException e) {
+ String errorMsg = "Failed to load configuration: " + e.getMessage();
+ logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+ shutdown();
+ }
+
+ config = new ModelLoaderConfig(configProperties, CONFIG_AUTH_LOCATION);
+ init();
+ }
+
+ @Override
+ public void finalize() {
+ preShutdownOperations();
+ }
+
+ /**
+ * Responsible for stopping the connection to the distribution client before
+ * the resource is destroyed.
+ */
+ protected void preShutdownOperations() {
+ logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
+ if (client != null) {
+ client.stop();
+ }
+ }
+
+ /**
+ * Responsible for loading configuration files, initializing model
+ * distribution clients, and starting them.
+ */
+ protected void init() {
+ // Initialize distribution client
+ logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
+ client = DistributionClientFactory.createDistributionClient();
+ EventCallback callback = new EventCallback(client, config);
+
+ IDistributionClientResult initResult = client.init(config, callback);
+
+ if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ String errorMsg = "Failed to initialize distribution client: "
+ + initResult.getDistributionMessageResult();
+ logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+
+ // Kick off a timer to retry the SDC connection
+ timer = new Timer();
+ TimerTask task = new SdcConnectionJob(client, config, callback, timer);
+ timer.schedule(task, new Date(), 60000);
+ }
+ else {
+ // Start distribution client
+ logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
+ IDistributionClientResult startResult = client.start();
+ if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ String errorMsg = "Failed to start distribution client: "
+ + startResult.getDistributionMessageResult();
+ logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+
+ // Kick off a timer to retry the SDC connection
+ timer = new Timer();
+ TimerTask task = new SdcConnectionJob(client, config, callback, timer);
+ timer.schedule(task, new Date(), 60000);
+ }
+ else {
+ logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
+ }
+ }
+ }
+
+ /**
+ * Shut down the process.
+ */
+ private void shutdown() {
+ preShutdownOperations();
+
+ // TODO: Find a better way to shut down the model loader.
+ try {
+ // Give logs time to write to file
+ Thread.sleep(2000);
+ } catch (InterruptedException e) {
+ // Nothing we can do at this point
+ }
+
+ Runtime.getRuntime().halt(1);
+ }
+
+ /** (non-Javadoc)
+ * @see org.openecomp.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
+ */
+ @Override
+ public Response loadModel(String modelid) {
+ Response response = Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
+
+ return response;
+ }
+
+ /** (non-Javadoc)
+ * @see org.openecomp.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
+ */
+ @Override
+ public Response saveModel(String modelid, String modelname) {
+ Response response = Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}")
+ .build();
+
+ return response;
+ }
+
+ @Override
+ public Response ingestModel(String modelid, HttpServletRequest req, String payload)
+ throws IOException {
+ Response response;
+
+ if (config.getIngestSimulatorEnabled()) {
+ logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
+
+ ModelArtifactHandler handler = new ModelArtifactHandler(config);
+ handler.loadModelTest(payload.getBytes());
+
+ response = Response.ok().build();
+ } else {
+ logger.debug("Simulation interface disabled");
+ response = Response.serverError().build();
+ }
+
+ return response;
+ }
+}
--- /dev/null
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.service;
+
+import java.util.Date;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import org.openecomp.cl.api.Logger;
+import org.openecomp.cl.eelf.LoggerFactory;
+import org.openecomp.modelloader.config.ModelLoaderConfig;
+import org.openecomp.modelloader.notification.EventCallback;
+import org.openecomp.sdc.api.IDistributionClient;
+import org.openecomp.sdc.api.results.IDistributionClientResult;
+import org.openecomp.sdc.utils.DistributionActionResultEnum;
+
+public class SdcConnectionJob extends TimerTask {
+ static Logger logger = LoggerFactory.getInstance().getLogger(SdcConnectionJob.class.getName());
+
+ private IDistributionClient client;
+ private ModelLoaderConfig config;
+ private EventCallback callback;
+ private Timer timer;
+
+ public SdcConnectionJob(IDistributionClient client,
+ ModelLoaderConfig config,
+ EventCallback callback,
+ Timer timer) {
+ this.client = client;
+ this.timer = timer;
+ this.callback = callback;
+ this.config = config;
+ }
+
+ @Override
+ public void run() {
+
+ IDistributionClientResult initResult = client.init(config, callback);
+
+ if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ String errorMsg = "Failed to initialize distribution client: "
+ + initResult.getDistributionMessageResult();
+ logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+ return;
+ }
+
+ IDistributionClientResult startResult = client.start();
+ if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
+ String errorMsg = "Failed to start distribution client: "
+ + startResult.getDistributionMessageResult();
+ logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
+ return;
+ }
+
+ // Success. Cancel the timer job
+ timer.cancel();
+ logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
+ }
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.config;\r
-\r
-import static org.junit.Assert.assertEquals;\r
-import static org.junit.Assert.assertFalse;\r
-\r
-import java.io.FileInputStream;\r
-import java.io.IOException;\r
-import java.util.List;\r
-import java.util.Properties;\r
-\r
-import org.eclipse.jetty.util.security.Password;\r
-import org.junit.Test;\r
-import org.openecomp.modelloader.restclient.AaiRestClient;\r
-\r
-import org.openecomp.sdc.utils.ArtifactTypeEnum;\r
-\r
-public class ModelLoaderConfigTest {\r
-\r
- @Test\r
- public void testYangModelArtifactType() {\r
- Properties props = new Properties();\r
- props.setProperty("ml.distribution.ARTIFACT_TYPES",\r
- "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG");\r
- ModelLoaderConfig config = new ModelLoaderConfig(props, null);\r
-\r
- List<String> types = config.getRelevantArtifactTypes();\r
-\r
- System.out.println("ArtifactType: " + types.get(0));\r
- assertEquals(0,\r
- types.get(0).compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString()));\r
-\r
- System.out.println("ArtifactType: " + types.get(1));\r
- assertEquals(0, types.get(1).compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString()));\r
-\r
- System.out.println("ArtifactType: " + types.get(2));\r
- assertEquals(0, types.get(2).compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString()));\r
-\r
- assertEquals(3, types.size());\r
- }\r
-\r
- @Test\r
- public void testDecryptPassword() {\r
- Properties props = new Properties();\r
- String testPass = "youshallnotpass";\r
- String encryptedTestPass = Password.obfuscate(testPass);\r
-\r
- System.out.println("Encrypt " + testPass + " ==> " + encryptedTestPass);\r
-\r
- props.put(ModelLoaderConfig.PROP_ML_DISTRIBUTION_PASSWORD, encryptedTestPass);\r
- ModelLoaderConfig config = new ModelLoaderConfig(props, null);\r
-\r
- assertEquals(testPass, config.getPassword());\r
- }\r
-\r
- @Test\r
- public void testDecryptKeystorePassword() {\r
- Properties props = new Properties();\r
- String testPass = "youshallnotpass";\r
- String encryptedTestPass = Password.obfuscate(testPass);\r
-\r
- System.out.println("Encrypt " + testPass + " ==> " + encryptedTestPass);\r
-\r
- props.put(ModelLoaderConfig.PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD, encryptedTestPass);\r
- ModelLoaderConfig config = new ModelLoaderConfig(props, null);\r
-\r
- assertEquals(testPass, config.getKeyStorePassword());\r
- }\r
-\r
- @Test\r
- public void testDecryptAAIPassword() {\r
-\r
- Properties props = new Properties();\r
- String testPassword = "myvoiceismypassword";\r
- String encryptedTestPassword = Password.obfuscate(testPassword);\r
-\r
- props.put(ModelLoaderConfig.PROP_AAI_AUTHENTICATION_PASSWORD, encryptedTestPassword);\r
- ModelLoaderConfig config = new ModelLoaderConfig(props, null);\r
-\r
- assertEquals(testPassword, config.getAaiAuthenticationPassword());\r
- }\r
-\r
- @Test\r
- public void testNoAAIAuth() throws IOException {\r
-\r
- Properties props = new Properties();\r
- props.load(\r
- new FileInputStream("src/test/resources/model-loader-empty-auth-password.properties"));\r
-\r
- ModelLoaderConfig config = new ModelLoaderConfig(props, null);\r
- AaiRestClient aaiClient = new AaiRestClient(config);\r
-\r
- assertFalse("Empty AAI Password should result in no basic authentication",\r
- aaiClient.useBasicAuth());\r
-\r
- props.load(new FileInputStream("src/test/resources/model-loader-no-auth-password.properties"));\r
- config = new ModelLoaderConfig(props, null);\r
- aaiClient = new AaiRestClient(config);\r
-\r
- assertFalse("No AAI Password should result in no basic authentication",\r
- aaiClient.useBasicAuth());\r
- }\r
- \r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.config;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.List;
+import java.util.Properties;
+
+import org.eclipse.jetty.util.security.Password;
+import org.junit.Test;
+import org.openecomp.modelloader.restclient.AaiRestClient;
+
+import org.openecomp.sdc.utils.ArtifactTypeEnum;
+
+public class ModelLoaderConfigTest {
+
+ @Test
+ public void testYangModelArtifactType() {
+ Properties props = new Properties();
+ props.setProperty("ml.distribution.ARTIFACT_TYPES",
+ "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG");
+ ModelLoaderConfig config = new ModelLoaderConfig(props, null);
+
+ List<String> types = config.getRelevantArtifactTypes();
+
+ System.out.println("ArtifactType: " + types.get(0));
+ assertEquals(0,
+ types.get(0).compareToIgnoreCase(ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.toString()));
+
+ System.out.println("ArtifactType: " + types.get(1));
+ assertEquals(0, types.get(1).compareToIgnoreCase(ArtifactTypeEnum.MODEL_QUERY_SPEC.toString()));
+
+ System.out.println("ArtifactType: " + types.get(2));
+ assertEquals(0, types.get(2).compareToIgnoreCase(ArtifactTypeEnum.VNF_CATALOG.toString()));
+
+ assertEquals(3, types.size());
+ }
+
+ @Test
+ public void testDecryptPassword() {
+ Properties props = new Properties();
+ String testPass = "youshallnotpass";
+ String encryptedTestPass = Password.obfuscate(testPass);
+
+ System.out.println("Encrypt " + testPass + " ==> " + encryptedTestPass);
+
+ props.put(ModelLoaderConfig.PROP_ML_DISTRIBUTION_PASSWORD, encryptedTestPass);
+ ModelLoaderConfig config = new ModelLoaderConfig(props, null);
+
+ assertEquals(testPass, config.getPassword());
+ }
+
+ @Test
+ public void testDecryptKeystorePassword() {
+ Properties props = new Properties();
+ String testPass = "youshallnotpass";
+ String encryptedTestPass = Password.obfuscate(testPass);
+
+ System.out.println("Encrypt " + testPass + " ==> " + encryptedTestPass);
+
+ props.put(ModelLoaderConfig.PROP_ML_DISTRIBUTION_KEYSTORE_PASSWORD, encryptedTestPass);
+ ModelLoaderConfig config = new ModelLoaderConfig(props, null);
+
+ assertEquals(testPass, config.getKeyStorePassword());
+ }
+
+ @Test
+ public void testDecryptAAIPassword() {
+
+ Properties props = new Properties();
+ String testPassword = "myvoiceismypassword";
+ String encryptedTestPassword = Password.obfuscate(testPassword);
+
+ props.put(ModelLoaderConfig.PROP_AAI_AUTHENTICATION_PASSWORD, encryptedTestPassword);
+ ModelLoaderConfig config = new ModelLoaderConfig(props, null);
+
+ assertEquals(testPassword, config.getAaiAuthenticationPassword());
+ }
+
+ @Test
+ public void testNoAAIAuth() throws IOException {
+
+ Properties props = new Properties();
+ props.load(
+ new FileInputStream("src/test/resources/model-loader-empty-auth-password.properties"));
+
+ ModelLoaderConfig config = new ModelLoaderConfig(props, null);
+ AaiRestClient aaiClient = new AaiRestClient(config);
+
+ assertFalse("Empty AAI Password should result in no basic authentication",
+ aaiClient.useBasicAuth());
+
+ props.load(new FileInputStream("src/test/resources/model-loader-no-auth-password.properties"));
+ config = new ModelLoaderConfig(props, null);
+ aaiClient = new AaiRestClient(config);
+
+ assertFalse("No AAI Password should result in no basic authentication",
+ aaiClient.useBasicAuth());
+ }
+
+ @Test
+ public void testGetUrls() {
+ Properties props = new Properties();
+ props.put(ModelLoaderConfig.PROP_AAI_MODEL_RESOURCE_URL, "/aai/v*/service-design-and-creation/models/model/");
+ props.put(ModelLoaderConfig.PROP_AAI_NAMED_QUERY_RESOURCE_URL, "/aai/v*/service-design-and-creation/named-queries/named-query/");
+ ModelLoaderConfig config = new ModelLoaderConfig(props, null);
+
+ assertEquals("/aai/v9/service-design-and-creation/models/model/", config.getAaiModelUrl("v9"));
+ assertEquals("/aai/v10/service-design-and-creation/named-queries/named-query/", config.getAaiNamedQueryUrl("v10"));
+ }
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.entity.model;\r
-\r
-import static org.junit.Assert.assertEquals;\r
-import static org.junit.Assert.assertNotNull;\r
-\r
-import java.util.ArrayList;\r
-import java.util.Collections;\r
-import java.util.List;\r
-\r
-import org.junit.Test;\r
-import org.openecomp.modelloader.entity.Artifact;\r
-\r
-public class ModelSorterTest {\r
-\r
- @Test\r
- public void noModels() {\r
-\r
- List<Artifact> emptyList = Collections.emptyList();\r
-\r
- ModelSorter sorter = new ModelSorter();\r
- sorter = new ModelSorter();\r
-\r
- List<Artifact> sortedList = sorter.sort(emptyList);\r
- assertNotNull(sortedList);\r
- assertEquals(0, sortedList.size());\r
-\r
- }\r
-\r
- @Test\r
- public void singleModel() {\r
-\r
- List<Artifact> modelList = new ArrayList<Artifact>();\r
-\r
- ModelArtifact model = new ModelArtifact();\r
- model.setNameVersionId("aaaaa");\r
- model.addDependentModelId("xyz");\r
- modelList.add(model);\r
-\r
- ModelSorter sorter = new ModelSorter();\r
- sorter = new ModelSorter();\r
-\r
- List<Artifact> sortedList = sorter.sort(modelList);\r
- assertNotNull(sortedList);\r
- assertEquals(1, sortedList.size());\r
-\r
- }\r
-\r
- /**\r
- * \r
- * depends on depends on B ------> A -------> C\r
- *\r
- *\r
- * Input list = a, b, c Sorted list = c, a, b\r
- *\r
- */\r
- @Test\r
- public void multipleModels() {\r
-\r
- List<Artifact> modelList = new ArrayList<Artifact>();\r
-\r
- ModelArtifact aaaa = new ModelArtifact();\r
- aaaa.setModelInvariantId("aaaa");\r
- aaaa.setModelVerId("mvaaaa");\r
- aaaa.addDependentModelId("cccc|mvcccc");\r
-\r
- ModelArtifact bbbb = new ModelArtifact();\r
- bbbb.setModelInvariantId("bbbb");\r
- bbbb.setModelVerId("mvbbbb");\r
- bbbb.addDependentModelId("aaaa|mvaaaa");\r
-\r
- ModelArtifact cccc = new ModelArtifact();\r
- cccc.setModelInvariantId("cccc");\r
- cccc.setModelVerId("mvcccc");\r
-\r
- modelList.add(aaaa);\r
- modelList.add(bbbb);\r
- modelList.add(cccc);\r
-\r
- ModelSorter sorter = new ModelSorter();\r
- sorter = new ModelSorter();\r
-\r
- List<Artifact> sortedList = sorter.sort(modelList);\r
- assertNotNull(sortedList);\r
- assertEquals(3, sortedList.size());\r
-\r
- assertEquals(cccc, sortedList.get(0));\r
- assertEquals(aaaa, sortedList.get(1));\r
- assertEquals(bbbb, sortedList.get(2));\r
- }\r
-\r
- @Test(expected = RuntimeException.class)\r
- public void circularDependency() {\r
-\r
- List<Artifact> modelList = new ArrayList<Artifact>();\r
-\r
- ModelArtifact aaaa = new ModelArtifact();\r
- aaaa.setNameVersionId("aaaa");\r
- aaaa.addDependentModelId("bbbb");\r
-\r
- ModelArtifact bbbb = new ModelArtifact();\r
- bbbb.setNameVersionId("bbbb");\r
- bbbb.addDependentModelId("aaaa");\r
-\r
- modelList.add(aaaa);\r
- modelList.add(bbbb);\r
-\r
- ModelSorter sorter = new ModelSorter();\r
- sorter = new ModelSorter();\r
-\r
- List<Artifact> sortedList = sorter.sort(modelList);\r
- assertNotNull(sortedList);\r
- assertEquals(3, sortedList.size());\r
-\r
- }\r
-\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.entity.model;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.openecomp.modelloader.entity.Artifact;
+
+public class ModelSorterTest {
+
+ @Test
+ public void noModels() {
+
+ List<Artifact> emptyList = Collections.emptyList();
+
+ ModelSorter sorter = new ModelSorter();
+ sorter = new ModelSorter();
+
+ List<Artifact> sortedList = sorter.sort(emptyList);
+ assertNotNull(sortedList);
+ assertEquals(0, sortedList.size());
+
+ }
+
+ @Test
+ public void singleModel() {
+
+ List<Artifact> modelList = new ArrayList<Artifact>();
+
+ ModelArtifact model = new ModelArtifact();
+ model.setNameVersionId("aaaaa");
+ model.addDependentModelId("xyz");
+ modelList.add(model);
+
+ ModelSorter sorter = new ModelSorter();
+ sorter = new ModelSorter();
+
+ List<Artifact> sortedList = sorter.sort(modelList);
+ assertNotNull(sortedList);
+ assertEquals(1, sortedList.size());
+
+ }
+
+ /**
+ *
+ * depends on depends on B ------> A -------> C
+ *
+ *
+ * Input list = a, b, c Sorted list = c, a, b
+ *
+ */
+ @Test
+ public void multipleModels() {
+
+ List<Artifact> modelList = new ArrayList<Artifact>();
+
+ ModelArtifact aaaa = new ModelArtifact();
+ aaaa.setModelInvariantId("aaaa");
+ aaaa.setModelVerId("mvaaaa");
+ aaaa.addDependentModelId("cccc|mvcccc");
+
+ ModelArtifact bbbb = new ModelArtifact();
+ bbbb.setModelInvariantId("bbbb");
+ bbbb.setModelVerId("mvbbbb");
+ bbbb.addDependentModelId("aaaa|mvaaaa");
+
+ ModelArtifact cccc = new ModelArtifact();
+ cccc.setModelInvariantId("cccc");
+ cccc.setModelVerId("mvcccc");
+
+ modelList.add(aaaa);
+ modelList.add(bbbb);
+ modelList.add(cccc);
+
+ ModelSorter sorter = new ModelSorter();
+ sorter = new ModelSorter();
+
+ List<Artifact> sortedList = sorter.sort(modelList);
+ assertNotNull(sortedList);
+ assertEquals(3, sortedList.size());
+
+ assertEquals(cccc, sortedList.get(0));
+ assertEquals(aaaa, sortedList.get(1));
+ assertEquals(bbbb, sortedList.get(2));
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void circularDependency() {
+
+ List<Artifact> modelList = new ArrayList<Artifact>();
+
+ ModelArtifact aaaa = new ModelArtifact();
+ aaaa.setNameVersionId("aaaa");
+ aaaa.addDependentModelId("bbbb");
+
+ ModelArtifact bbbb = new ModelArtifact();
+ bbbb.setNameVersionId("bbbb");
+ bbbb.addDependentModelId("aaaa");
+
+ modelList.add(aaaa);
+ modelList.add(bbbb);
+
+ ModelSorter sorter = new ModelSorter();
+ sorter = new ModelSorter();
+
+ List<Artifact> sortedList = sorter.sort(modelList);
+ assertNotNull(sortedList);
+ assertEquals(2, sortedList.size());
+
+ }
+
+}
-/**\r
- * ============LICENSE_START=======================================================\r
- * Model Loader\r
- * ================================================================================\r
- * Copyright © 2017 AT&T Intellectual Property.\r
- * Copyright © 2017 Amdocs\r
- * All rights reserved.\r
- * ================================================================================\r
- * Licensed under the Apache License, Version 2.0 (the "License");\r
- * you may not use this file except in compliance with the License.\r
- * You may obtain a copy of the License at\r
- * http://www.apache.org/licenses/LICENSE-2.0\r
- * Unless required by applicable law or agreed to in writing, software\r
- * distributed under the License is distributed on an "AS IS" BASIS,\r
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
- * See the License for the specific language governing permissions and\r
- * limitations under the License.\r
- * ============LICENSE_END=========================================================\r
- *\r
- * ECOMP and OpenECOMP are trademarks\r
- * and service marks of AT&T Intellectual Property.\r
- */\r
-package org.openecomp.modelloader.restclient;\r
-\r
-import java.io.IOException;\r
-import java.nio.file.Files;\r
-import java.nio.file.Paths;\r
-\r
-import org.openecomp.modelloader.config.ModelLoaderConfig;\r
-import org.openecomp.modelloader.entity.ArtifactType;\r
-import org.openecomp.modelloader.entity.model.ModelArtifact;\r
-\r
-public class AaiRestClientTest {\r
-\r
- // This test requires a running A&AI system. Uncomment to test locally.\r
- /*\r
- * @Test public void testRestClient() throws Exception { final String\r
- * MODEL_FILE = "src/test/resources/models/vnf-model.xml";\r
- * \r
- * Properties props = new Properties();\r
- * props.setProperty("ml.distribution.ARTIFACT_TYPES",\r
- * "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG");\r
- * props.setProperty("ml.aai.BASE_URL", "https://127.0.0.1:4321");\r
- * props.setProperty("ml.aai.MODEL_URL",\r
- * "/aai/v8/service-design-and-creation/models/model/");\r
- * props.setProperty("ml.aai.KEYSTORE_FILE", "aai-client-cert.p12");\r
- * props.setProperty("ml.aai.KEYSTORE_PASSWORD",\r
- * "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o");\r
- * \r
- * ModelLoaderConfig config = new ModelLoaderConfig(props, "");\r
- * \r
- * String payload = readFile(MODEL_FILE); System.out.println("FILE:" +\r
- * payload);\r
- * \r
- * File xmlFile = new File(MODEL_FILE); DocumentBuilderFactory dbFactory =\r
- * DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder =\r
- * dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile);\r
- * \r
- * // Get the ID of the model String modelId = null; NodeList nodeList =\r
- * doc.getDocumentElement().getChildNodes(); for (int i = 0; i <\r
- * nodeList.getLength(); i++) { Node currentNode = nodeList.item(i); if\r
- * (currentNode.getNodeName().equals("model-name-version-id")) { modelId =\r
- * currentNode.getTextContent(); break; } }\r
- * \r
- * // Add the model try { ModelArtifact model = new ModelArtifact();\r
- * model.setNameVersionId(modelId); model.setType(ArtifactType.MODEL);\r
- * model.setPayload(payload);\r
- * \r
- * AAIRestClient aaiClient = new AAIRestClient(config);\r
- * \r
- * // GET model System.out.println("Calling GET API ..."); ClientResponse\r
- * getResponse = aaiClient.getResource(getURL(model, config),\r
- * "example-trans-id-0", AAIRestClient.MimeType.XML); System.out.println(\r
- * "GET result: " + getResponse.getStatus());\r
- * assertTrue(getResponse.getStatus() ==\r
- * Response.Status.NOT_FOUND.getStatusCode());\r
- * \r
- * // Add the model System.out.println("Calling PUT API ..."); ClientResponse\r
- * res = aaiClient.putResource(getURL(model, config), model.getPayload(),\r
- * "example-trans-id-1", AAIRestClient.MimeType.XML); System.out.println(\r
- * "PUT result: " + res.getStatus()); assertTrue(res.getStatus() ==\r
- * Response.Status.CREATED.getStatusCode());\r
- * \r
- * // Delete the model System.out.println("Calling DELETE API ..."); res =\r
- * aaiClient.getAndDeleteResource(getURL(model, config),\r
- * "example-trans-id-3"); System.out.println("DELETE result: " +\r
- * res.getStatus()); assertTrue(res.getStatus() ==\r
- * Response.Status.NO_CONTENT.getStatusCode()); } catch (Exception e) {\r
- * e.printStackTrace(); } }\r
- */\r
-\r
- static String readFile(String path) throws IOException {\r
- byte[] encoded = Files.readAllBytes(Paths.get(path));\r
- return new String(encoded);\r
- }\r
-\r
- private String getURL(ModelArtifact model, ModelLoaderConfig config) {\r
- String baseURL = config.getAaiBaseUrl().trim();\r
- String subURL = null;\r
- if (model.getType().equals(ArtifactType.MODEL)) {\r
- subURL = config.getAaiModelUrl().trim();\r
- } else {\r
- subURL = config.getAaiNamedQueryUrl().trim();\r
- }\r
-\r
- if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {\r
- baseURL = baseURL + "/";\r
- }\r
-\r
- if (baseURL.endsWith("/") && subURL.startsWith("/")) {\r
- baseURL = baseURL.substring(0, baseURL.length() - 1);\r
- }\r
-\r
- if (!subURL.endsWith("/")) {\r
- subURL = subURL + "/";\r
- }\r
-\r
- String url = baseURL + subURL + model.getNameVersionId();\r
- return url;\r
- }\r
-}\r
+/**
+ * ============LICENSE_START=======================================================
+ * Model Loader
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property.
+ * Copyright © 2017 Amdocs
+ * 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=========================================================
+ *
+ * ECOMP and OpenECOMP are trademarks
+ * and service marks of AT&T Intellectual Property.
+ */
+package org.openecomp.modelloader.restclient;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+import org.openecomp.modelloader.config.ModelLoaderConfig;
+import org.openecomp.modelloader.entity.ArtifactType;
+import org.openecomp.modelloader.entity.model.ModelArtifact;
+
+public class AaiRestClientTest {
+
+ // This test requires a running A&AI system. Uncomment to test locally.
+ /*
+ * @Test public void testRestClient() throws Exception { final String
+ * MODEL_FILE = "src/test/resources/models/vnf-model.xml";
+ *
+ * Properties props = new Properties();
+ * props.setProperty("ml.distribution.ARTIFACT_TYPES",
+ * "MODEL_INVENTORY_PROFILE,MODEL_QUERY_SPEC,VNF_CATALOG");
+ * props.setProperty("ml.aai.BASE_URL", "https://127.0.0.1:4321");
+ * props.setProperty("ml.aai.MODEL_URL",
+ * "/aai/v8/service-design-and-creation/models/model/");
+ * props.setProperty("ml.aai.KEYSTORE_FILE", "aai-client-cert.p12");
+ * props.setProperty("ml.aai.KEYSTORE_PASSWORD",
+ * "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o");
+ *
+ * ModelLoaderConfig config = new ModelLoaderConfig(props, "");
+ *
+ * String payload = readFile(MODEL_FILE); System.out.println("FILE:" +
+ * payload);
+ *
+ * File xmlFile = new File(MODEL_FILE); DocumentBuilderFactory dbFactory =
+ * DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder =
+ * dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile);
+ *
+ * // Get the ID of the model String modelId = null; NodeList nodeList =
+ * doc.getDocumentElement().getChildNodes(); for (int i = 0; i <
+ * nodeList.getLength(); i++) { Node currentNode = nodeList.item(i); if
+ * (currentNode.getNodeName().equals("model-name-version-id")) { modelId =
+ * currentNode.getTextContent(); break; } }
+ *
+ * // Add the model try { ModelArtifact model = new ModelArtifact();
+ * model.setNameVersionId(modelId); model.setType(ArtifactType.MODEL);
+ * model.setPayload(payload);
+ *
+ * AAIRestClient aaiClient = new AAIRestClient(config);
+ *
+ * // GET model System.out.println("Calling GET API ..."); ClientResponse
+ * getResponse = aaiClient.getResource(getURL(model, config),
+ * "example-trans-id-0", AAIRestClient.MimeType.XML); System.out.println(
+ * "GET result: " + getResponse.getStatus());
+ * assertTrue(getResponse.getStatus() ==
+ * Response.Status.NOT_FOUND.getStatusCode());
+ *
+ * // Add the model System.out.println("Calling PUT API ..."); ClientResponse
+ * res = aaiClient.putResource(getURL(model, config), model.getPayload(),
+ * "example-trans-id-1", AAIRestClient.MimeType.XML); System.out.println(
+ * "PUT result: " + res.getStatus()); assertTrue(res.getStatus() ==
+ * Response.Status.CREATED.getStatusCode());
+ *
+ * // Delete the model System.out.println("Calling DELETE API ..."); res =
+ * aaiClient.getAndDeleteResource(getURL(model, config),
+ * "example-trans-id-3"); System.out.println("DELETE result: " +
+ * res.getStatus()); assertTrue(res.getStatus() ==
+ * Response.Status.NO_CONTENT.getStatusCode()); } catch (Exception e) {
+ * e.printStackTrace(); } }
+ */
+
+ static String readFile(String path) throws IOException {
+ byte[] encoded = Files.readAllBytes(Paths.get(path));
+ return new String(encoded);
+ }
+
+ private String getURL(ModelArtifact model, ModelLoaderConfig config) {
+ String baseURL = config.getAaiBaseUrl().trim();
+ String subURL = null;
+ if (model.getType().equals(ArtifactType.MODEL)) {
+ subURL = config.getAaiModelUrl(model.getModelNamespaceVersion()).trim();
+ } else {
+ subURL = config.getAaiNamedQueryUrl(model.getModelNamespaceVersion()).trim();
+ }
+
+ if ((!baseURL.endsWith("/")) && (!subURL.startsWith("/"))) {
+ baseURL = baseURL + "/";
+ }
+
+ if (baseURL.endsWith("/") && subURL.startsWith("/")) {
+ baseURL = baseURL.substring(0, baseURL.length() - 1);
+ }
+
+ if (!subURL.endsWith("/")) {
+ subURL = subURL + "/";
+ }
+
+ String url = baseURL + subURL + model.getNameVersionId();
+ return url;
+ }
+}