summaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'vid-app-common/src/main/java')
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java28
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java101
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java51
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSPropertySupplier.java47
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java25
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstance.java26
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstances.java12
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceSubscription.java17
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/aai/model/Services.java24
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/asdc/beans/ServiceBuilder.java72
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java29
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java134
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientException.java7
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java173
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java31
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java161
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java70
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java20
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java114
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/mso/MsoException.java7
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java18
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java40
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/services/AaiService.java24
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java43
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java323
-rw-r--r--vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java39
26 files changed, 1007 insertions, 629 deletions
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java
index c1964c161..baf92b880 100644
--- a/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java
+++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiClient.java
@@ -8,16 +8,17 @@ import org.codehaus.jackson.map.ObjectMapper;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
import org.onap.vid.aai.model.*;
import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.*;
import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
-import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
import org.onap.vid.aai.model.Relationship;
import org.onap.vid.aai.model.RelationshipData;
import org.onap.vid.aai.model.RelationshipList;
+import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
import org.onap.vid.aai.util.AAIRestInterface;
import org.onap.vid.aai.util.VidObjectMapperType;
import org.onap.vid.exceptions.GenericUncheckedException;
@@ -26,7 +27,6 @@ import org.onap.vid.model.probes.ErrorMetadata;
import org.onap.vid.model.probes.ExternalComponentStatus;
import org.onap.vid.model.probes.HttpRequestMetadata;
import org.onap.vid.utils.Logging;
-import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.springframework.web.util.UriUtils;
import javax.inject.Inject;
@@ -37,7 +37,10 @@ import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
-import java.util.*;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.UUID;
import static java.util.Collections.emptyList;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
@@ -297,6 +300,10 @@ public class AaiClient implements AaiClientInterface {
@Override
public Response getVersionByInvariantId(List<String> modelInvariantId) {
+ if (modelInvariantId.isEmpty()) {
+ throw new GenericUncheckedException("Zero invariant-ids provided to getVersionByInvariantId; request is rejected as this will cause full models listing");
+ }
+
StringBuilder sb = new StringBuilder();
for (String id : modelInvariantId){
sb.append(MODEL_INVARIANT_ID);
@@ -413,9 +420,7 @@ public class AaiClient implements AaiClientInterface {
} else {
logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());
if (resp.getStatus() != HttpStatus.SC_OK) {
- logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
- String rawData = resp.readEntity(String.class);
- subscriberDataResponse = new AaiResponse<>(null, rawData, resp.getStatus());
+ subscriberDataResponse = processFailureResponse(resp,responseBody);
} else {
subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions);
}
@@ -423,6 +428,17 @@ public class AaiClient implements AaiClientInterface {
return subscriberDataResponse;
}
+ private AaiResponse processFailureResponse(Response resp, String responseBody) {
+ logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
+ String rawData;
+ if (responseBody != null) {
+ rawData = responseBody;
+ } else {
+ rawData = resp.readEntity(String.class);
+ }
+ return new AaiResponse<>(null, rawData, resp.getStatus());
+ }
+
private AaiResponse processOkResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
AaiResponse subscriberDataResponse;
String finalResponse = null;
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java
new file mode 100644
index 000000000..6e25e2715
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClient.java
@@ -0,0 +1,101 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.aai;
+
+import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.ACCEPT;
+import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.CONTENT_TYPE;
+import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.FROM_APP_ID_HEADER;
+import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.REQUEST_ID;
+import static org.onap.vid.aai.AaiOverTLSClientInterface.HEADERS.TRANSACTION_ID_HEADER;
+
+import io.joshworks.restclient.http.HttpResponse;
+import io.vavr.collection.HashMap;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.Map;
+import javax.ws.rs.core.MediaType;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.aai.model.AaiNodeQueryResponse;
+import org.onap.vid.aai.model.ResourceType;
+import org.onap.vid.aai.util.AAIProperties;
+import org.onap.vid.client.SyncRestClientInterface;
+import org.onap.vid.model.SubscriberList;
+
+public class AaiOverTLSClient implements AaiOverTLSClientInterface {
+
+ private final AaiOverTLSPropertySupplier propertySupplier;
+ private SyncRestClientInterface syncRestClient;
+ private boolean useClientCert;
+ private static final String CALLER_APP_ID = "VidAaiController";
+ private String urlBase;
+
+ public AaiOverTLSClient(SyncRestClientInterface syncRestClient, AaiOverTLSPropertySupplier propertySupplier) {
+ this(syncRestClient, propertySupplier, SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL));
+ }
+
+ AaiOverTLSClient(SyncRestClientInterface syncRestClient, AaiOverTLSPropertySupplier propertySupplier, String baseUrl) {
+ this.syncRestClient = syncRestClient;
+ this.propertySupplier = propertySupplier;
+ this.urlBase = baseUrl;
+ }
+
+ @Override
+ public void setUseClientCert(boolean useClientCert) {
+ this.useClientCert = useClientCert;
+ }
+
+ @Override
+ public HttpResponse<AaiNodeQueryResponse> searchNodeTypeByName(String name, ResourceType type) {
+ String uri = urlBase + String.format(URIS.NODE_TYPE_BY_NAME, type.getAaiFormat(), type.getNameFilter(), name);
+ return syncRestClient.get(uri, getRequestHeaders(), Collections.emptyMap(), AaiNodeQueryResponse.class);
+ }
+
+ @Override
+ public HttpResponse<SubscriberList> getAllSubscribers() {
+ String uri = urlBase + String.format(URIS.SUBSCRIBERS, 0);
+ return syncRestClient.get(uri, getRequestHeaders(), Collections.emptyMap(), SubscriberList.class);
+ }
+
+ private Map<String, String> getRequestHeaders() {
+ Map<String, String> result = HashMap.of(
+ TRANSACTION_ID_HEADER, propertySupplier.getRandomUUID(),
+ FROM_APP_ID_HEADER, CALLER_APP_ID,
+ CONTENT_TYPE, MediaType.APPLICATION_JSON,
+ REQUEST_ID, propertySupplier.getRequestId(),
+ ACCEPT, MediaType.APPLICATION_JSON)
+ .toJavaMap();
+ result.putAll(getAuthorizationHeader());
+ return result;
+ }
+
+ private Map<String, String> getAuthorizationHeader() {
+ if (!useClientCert) {
+ String vidUsername = propertySupplier.getUsername();
+ String vidPassword = propertySupplier.getPassword();
+ String encoded = Base64.getEncoder()
+ .encodeToString((vidUsername + ":" + vidPassword).getBytes(StandardCharsets.UTF_8));
+ return HashMap.of("Authorization", "Basic " + encoded).toJavaMap();
+ }
+ return HashMap.<String, String>empty().toJavaMap();
+ }
+
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java
new file mode 100644
index 000000000..ad43746ca
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSClientInterface.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.aai;
+
+import io.joshworks.restclient.http.HttpResponse;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.aai.model.AaiNodeQueryResponse;
+import org.onap.vid.aai.model.ResourceType;
+import org.onap.vid.model.SubscriberList;
+
+public interface AaiOverTLSClientInterface {
+
+ class URIS {
+
+ static final String SUBSCRIBERS = "business/customers?subscriber-type=INFRA&depth=%s";
+ static final String NODE_TYPE_BY_NAME = "search/nodes-query?search-node-type=%s&filter=%s:EQUALS:%s";
+ }
+
+ class HEADERS {
+ static final String TRANSACTION_ID_HEADER = "X-TransactionId";
+ static final String FROM_APP_ID_HEADER = "X-FromAppId";
+ static final String CONTENT_TYPE = "Content-Type";
+ static final String REQUEST_ID = SystemProperties.ECOMP_REQUEST_ID;
+ static final String ACCEPT = "Accept";
+ }
+
+ void setUseClientCert(boolean useClientCert);
+
+ HttpResponse<AaiNodeQueryResponse> searchNodeTypeByName(String name, ResourceType type);
+
+ HttpResponse<SubscriberList> getAllSubscribers();
+
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSPropertySupplier.java b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSPropertySupplier.java
new file mode 100644
index 000000000..33b44b159
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/aai/AaiOverTLSPropertySupplier.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2018 Nokia Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.vid.aai;
+
+import java.util.UUID;
+import org.eclipse.jetty.util.security.Password;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.aai.util.AAIProperties;
+import org.onap.vid.utils.Logging;
+
+public class AaiOverTLSPropertySupplier {
+
+ public String getUsername() {
+ return SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME);
+ }
+
+ public String getPassword() {
+ return Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X));
+ }
+
+ public String getRequestId() {
+ return Logging.extractOrGenerateRequestId();
+ }
+
+ public String getRandomUUID(){
+ return UUID.randomUUID().toString();
+ }
+
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java b/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java
index f80cae504..0e403697b 100644
--- a/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java
+++ b/vid-app-common/src/main/java/org/onap/vid/aai/exceptions/InvalidAAIResponseException.java
@@ -1,3 +1,24 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.vid.aai.exceptions;
import org.onap.vid.aai.AaiResponse;
@@ -10,4 +31,8 @@ public class InvalidAAIResponseException extends GenericUncheckedException {
public InvalidAAIResponseException(AaiResponse aaiResponse) {
super(String.format("errorCode: %d, raw: %s", aaiResponse.getHttpCode(), aaiResponse.getErrorMessage()));
}
+
+ public InvalidAAIResponseException(int statusCode, String message) {
+ super(String.format("errorCode: %d, raw: %s", statusCode, message));
+ }
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstance.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstance.java
deleted file mode 100644
index 381f9bc25..000000000
--- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstance.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package org.onap.vid.aai.model;
-
-import org.codehaus.jackson.annotate.JsonProperty;
-
-public class ServiceInstance {
-
- @JsonProperty("service-instance-id")
- public String serviceInstanceId;
-
- @JsonProperty("service-instance-name")
- public String serviceInstanceName;
-
- @JsonProperty("persona-model-id")
- public String personaModelId;
-
- @JsonProperty("persona-model-version")
- public String personaModelVersion;
-
- @JsonProperty("resource-version")
- public String resourceVersion;
-
- @JsonProperty("orchestration-status")
- public String orchestrationStatus;
-
-
-}
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstances.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstances.java
deleted file mode 100644
index 0fced4c57..000000000
--- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceInstances.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package org.onap.vid.aai.model;
-
-import java.util.List;
-
-import org.codehaus.jackson.annotate.JsonProperty;
-
-public class ServiceInstances {
-
- @JsonProperty("service-instance")
- public List<ServiceInstance> serviceInstance;
-
-}
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceSubscription.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceSubscription.java
deleted file mode 100644
index 91582e816..000000000
--- a/vid-app-common/src/main/java/org/onap/vid/aai/model/ServiceSubscription.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package org.onap.vid.aai.model;
-
-import org.codehaus.jackson.annotate.JsonProperty;
-
-public class ServiceSubscription {
-
- @JsonProperty("service-type")
- public String serviceType;
-
- @JsonProperty("resource-version")
- public String resourceVersion;
-
- @JsonProperty("service-instances")
- public ServiceInstances serviceInstances;
-
-
-}
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/model/Services.java b/vid-app-common/src/main/java/org/onap/vid/aai/model/Services.java
deleted file mode 100644
index 3ba4b22d0..000000000
--- a/vid-app-common/src/main/java/org/onap/vid/aai/model/Services.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package org.onap.vid.aai.model;
-
-import java.util.List;
-
-import org.codehaus.jackson.annotate.JsonProperty;
-
-public class Services {
- @JsonProperty("global-customer-id")
- public String globalCustomerId;
-
- @JsonProperty("subscriber-name")
- public String subscriberName;
-
- @JsonProperty("subscriber-type")
- public String subscriberType;
-
- @JsonProperty("resource-version")
- public String resourceVersion;
-
- @JsonProperty("service-subscriptions")
- public List<ServiceSubscription> serviceSubscriptions;
-
-
-}
diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/beans/ServiceBuilder.java b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/ServiceBuilder.java
new file mode 100644
index 000000000..73bef7636
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/asdc/beans/ServiceBuilder.java
@@ -0,0 +1,72 @@
+package org.onap.vid.asdc.beans;
+
+import java.util.Collection;
+
+public class ServiceBuilder {
+ private String uuid;
+ private String invariantUUID;
+ private String name;
+ private String version;
+ private String toscaModelURL;
+ private String category;
+ private Service.LifecycleState lifecycleState;
+ private String distributionStatus;
+ private Collection<Artifact> artifacts;
+ private Collection<SubResource> resources;
+
+ public ServiceBuilder setUuid(String uuid) {
+ this.uuid = uuid;
+ return this;
+ }
+
+ public ServiceBuilder setInvariantUUID(String invariantUUID) {
+ this.invariantUUID = invariantUUID;
+ return this;
+ }
+
+ public ServiceBuilder setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public ServiceBuilder setVersion(String version) {
+ this.version = version;
+ return this;
+ }
+
+ public ServiceBuilder setToscaModelURL(String toscaModelURL) {
+ this.toscaModelURL = toscaModelURL;
+ return this;
+ }
+
+ public ServiceBuilder setCategory(String category) {
+ this.category = category;
+ return this;
+ }
+
+ public ServiceBuilder setLifecycleState(Service.LifecycleState lifecycleState) {
+ this.lifecycleState = lifecycleState;
+ return this;
+ }
+
+ public ServiceBuilder setDistributionStatus(String distributionStatus) {
+ this.distributionStatus = distributionStatus;
+ return this;
+ }
+
+ public ServiceBuilder setArtifacts(Collection<Artifact> artifacts) {
+ this.artifacts = artifacts;
+ return this;
+ }
+
+ public ServiceBuilder setResources(Collection<SubResource> resources) {
+ this.resources = resources;
+ return this;
+ }
+
+ public Service build() {
+ return new Service(uuid, invariantUUID, category, version, name, distributionStatus, toscaModelURL, lifecycleState, artifacts, resources);
+ }
+}
+
+
diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java
index 17fb29b59..57d80ce9d 100644
--- a/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java
+++ b/vid-app-common/src/main/java/org/onap/vid/asdc/parser/ToscaParserImpl2.java
@@ -1,7 +1,6 @@
package org.onap.vid.asdc.parser;
-import org.onap.vid.asdc.beans.Service;
-import org.onap.vid.model.*;
+import org.apache.commons.lang3.StringUtils;
import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
import org.onap.sdc.tosca.parser.impl.FilterType;
@@ -11,6 +10,8 @@ import org.onap.sdc.toscaparser.api.Group;
import org.onap.sdc.toscaparser.api.*;
import org.onap.sdc.toscaparser.api.elements.Metadata;
import org.onap.sdc.toscaparser.api.parameters.Input;
+import org.onap.vid.asdc.beans.Service;
+import org.onap.vid.model.*;
import java.nio.file.Path;
import java.util.*;
@@ -417,7 +418,22 @@ public class ToscaParserImpl2 {
private boolean isInputMatchesToGroup(List<Property> annotationProperties, org.onap.vid.model.Group group){
for(Property property: annotationProperties){
if(property.getName().equals(VF_MODULE_LABEL)){
- return getPropertyValueAsString(property).equals(group.getProperties().getVfModuleLabel());
+ final Object values = property.getValue();
+ final String vfModuleLabel = group.getProperties().getVfModuleLabel();
+ if (values instanceof List) {
+ if (listContainsAsString((List) values, vfModuleLabel)) return true;
+ } else {
+ return getPropertyValueAsString(property).equals(vfModuleLabel);
+ }
+ }
+ }
+ return false;
+ }
+
+ private boolean listContainsAsString(List list, String value) {
+ for (Object v : list) {
+ if (StringUtils.equals(v.toString(), value)) {
+ return true;
}
}
return false;
@@ -428,7 +444,7 @@ public class ToscaParserImpl2 {
}
private String removeSquareBrackets(String stringWithSquareBrackets){
- return stringWithSquareBrackets.substring(1, stringWithSquareBrackets.length()-1);
+ return stringWithSquareBrackets.replaceAll("(^\\[|\\]$)", "");
}
private GroupProperties extractVfModuleProperties(Group group, ISdcCsarHelper csarHelper){
@@ -507,7 +523,10 @@ public class ToscaParserImpl2 {
for (Property property : properties) {
//special handling to necessary sub-property "ecomp_generated_naming"
if(property.getName().equals("nf_naming")){
- propertiesMap.put(removeSquareBrackets(((LinkedHashMap)(property.getValue())).keySet().toString()) ,((LinkedHashMap)(property.getValue())).get("ecomp_generated_naming").toString());
+ final Object ecompGeneratedNaming = ((Map) (property.getValue())).get("ecomp_generated_naming");
+ if (ecompGeneratedNaming != null) {
+ propertiesMap.put("ecomp_generated_naming", ecompGeneratedNaming.toString());
+ }
}
propertiesMap.put(property.getName(), property.getValue().toString());
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java
index a3ff5f923..9e50c4456 100644
--- a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java
+++ b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClient.java
@@ -25,42 +25,33 @@ import io.joshworks.restclient.http.JsonNode;
import io.joshworks.restclient.http.RestClient;
import io.joshworks.restclient.http.exceptions.RestClientException;
import io.joshworks.restclient.http.mapper.ObjectMapper;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import io.joshworks.restclient.request.GetRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
-import org.eclipse.jetty.util.security.Password;
+import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
-import org.apache.http.conn.ssl.SSLContexts;
-import io.vavr.CheckedFunction1;
-import lombok.SneakyThrows;
-import lombok.val;
+import org.eclipse.jetty.util.security.Password;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.vid.properties.VidProperties;
-import java.security.UnrecoverableKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.KeyManagementException;
-import java.security.cert.CertificateException;
-import javax.net.ssl.SSLException;
-import java.security.KeyStoreException;
-import java.text.SimpleDateFormat;
import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLException;
+import java.io.File;
import java.io.FileInputStream;
-import java.security.KeyStore;
-import java.text.DateFormat;
-import java.io.InputStream;
import java.io.IOException;
-import java.util.Date;
+import java.io.InputStream;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
import java.util.Map;
-import java.io.File;
-import org.onap.portalsdk.core.util.SystemProperties;
-import org.onap.vid.properties.VidProperties;
public class SyncRestClient implements SyncRestClientInterface {
-
- private static final String CANNOT_INITIALIZE_CUSTOM_HTTP_CLIENT = "Cannot initialize custom http client from current configuration. Using default one.";
- private static final String TRY_TO_CALL_OVER_HTTP = "SSL Handshake problem occured. Will try to retry over Http.";
private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SyncRestClient.class);
- private static final DateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss:SSSS");
private static final String[] SUPPORTED_SSL_VERSIONS = {"TLSv1", "TLSv1.2"};
private static final String HTTPS_SCHEMA = "https://";
private static final String HTTP_SCHEMA = "http://";
@@ -91,13 +82,13 @@ public class SyncRestClient implements SyncRestClientInterface {
@Override
public <T> HttpResponse<T> post(String url, Map<String, String> headers, Object body, Class<T> responseClass) {
return callWithRetryOverHttp(url,
- url2 -> restClient.post(url2).headers(headers).body(body).asObject(responseClass));
+ url2 -> restClient.post(url2).headers(headers).body(body).asObject(responseClass));
}
@Override
public HttpResponse<JsonNode> get(String url, Map<String, String> headers, Map<String, String> routeParams) {
return callWithRetryOverHttp(url, url2 -> {
- val getRequest = restClient.get(url2).headers(headers);
+ GetRequest getRequest = restClient.get(url2).headers(headers);
routeParams.forEach(getRequest::routeParam);
return getRequest.asJson();
});
@@ -105,9 +96,9 @@ public class SyncRestClient implements SyncRestClientInterface {
@Override
public <T> HttpResponse<T> get(String url, Map<String, String> headers, Map<String, String> routeParams,
- Class<T> responseClass) {
+ Class<T> responseClass) {
return callWithRetryOverHttp(url, url2 -> {
- val getRequest = restClient.get(url2).headers(headers);
+ GetRequest getRequest = restClient.get(url2).headers(headers);
routeParams.forEach(getRequest::routeParam);
return getRequest.asObject(responseClass);
});
@@ -115,9 +106,9 @@ public class SyncRestClient implements SyncRestClientInterface {
@Override
public HttpResponse<InputStream> getStream(String url, Map<String, String> headers,
- Map<String, String> routeParams) {
+ Map<String, String> routeParams) {
return callWithRetryOverHttp(url, url2 -> {
- val getRequest = restClient.get(url2).headers(headers);
+ GetRequest getRequest = restClient.get(url2).headers(headers);
routeParams.forEach(getRequest::routeParam);
return getRequest.asBinary();
});
@@ -131,7 +122,7 @@ public class SyncRestClient implements SyncRestClientInterface {
@Override
public <T> HttpResponse<T> put(String url, Map<String, String> headers, Object body, Class<T> responseClass) {
return callWithRetryOverHttp(url,
- url2 -> restClient.put(url2).headers(headers).body(body).asObject(responseClass));
+ url2 -> restClient.put(url2).headers(headers).body(body).asObject(responseClass));
}
@Override
@@ -154,81 +145,100 @@ public class SyncRestClient implements SyncRestClientInterface {
restClient.shutdown();
}
- @SneakyThrows
- private <T> HttpResponse<T> callWithRetryOverHttp(String url,
- CheckedFunction1<String, HttpResponse<T>> httpRequest) {
+ private <T> HttpResponse<T> callWithRetryOverHttp(String url, HttpRequest<T> httpRequest) {
+ try {
+ return callWithRetryOverHttpThrows(url, httpRequest);
+ } catch (IOException e) {
+ throw new SyncRestClientException("IOException while calling rest service", e);
+ }
+ }
+
+ private <T> HttpResponse<T> callWithRetryOverHttpThrows(String url, HttpRequest<T> httpRequest) throws IOException {
try {
return httpRequest.apply(url);
} catch (RestClientException e) {
- if (e.getCause() instanceof SSLException) {
- logger.warn(EELFLoggerDelegate.debugLogger,
- DATE_FORMAT.format(new Date()) + TRY_TO_CALL_OVER_HTTP, e);
+ if (causedBySslHandshakeError(e)) {
+ logger.warn(EELFLoggerDelegate.debugLogger, "SSL Handshake problem occured. Will try to retry over Http.", e);
return httpRequest.apply(url.replaceFirst(HTTPS_SCHEMA, HTTP_SCHEMA));
}
throw e;
}
}
+ private boolean causedBySslHandshakeError(RestClientException exception) {
+ return exception.getCause() instanceof SSLException;
+ }
+
private ObjectMapper defaultObjectMapper() {
- val objectMapper = new org.codehaus.jackson.map.ObjectMapper();
+ org.codehaus.jackson.map.ObjectMapper objectMapper = new org.codehaus.jackson.map.ObjectMapper();
return new ObjectMapper() {
@Override
- @SneakyThrows
public <T> T readValue(String value, Class<T> aClass) {
- return objectMapper.readValue(value, aClass);
+ try {
+ return objectMapper.readValue(value, aClass);
+ } catch (IOException e) {
+ throw new SyncRestClientException("IOException while reading value", e);
+ }
}
@Override
- @SneakyThrows
public String writeValue(Object value) {
- return objectMapper.writeValueAsString(value);
+ try {
+ return objectMapper.writeValueAsString(value);
+ } catch (IOException e) {
+ throw new SyncRestClientException("IOException while writing value", e);
+ }
}
};
}
private CloseableHttpClient defaultHttpClient() {
try {
- val trustStorePath = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_FILENAME);
- val trustStorePass = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_PASSWD_X);
- val decryptedTrustStorePass = Password.deobfuscate(trustStorePass);
+ String trustStorePath = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_FILENAME);
+ String trustStorePass = SystemProperties.getProperty(VidProperties.VID_TRUSTSTORE_PASSWD_X);
+ String decryptedTrustStorePass = Password.deobfuscate(trustStorePass);
- val trustStore = loadTruststore(trustStorePath, decryptedTrustStorePass);
- val sslContext = trustOwnCACerts(decryptedTrustStorePass, trustStore);
- val sslSf = allowTLSProtocols(sslContext);
+ KeyStore trustStore = loadTruststore(trustStorePath, decryptedTrustStorePass);
+ SSLContext sslContext = trustOwnCACerts(decryptedTrustStorePass, trustStore);
+ SSLConnectionSocketFactory sslSf = allowTLSProtocols(sslContext);
return HttpClients.custom().setSSLSocketFactory(sslSf).build();
} catch (IOException | CertificateException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
- logger.warn(EELFLoggerDelegate.debugLogger,
- DATE_FORMAT.format(new Date()) + CANNOT_INITIALIZE_CUSTOM_HTTP_CLIENT, e);
+ logger.warn(EELFLoggerDelegate.debugLogger, "Cannot initialize custom http client from current configuration. Using default one.", e);
return HttpClients.createDefault();
}
}
private SSLConnectionSocketFactory allowTLSProtocols(SSLContext sslcontext) {
return new SSLConnectionSocketFactory(
- sslcontext,
- SUPPORTED_SSL_VERSIONS,
- null,
- SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
+ sslcontext,
+ SUPPORTED_SSL_VERSIONS,
+ null,
+ SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
private SSLContext trustOwnCACerts(String trustStorePass, KeyStore trustStore)
- throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
+ throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
return SSLContexts.custom()
- .useTLS()
- .loadKeyMaterial(trustStore, trustStorePass.toCharArray())
- .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
- .build();
+ .useTLS()
+ .loadKeyMaterial(trustStore, trustStorePass.toCharArray())
+ .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
+ .build();
}
private KeyStore loadTruststore(String trustStorePath, String trustStorePass)
- throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
- val trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
+ throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
+ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (FileInputStream instream = new FileInputStream(new File(trustStorePath))) {
trustStore.load(instream, trustStorePass.toCharArray());
}
return trustStore;
}
+ @FunctionalInterface
+ private interface HttpRequest<T> {
+ HttpResponse<T> apply(String url) throws IOException;
+ }
+
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientException.java b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientException.java
new file mode 100644
index 000000000..2a4f093b1
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientException.java
@@ -0,0 +1,7 @@
+package org.onap.vid.client;
+
+public class SyncRestClientException extends RuntimeException {
+ public SyncRestClientException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java
index 12cc68e61..86e832ba7 100644
--- a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java
+++ b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthCheckController.java
@@ -25,7 +25,7 @@ import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.onap.vid.dao.FnAppDoaImpl;
import org.onap.vid.model.GitRepositoryState;
-import org.springframework.beans.factory.annotation.Value;
+import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -38,6 +38,9 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
+import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
+import static org.springframework.http.HttpStatus.OK;
+
/**
* Controller for user profile view. The view is restricted to authenticated
* users. The view name resolves to page user_profile.jsp which uses Angular.
@@ -47,158 +50,86 @@ import java.util.Properties;
@RequestMapping("/")
public class HealthCheckController extends UnRestrictedBaseController {
- /**
- * The logger.
- */
private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(HealthCheckController.class);
-
- /**
- * The Constant dateFormat.
- */
- final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
-
- private static final String HEALTH_CHECK_PATH = "/healthCheck";
+ private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
private static final String GIT_PROPERTIES_FILENAME = "git.properties";
+ private FnAppDoaImpl fnAppDoaImpl;
- /**
- * Model for JSON response with health-check results.
- */
- public class HealthStatus {
- // Either 200 or 500
- public int statusCode;
-
- // Additional detail in case of error, empty in case of success.
- public String message;
-
- public String date;
-
- public HealthStatus(int code, String msg) {
- this.statusCode = code;
- this.message = msg;
- }
-
- public HealthStatus(int code, String date, String msg) {
- this.statusCode = code;
- this.message = msg;
- this.date = date;
- }
-
- public int getStatusCode() {
- return statusCode;
- }
-
- public void setStatusCode(int code) {
- this.statusCode = code;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String msg) {
- this.message = msg;
- }
-
- public String getDate() {
- return date;
- }
-
- public void setDate(String date) {
- this.date = date;
- }
-
+ @Autowired
+ public HealthCheckController(FnAppDoaImpl fnAppDoaImpl) {
+ this.fnAppDoaImpl = fnAppDoaImpl;
}
- @SuppressWarnings("unchecked")
- public int getProfileCount(String driver, String URL, String username, String password) {
- FnAppDoaImpl doa = new FnAppDoaImpl();
- int count = doa.getProfileCount(driver, URL, username, password);
- return count;
- }
-
-
/**
* Obtain the HealthCheck Status from the System.Properties file.
* Used by IDNS for redundancy
*
* @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
*/
@RequestMapping(value = "/healthCheck", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public HealthStatus gethealthCheckStatusforIDNS() {
-
- String driver = SystemProperties.getProperty("db.driver");
- String URL = SystemProperties.getProperty("db.connectionURL");
- String username = SystemProperties.getProperty("db.userName");
- String password = SystemProperties.getProperty("db.password");
-
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "driver ::" + driver);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::" + URL);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::" + username);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "password::" + password);
-
-
- HealthStatus healthStatus = null;
- try {
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check");
- int count = getProfileCount(driver, URL, username, password);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::" + count);
- healthStatus = new HealthStatus(200, "health check succeeded");
- } catch (Exception ex) {
-
- LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
- healthStatus = new HealthStatus(500, "health check failed: " + ex.toString());
- }
- return healthStatus;
+ public HealthStatus getHealthCheckStatusForIDNS() {
+ return createCorrespondingStatus();
}
/**
* Obtain the HealthCheck Status from the System.Properties file.
*
* @return ResponseEntity The response entity
- * @throws IOException Signals that an I/O exception has occurred.
- * Project :
*/
@RequestMapping(value = "rest/healthCheck/{User-Agent}/{X-ECOMP-RequestID}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public HealthStatus getHealthCheck(
@PathVariable("User-Agent") String UserAgent,
@PathVariable("X-ECOMP-RequestID") String ECOMPRequestID) {
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "User-Agent ", UserAgent);
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "X-ECOMP-RequestID ", ECOMPRequestID);
+ return createCorrespondingStatus();
+ }
- String driver = SystemProperties.getProperty("db.driver");
- String URL = SystemProperties.getProperty("db.connectionURL");
- String username = SystemProperties.getProperty("db.userName");
- String password = SystemProperties.getProperty("db.password");
-
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "driver ::" + driver);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::" + URL);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::" + username);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "password::" + password);
-
+ @RequestMapping(value = "/commitInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
+ public GitRepositoryState getCommitInfo() throws IOException {
+ Properties properties = new Properties();
+ properties.load(getClass().getClassLoader().getResourceAsStream(GIT_PROPERTIES_FILENAME));
+ return new GitRepositoryState(properties);
+ }
- HealthStatus healthStatus = null;
+ private HealthStatus createCorrespondingStatus() {
+ logData();
try {
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check");
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "User-Agent" + UserAgent);
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "X-ECOMP-RequestID" + ECOMPRequestID);
+ int count = fnAppDoaImpl.getProfileCount(getUrl(), getUsername(), getPassword());
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::", count);
+ return okStatus();
+ } catch (Exception ex) {
+ String errorMsg = ex.getMessage();
+ LOGGER.error(EELFLoggerDelegate.errorLogger, errorMsg);
+ return errorStatus(errorMsg);
+ }
+ }
+ private void logData() {
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "Performing health check");
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "URL::", getUrl());
+ LOGGER.debug(EELFLoggerDelegate.debugLogger, "username::", getUsername());
+ }
- int count = getProfileCount(driver, URL, username, password);
+ private HealthStatus okStatus() {
+ return new HealthStatus(OK, dateFormat.format(new Date()), "health check succeeded");
+ }
- LOGGER.debug(EELFLoggerDelegate.debugLogger, "count:::" + count);
- healthStatus = new HealthStatus(200, dateFormat.format(new Date()), "health check succeeded");
- } catch (Exception ex) {
+ private HealthStatus errorStatus(String msg) {
+ return new HealthStatus(INTERNAL_SERVER_ERROR, dateFormat.format(
+ new Date()), "health check failed: " + msg);
+ }
- LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
- healthStatus = new HealthStatus(500, dateFormat.format(new Date()), "health check failed: " + ex.toString());
- }
- return healthStatus;
+ private String getUrl() {
+ return SystemProperties.getProperty("db.connectionURL");
}
- @RequestMapping(value = "/commitInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
- public GitRepositoryState getCommitInfo() throws IOException {
- Properties properties = new Properties();
- properties.load(getClass().getClassLoader().getResourceAsStream(GIT_PROPERTIES_FILENAME));
- return new GitRepositoryState(properties);
+ private String getUsername() {
+ return SystemProperties.getProperty("db.userName");
+ }
+
+ private String getPassword() {
+ return SystemProperties.getProperty("db.password");
}
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java
new file mode 100644
index 000000000..6056c2898
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/controllers/HealthStatus.java
@@ -0,0 +1,31 @@
+package org.onap.vid.controllers;
+
+import org.springframework.http.HttpStatus;
+
+/**
+ * Model for JSON response with health-check results.
+ */
+public final class HealthStatus {
+
+ private final int statusCode;
+ private final String detailedMsg;
+ private final String date;
+
+ public HealthStatus(HttpStatus code, String date, String detailedMsg) {
+ this.statusCode = code.value();
+ this.detailedMsg = detailedMsg;
+ this.date = date;
+ }
+
+ public int getStatusCode() {
+ return statusCode;
+ }
+
+ public String getDetailedMsg() {
+ return detailedMsg;
+ }
+
+ public String getDate() {
+ return date;
+ }
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java
index 6d6ffb31b..b9d67b6df 100644
--- a/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java
+++ b/vid-app-common/src/main/java/org/onap/vid/controllers/VidController.java
@@ -4,12 +4,14 @@
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
+ * Modifications Copyright 2018 Nokia
+ * ================================================================================
* 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.
@@ -40,122 +42,73 @@ import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
-//import org.onap.vid.model.Service;
-
@RestController
public class VidController extends RestrictedBaseController {
- private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidController.class);
-
- private final VidService service;
+ private static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(VidController.class);
- @Autowired
- public VidController(VidService vidService) {
- service = vidService;
- }
-
- @Autowired
- private AaiService aaiService;
-
- @Autowired
- RoleProvider roleProvider;
+ private final VidService vidService;
+ private final AaiService aaiService;
+ private final RoleProvider roleProvider;
+ private final PombaService pombaService;
@Autowired
- private PombaService pombaService;
-
-// /**
-// * Gets the services.
-// *
-// * @param request the request
-// * @return the services
-// * @throws VidServiceUnavailableException the vid service unavailable exception
-// */
-// @RequestMapping(value={"/rest/models/services"}, method = RequestMethod.GET)
-// public SecureServices getServices(HttpServletRequest request) throws VidServiceUnavailableException {
-// try {
-// AaiService aaiService = new AaiServiceImpl();
-// LOG.info("Start API for browse ASDC was called");
-// SecureServices secureServices = new SecureServices();
-// Map<String, String[]> requestParams = request.getParameterMap();
-// List<Role> roles = roleProvider.getUserRoles(request);
-// secureServices.setServices(aaiService.getServicesByDistributionStatus());
-// secureServices.setServices(service.getServices(requestParams));
-// secureServices.setReadOnly(roleProvider.userPermissionIsReadOnly(roles));
-// return secureServices;
-// } catch (AsdcCatalogException e) {
-// LOG.error("Failed to retrieve service definitions from SDC", e);
-// throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e);
-// } catch (Throwable t) {
-// LOG.debug("Unexpected error while retrieving service definitions from SDC: " + t.getMessage() + ":", t);
-// t.printStackTrace();
-// throw new VidServiceUnavailableException("Unexpected error while retrieving service definitions from SDC: " + t.getMessage(), t);
-// }
-// }
-
- /**
- * Gets the services.
- *
- * @param request the request
- * @return the services
- * @throws VidServiceUnavailableException the vid service unavailable exception
- */
- @RequestMapping(value={"/rest/models/services"}, method = RequestMethod.GET)
- public SecureServices getServices(HttpServletRequest request) throws VidServiceUnavailableException {
- try {
- LOG.info("Start API for browse ASDC was called");
- SecureServices secureServices = new SecureServices();
- List<Role> roles = roleProvider.getUserRoles(request);
- secureServices.setServices(aaiService.getServicesByDistributionStatus());
- //Disable roles until AAF integration finishes
- //secureServices.setReadOnly(roleProvider.userPermissionIsReadOnly(roles));
- secureServices.setReadOnly(false);
- return secureServices;
- }
- catch (Exception t) {
- LOG.debug("Unexpected error while retrieving service definitions from A&AI: " + t.getMessage() + ":", t);
- throw new VidServiceUnavailableException("Unexpected error while retrieving service definitions from A&AI: " + t.getMessage(), t);
- }
- }
+ public VidController(VidService vidService, AaiService aaiService, RoleProvider roleProvider,
+ PombaService pombaService) {
+ this.vidService = vidService;
+ this.aaiService = aaiService;
+ this.roleProvider = roleProvider;
+ this.pombaService = pombaService;
+ }
+ /**
+ * @param request the request
+ * @return the services
+ */
+ @RequestMapping(value = {"/rest/models/services"}, method = RequestMethod.GET)
+ public SecureServices getServices(HttpServletRequest request) {
+ LOG.info("Start API for browse ASDC was called");
+ SecureServices secureServices = new SecureServices();
+ List<Role> roles = roleProvider.getUserRoles(request);
+ secureServices.setServices(aaiService.getServicesByDistributionStatus());
+ secureServices.setReadOnly(roleProvider.userPermissionIsReadOnly(roles));
+ return secureServices;
+ }
- /**
- * Gets the services.
- *
- * @param uuid the uuid
- * @return the services
- * @throws VidServiceUnavailableException the vid service unavailable exception
- */
- @RequestMapping(value={"/rest/models/services/{uuid}"}, method = RequestMethod.GET)
- public ServiceModel getServices(@PathVariable("uuid") String uuid, HttpServletRequest request) throws VidServiceUnavailableException {
- try {
- return service.getService(uuid);
- } catch (AsdcCatalogException e) {
- LOG.error("Failed to retrieve service definitions from SDC. Error: "+e.getMessage() , e);
- throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e);
- }
- }
+ /**
+ * @param uuid the uuid
+ * @return the services
+ * @throws VidServiceUnavailableException the vid service unavailable exception
+ */
+ @RequestMapping(value = {"/rest/models/services/{uuid}"}, method = RequestMethod.GET)
+ public ServiceModel getService(@PathVariable("uuid") String uuid) throws VidServiceUnavailableException {
+ try {
+ return vidService.getService(uuid);
+ } catch (AsdcCatalogException e) {
+ LOG.error("Failed to retrieve service definitions from SDC. Error: " + e.getMessage(), e);
+ throw new VidServiceUnavailableException("Failed to retrieve service definitions from SDC", e);
+ }
+ }
- @RequestMapping(value = "/rest/models/reset", method = RequestMethod.POST)
- @ResponseStatus(HttpStatus.ACCEPTED)
- public void invalidateServiceModelCache(HttpServletRequest request) {
- service.invalidateServiceCache();
- }
+ @RequestMapping(value = "/rest/models/reset", method = RequestMethod.POST)
+ @ResponseStatus(HttpStatus.ACCEPTED)
+ public void invalidateServiceModelCache() {
+ vidService.invalidateServiceCache();
+ }
- /**
- * Gets the services view.
- *
- * @param request the request
- * @return the services view
- * @throws VidServiceUnavailableException the vid service unavailable exception
- */
- @RequestMapping(value={"/serviceModels"}, method=RequestMethod.GET)
- public ModelAndView getServicesView(HttpServletRequest request) {
+ /**
+ * @return the services view
+ * @throws VidServiceUnavailableException the vid service unavailable exception
+ */
+ // FIX ME: Circular view path [serviceModels]: would dispatch back to the current handler URL [/serviceModels] again.
+ @RequestMapping(value = {"/serviceModels"}, method = RequestMethod.GET)
+ public ModelAndView getServicesView() {
return new ModelAndView("serviceModels");
}
@RequestMapping(value = {"/rest/models/services/verifyService"}, method = RequestMethod.POST)
- public void verifyServiceInstance(HttpServletRequest request, @RequestBody PombaRequest pombaRequest) {
- pombaService.verify(pombaRequest);
+ public void verifyServiceInstance(@RequestBody PombaRequest pombaRequest) {
+ pombaService.verify(pombaRequest);
}
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java b/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java
index 0f4b536a1..56dce9ac7 100644
--- a/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java
+++ b/vid-app-common/src/main/java/org/onap/vid/controllers/WebConfig.java
@@ -21,9 +21,14 @@
package org.onap.vid.controllers;
-import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import io.joshworks.restclient.http.mapper.ObjectMapper;
+import java.io.IOException;
import org.onap.vid.aai.AaiClient;
import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.aai.AaiOverTLSClient;
+import org.onap.vid.aai.AaiOverTLSClientInterface;
+import org.onap.vid.aai.AaiOverTLSPropertySupplier;
import org.onap.vid.aai.AaiResponseTranslator;
import org.onap.vid.aai.PombaClientImpl;
import org.onap.vid.aai.PombaClientInterface;
@@ -48,7 +53,6 @@ import org.onap.vid.services.VidService;
import org.onap.vid.services.VidServiceImpl;
import org.onap.vid.scheduler.SchedulerRestInterface;
import org.onap.vid.scheduler.SchedulerRestInterfaceIfc;
-import org.onap.vid.services.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -66,8 +70,8 @@ public class WebConfig {
* @return the object mapper
*/
@Bean
- public ObjectMapper getObjectMapper() {
- return new ObjectMapper();
+ public com.fasterxml.jackson.databind.ObjectMapper getObjectMapper() {
+ return new com.fasterxml.jackson.databind.ObjectMapper();
}
@@ -161,4 +165,62 @@ public class WebConfig {
public SchedulerRestInterfaceIfc getSchedulerRestInterface(){
return new SchedulerRestInterface();
}
+
+ @Bean(name = "aaiClientForFasterXmlMapping")
+ public AaiOverTLSClientInterface getAaiClientForFasterXmlMapping(){
+ ObjectMapper objectMapper = new ObjectMapper() {
+
+ com.fasterxml.jackson.databind.ObjectMapper om = new com.fasterxml.jackson.databind.ObjectMapper();
+
+ @Override
+ public <T> T readValue(String s, Class<T> aClass) {
+ try {
+ return om.readValue(s, aClass);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String writeValue(Object o) {
+ try {
+ return om.writeValueAsString(o);
+ } catch (JsonProcessingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+
+ return new AaiOverTLSClient(new SyncRestClient(objectMapper), new AaiOverTLSPropertySupplier());
+ }
+
+
+ @Bean(name = "aaiClientForCodehausMapping")
+ public AaiOverTLSClientInterface getAaiClientForCodehausMapping() {
+
+ ObjectMapper objectMapper = new ObjectMapper() {
+
+ org.codehaus.jackson.map.ObjectMapper om = new org.codehaus.jackson.map.ObjectMapper();
+
+ @Override
+ public <T> T readValue(String s, Class<T> aClass) {
+ try {
+ return om.readValue(s, aClass);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public String writeValue(Object o) {
+ try {
+ return om.writeValueAsString(o);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+
+ return new AaiOverTLSClient(new SyncRestClient(objectMapper), new AaiOverTLSPropertySupplier());
+ }
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java b/vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java
new file mode 100644
index 000000000..bd7a67b5a
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/dao/ConnectionFactory.java
@@ -0,0 +1,20 @@
+package org.onap.vid.dao;
+
+import org.springframework.stereotype.Component;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+@Component
+public class ConnectionFactory {
+
+ public Connection getConnection(String url, String username, String password) throws SQLException {
+ checkNotNull(url);
+ checkNotNull(username);
+ checkNotNull(password);
+ return DriverManager.getConnection(url, username, password);
+ }
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java b/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java
index 65fc5217f..e3fdc95f2 100644
--- a/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java
+++ b/vid-app-common/src/main/java/org/onap/vid/dao/FnAppDoaImpl.java
@@ -7,9 +7,9 @@
* 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.
@@ -21,94 +21,38 @@
package org.onap.vid.dao;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
import java.sql.*;
-
+@Repository
public class FnAppDoaImpl {
- /** The logger. */
- static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnAppDoaImpl.class);
-
- public int getProfileCount(String driver, String URL, String username, String password) {
- Connection dbc = null;
- PreparedStatement pst = null;
- ResultSet rs = null;
- String q = null;
- int count = 0;
- try {
- dbc = getConnection(URL,username,password);
- logger.debug(EELFLoggerDelegate.debugLogger, "getConnection:::"+ dbc);
- q = "select count(*) from fn_app";
- pst = dbc.prepareStatement(q);
- rs = pst.executeQuery();
-
- if (rs.next())
- count = rs.getInt(1);
- } catch(Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
- } finally {
- cleanup(rs,pst,dbc);
- }
- logger.debug(EELFLoggerDelegate.debugLogger, "count:::"+ count);
- return count;
- }
-
- public static Connection getConnection(String url, String username, String password) throws SQLException {
- java.sql.Connection con=null;
-
- if( url!=null && username!=null && password!=null ){
- con = DriverManager.getConnection(url, username, password);
- }
-
- logger.info("Connection Successful");
-
- return con;
-
- }
-
- public static void cleanup(ResultSet rs, PreparedStatement st, Connection c) {
- if (rs != null) {
- closeResultSet(rs);
- }
- if (st != null) {
- closePreparedStatement(st);
- }
- if (c != null) {
- rollbackAndCloseConnection(c);
- }
- }
-
- private static void rollbackAndCloseConnection(Connection c) {
- try {
- c.rollback();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to rollback connection", e);
+ static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnAppDoaImpl.class);
+
+ private ConnectionFactory connectionFactory;
+
+ @Autowired
+ public FnAppDoaImpl(ConnectionFactory connectionFactory) {
+ this.connectionFactory = connectionFactory;
+ }
+
+ public int getProfileCount(String URL, String username, String password) throws SQLException {
+ String q = "select count(*) from fn_app";
+ int count = 0;
+ try (Connection dbc = connectionFactory.getConnection(URL, username, password);
+ PreparedStatement pst = dbc.prepareStatement(q); ResultSet rs = pst.executeQuery()) {
+ logger.debug(EELFLoggerDelegate.debugLogger, "getConnection:::", dbc);
+ if (rs.next()) {
+ count = rs.getInt(1);
+ }
+ } catch (SQLException ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Failed to perform health check", ex);
+ throw ex;
}
- try {
- c.close();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to close connection", e);
- }
- }
-
- private static void closePreparedStatement(PreparedStatement st) {
- try {
- st.close();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to close statement", e);
- }
- }
- private static void closeResultSet(ResultSet rs) {
- try {
- rs.close();
- } catch (Exception e) {
- if (logger != null)
- logger.error("Error when trying to close result set", e);
- }
- }
+ logger.debug(EELFLoggerDelegate.debugLogger, "count:::", count);
+ return count;
+ }
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoException.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoException.java
new file mode 100644
index 000000000..02d54c354
--- /dev/null
+++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoException.java
@@ -0,0 +1,7 @@
+package org.onap.vid.mso;
+
+public class MsoException extends RuntimeException {
+ public MsoException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java
index 834f80885..7c8ab89c1 100644
--- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java
+++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoInterface.java
@@ -20,13 +20,15 @@
*/
package org.onap.vid.mso;
+import com.fasterxml.jackson.core.JsonProcessingException;
import io.joshworks.restclient.http.HttpResponse;
import io.joshworks.restclient.http.mapper.ObjectMapper;
-import lombok.SneakyThrows;
import org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider;
import org.onap.vid.changeManagement.RequestDetailsWrapper;
import org.onap.vid.mso.rest.RequestDetails;
+import java.io.IOException;
+
/**
* Created by pickjonathan on 21/06/2017.
*/
@@ -123,16 +125,22 @@ public interface MsoInterface {
return new ObjectMapper() {
CustomJacksonJaxBJsonProvider mapper = new CustomJacksonJaxBJsonProvider();
- @SneakyThrows
@Override
public <T> T readValue(String s, Class<T> aClass) {
- return mapper.getMapper().readValue(s, aClass);
+ try {
+ return mapper.getMapper().readValue(s, aClass);
+ } catch (IOException e) {
+ throw new MsoException(e);
+ }
}
- @SneakyThrows
@Override
public String writeValue(Object o) {
- return mapper.getMapper().writeValueAsString(o);
+ try {
+ return mapper.getMapper().writeValueAsString(o);
+ } catch (JsonProcessingException e) {
+ throw new MsoException(e);
+ }
}
};
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java b/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java
index 45835d459..b83f751fe 100644
--- a/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java
+++ b/vid-app-common/src/main/java/org/onap/vid/roles/RoleProvider.java
@@ -1,7 +1,29 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.vid.roles;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
+import io.joshworks.restclient.http.HttpResponse;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.web.support.UserUtils;
import org.onap.vid.aai.AaiResponse;
@@ -16,8 +38,6 @@ import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
-//import org.codehaus.jackson.map.ObjectMapper;
-
/**
* Created by Oren on 7/1/17.
*/
@@ -40,21 +60,21 @@ public class RoleProvider {
public void init() {
LOG.debug(EELFLoggerDelegate.debugLogger, "Role provider => init method started");
- AaiResponse<SubscriberList> subscribersResponse = aaiService.getFullSubscriberList();
- subscribers = subscribersResponse.getT();
+ HttpResponse<SubscriberList> subscribersResponse = aaiService.getFullSubscriberList();
+ subscribers = subscribersResponse.getBody();
LOG.debug(EELFLoggerDelegate.debugLogger, "Role provider => init method finished");
}
- public List<Role> getUserRoles(HttpServletRequest request) throws JsonProcessingException {
+ public List<Role> getUserRoles(HttpServletRequest request) {
String logPrefix = "Role Provider (" + UserUtils.getUserId(request) + ") ==>";
LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Entering to get user role for user " + UserUtils.getUserId(request));
List<Role> roleList = new ArrayList<>();
- //Disable roles until AAF integration finishes
- /*HashMap roles = UserUtils.getRoles(request);
+
+ Map roles = UserUtils.getRoles(request);
for (Object role : roles.keySet()) {
- org.openecomp.portalsdk.core.domain.Role sdkRol = (org.openecomp.portalsdk.core.domain.Role) roles.get(role);
+ org.onap.portalsdk.core.domain.Role sdkRol = (org.onap.portalsdk.core.domain.Role) roles.get(role);
LOG.debug(EELFLoggerDelegate.debugLogger, logPrefix + "Role " + sdkRol.getName() + " is being proccessed");
try {
@@ -67,11 +87,11 @@ public class RoleProvider {
roleList.add(createRoleFromStringArr(roleParts, logPrefix));
String msg = String.format(logPrefix + " User %s got permissions %s", UserUtils.getUserId(request), Arrays.toString(roleParts));
LOG.debug(EELFLoggerDelegate.debugLogger, msg);
- } catch (RoleParsingException e) {
+ } catch (Exception e) {
LOG.error(logPrefix + " Failed to parse permission");
}
- }*/
+ }
return roleList;
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java b/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java
index f3e0bfdab..d2ee32cbc 100644
--- a/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java
+++ b/vid-app-common/src/main/java/org/onap/vid/services/AaiService.java
@@ -1,5 +1,27 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.vid.services;
+import io.joshworks.restclient.http.HttpResponse;
import org.onap.vid.aai.AaiResponse;
import org.onap.vid.aai.AaiResponseTranslator;
import org.onap.vid.aai.SubscriberFilteredResults;
@@ -28,7 +50,7 @@ public interface AaiService {
AaiResponse getServiceInstanceSearchResults(String subscriberId, String instanceIdentifier, RoleValidator roleProvider, List<String> owningEntities, List<String> projects);
- AaiResponse<SubscriberList> getFullSubscriberList();
+ HttpResponse<SubscriberList> getFullSubscriberList();
AaiResponse getServices(RoleValidator roleValidator);
diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java
index 4de2cc740..c5bee2448 100644
--- a/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java
+++ b/vid-app-common/src/main/java/org/onap/vid/services/AaiServiceImpl.java
@@ -1,5 +1,27 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.vid.services;
+import io.joshworks.restclient.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.codehaus.jackson.JsonNode;
import org.onap.vid.aai.*;
@@ -30,6 +52,7 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
+import org.springframework.beans.factory.annotation.Qualifier;
/**
* Created by Oren on 7/4/17.
@@ -45,6 +68,10 @@ public class AaiServiceImpl implements AaiService {
private AaiClientInterface aaiClient;
@Autowired
+ @Qualifier("aaiClientForCodehausMapping")
+ private AaiOverTLSClientInterface aaiOverTLSClient;
+
+ @Autowired
private AaiResponseTranslator aaiResponseTranslator;
private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiServiceImpl.class);
@@ -162,11 +189,13 @@ public class AaiServiceImpl implements AaiService {
@Override
public SubscriberFilteredResults getFullSubscriberList(RoleValidator roleValidator) {
- AaiResponse<SubscriberList> subscriberResponse = aaiClient.getAllSubscribers();
-
- return new SubscriberFilteredResults(roleValidator, subscriberResponse.getT(),
- subscriberResponse.getErrorMessage(),
- subscriberResponse.getHttpCode());
+ HttpResponse<SubscriberList> allSubscribers = aaiOverTLSClient.getAllSubscribers();
+ return new SubscriberFilteredResults(
+ roleValidator,
+ allSubscribers.getBody(),
+ allSubscribers.getStatusText(),
+ allSubscribers.getStatus()
+ );
}
@Override
@@ -175,8 +204,8 @@ public class AaiServiceImpl implements AaiService {
}
@Override
- public AaiResponse<SubscriberList> getFullSubscriberList() {
- return aaiClient.getAllSubscribers();
+ public HttpResponse<SubscriberList> getFullSubscriberList() {
+ return aaiOverTLSClient.getAllSubscribers();
}
@Override
diff --git a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java
index 7259301a8..df8e92d66 100644
--- a/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java
+++ b/vid-app-common/src/main/java/org/onap/vid/services/AsyncInstantiationBusinessLogicImpl.java
@@ -1,10 +1,35 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.vid.services;
import com.google.common.collect.ImmutableMap;
+import io.joshworks.restclient.http.HttpResponse;
+import java.io.IOException;
import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SessionFactory;
import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.aai.AaiOverTLSClientInterface;
import org.onap.vid.aai.AaiResponse;
import org.onap.vid.aai.exceptions.InvalidAAIResponseException;
import org.onap.vid.aai.model.AaiNodeQueryResponse;
@@ -35,6 +60,7 @@ import org.onap.vid.utils.DaoUtils;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.service.DataAccessService;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
@@ -50,7 +76,7 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
private static final int MAX_RETRIES_GETTING_COUNTER = 100;
private static final int MAX_RETRIES_GETTING_FREE_NAME_FROM_AAI = 10000;
- public static final String NAME_FOR_CHECK_AAI_STATUS = "NAME_FOR_CHECK_AAI_STATUS";
+ private static final String NAME_FOR_CHECK_AAI_STATUS = "NAME_FOR_CHECK_AAI_STATUS";
private final DataAccessService dataAccessService;
@@ -60,60 +86,62 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
private SessionFactory sessionFactory;
- private AaiClientInterface aaiClient;
+ private AaiOverTLSClientInterface aaiOverTLSClient;
private int maxRetriesGettingFreeNameFromAai = MAX_RETRIES_GETTING_FREE_NAME_FROM_AAI;
- private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AsyncInstantiationBusinessLogicImpl.class);
+ private static final EELFLoggerDelegate logger = EELFLoggerDelegate
+ .getLogger(AsyncInstantiationBusinessLogicImpl.class);
private Map<String, JobStatus> msoStateToJobStatusMap = ImmutableMap.<String, JobStatus>builder()
- .put("inprogress", JobStatus.IN_PROGRESS)
- .put("failed", JobStatus.FAILED)
- .put("pause", JobStatus.PAUSE)
- .put("paused", JobStatus.PAUSE)
- .put("complete", JobStatus.COMPLETED)
- .put("pending", JobStatus.IN_PROGRESS)
- .put("pendingmanualtask", JobStatus.PAUSE)
- .put("unlocked", JobStatus.IN_PROGRESS)
- .build();
+ .put("inprogress", JobStatus.IN_PROGRESS)
+ .put("failed", JobStatus.FAILED)
+ .put("pause", JobStatus.PAUSE)
+ .put("paused", JobStatus.PAUSE)
+ .put("complete", JobStatus.COMPLETED)
+ .put("pending", JobStatus.IN_PROGRESS)
+ .put("pendingmanualtask", JobStatus.PAUSE)
+ .put("unlocked", JobStatus.IN_PROGRESS)
+ .build();
@Autowired
public AsyncInstantiationBusinessLogicImpl(DataAccessService dataAccessService,
- JobAdapter jobAdapter,
- JobsBrokerService jobService,
- SessionFactory sessionFactory,
- AaiClientInterface aaiClient) {
+ JobAdapter jobAdapter,
+ JobsBrokerService jobService,
+ SessionFactory sessionFactory,
+ @Qualifier("aaiClientForFasterXmlMapping") AaiOverTLSClientInterface aaiOverTLSClient) {
this.dataAccessService = dataAccessService;
this.jobAdapter = jobAdapter;
this.jobService = jobService;
this.sessionFactory = sessionFactory;
- this.aaiClient = aaiClient;
+ this.aaiOverTLSClient = aaiOverTLSClient;
}
@Override
public List<ServiceInfo> getAllServicesInfo() {
- return dataAccessService.getList(ServiceInfo.class, filterByCreationDateAndNotDeleted(), orderByCreatedDateAndStatus(), null);
+ return dataAccessService
+ .getList(ServiceInfo.class, filterByCreationDateAndNotDeleted(), orderByCreatedDateAndStatus(), null);
}
private String filterByCreationDateAndNotDeleted() {
LocalDateTime minus3Months = LocalDateTime.now().minusMonths(3);
Timestamp filterDate = Timestamp.valueOf(minus3Months);
return " where" +
- " hidden = false" +
- " and deleted_at is null" + // don't fetch deleted
- " and created >= '" + filterDate + "' ";
+ " hidden = false" +
+ " and deleted_at is null" + // don't fetch deleted
+ " and created >= '" + filterDate + "' ";
}
private String orderByCreatedDateAndStatus() {
return " createdBulkDate DESC ,\n" +
- " (CASE jobStatus\n" +
- " WHEN 'COMPLETED' THEN 0\n" +
- " WHEN 'FAILED' THEN 0\n" +
- " WHEN 'IN_PROGRESS' THEN 1\n" +
- " WHEN 'PAUSE' THEN 2\n" +
- " WHEN 'PENDING' THEN 3\n" +
- " WHEN 'STOPPED' THEN 3 END),\n" +
- " statusModifiedDate ";
+ " (CASE jobStatus\n" +
+ " WHEN 'COMPLETED' THEN 0\n" +
+ " WHEN 'FAILED' THEN 0\n" +
+ " WHEN 'IN_PROGRESS' THEN 1\n" +
+ " WHEN 'PAUSE' THEN 2\n" +
+ " WHEN 'PENDING' THEN 3\n" +
+ " WHEN 'STOPPED' THEN 3 END),\n" +
+ " statusModifiedDate ";
}
@Override
@@ -125,77 +153,87 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
for (int i = 0; i < bulkSize; i++) {
Job job = jobAdapter.createJob(JobType.ServiceInstantiation, request, templateId, userId, i);
UUID jobId = jobService.add(job);
- auditVidStatus(jobId,job.getStatus());
+ auditVidStatus(jobId, job.getStatus());
uuids.add(jobId);
- dataAccessService.saveDomainObject(createServiceInfo(userId, request, jobId, templateId, createdBulkDate), DaoUtils.getPropsMap());
+ dataAccessService.saveDomainObject(createServiceInfo(userId, request, jobId, templateId, createdBulkDate),
+ DaoUtils.getPropsMap());
}
return uuids;
}
- private ServiceInfo createServiceInfo(String userId, ServiceInstantiation serviceInstantiation, UUID jobId, UUID templateId, Date createdBulkDate) {
+ private ServiceInfo createServiceInfo(String userId, ServiceInstantiation serviceInstantiation, UUID jobId,
+ UUID templateId, Date createdBulkDate) {
return new ServiceInfo(
- userId, Job.JobStatus.PENDING, serviceInstantiation.isPause(), jobId, templateId,
- serviceInstantiation.getOwningEntityId(),
- serviceInstantiation.getOwningEntityName(),
- serviceInstantiation.getProjectName(),
- serviceInstantiation.getAicZoneId(),
- serviceInstantiation.getAicZoneName(),
- serviceInstantiation.getTenantId(),
- serviceInstantiation.getTenantName(),
- serviceInstantiation.getLcpCloudRegionId(),
- null,
- serviceInstantiation.getSubscriptionServiceType(),
- serviceInstantiation.getSubscriberName(),
- null,
- serviceInstantiation.getInstanceName(),
- serviceInstantiation.getModelInfo().getModelInvariantId(),
- serviceInstantiation.getModelInfo().getModelName(),
- serviceInstantiation.getModelInfo().getModelVersion(),
- createdBulkDate
+ userId, Job.JobStatus.PENDING, serviceInstantiation.isPause(), jobId, templateId,
+ serviceInstantiation.getOwningEntityId(),
+ serviceInstantiation.getOwningEntityName(),
+ serviceInstantiation.getProjectName(),
+ serviceInstantiation.getAicZoneId(),
+ serviceInstantiation.getAicZoneName(),
+ serviceInstantiation.getTenantId(),
+ serviceInstantiation.getTenantName(),
+ serviceInstantiation.getLcpCloudRegionId(),
+ null,
+ serviceInstantiation.getSubscriptionServiceType(),
+ serviceInstantiation.getSubscriberName(),
+ null,
+ serviceInstantiation.getInstanceName(),
+ serviceInstantiation.getModelInfo().getModelInvariantId(),
+ serviceInstantiation.getModelInfo().getModelName(),
+ serviceInstantiation.getModelInfo().getModelVersion(),
+ createdBulkDate
);
}
@Override
- public RequestDetailsWrapper<ServiceInstantiationRequestDetails> generateServiceInstantiationRequest(UUID jobId, ServiceInstantiation payload, String userId) {
+ public RequestDetailsWrapper<ServiceInstantiationRequestDetails> generateServiceInstantiationRequest(UUID jobId,
+ ServiceInstantiation payload, String userId) {
- ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity owningEntity = new ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity(payload.getOwningEntityId(), payload.getOwningEntityName());
+ ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity owningEntity = new ServiceInstantiationRequestDetails.ServiceInstantiationOwningEntity(
+ payload.getOwningEntityId(), payload.getOwningEntityName());
SubscriberInfo subscriberInfo = new SubscriberInfo();
subscriberInfo.setGlobalSubscriberId(payload.getGlobalSubscriberId());
String serviceInstanceName = null;
- if(payload.isUserProvidedNaming()) {
+ if (payload.isUserProvidedNaming()) {
serviceInstanceName = getUniqueName(payload.getInstanceName(), ResourceType.SERVICE_INSTANCE);
String finalServiceInstanceName = serviceInstanceName;
updateServiceInfo(jobId, x -> x.setServiceInstanceName(finalServiceInstanceName));
}
ServiceInstantiationRequestDetails.RequestInfo requestInfo = new ServiceInstantiationRequestDetails.RequestInfo(
- serviceInstanceName,
- payload.getProductFamilyId(),
- "VID",
- payload.isRollbackOnFailure(),
- userId);
+ serviceInstanceName,
+ payload.getProductFamilyId(),
+ "VID",
+ payload.isRollbackOnFailure(),
+ userId);
List<ServiceInstantiationRequestDetails.ServiceInstantiationService> serviceInstantiationService = new LinkedList<>();
- List<Map<String, String>> unFilteredInstanceParams = payload.getInstanceParams() != null ? payload.getInstanceParams() : new LinkedList<>();
+ List<Map<String, String>> unFilteredInstanceParams =
+ payload.getInstanceParams() != null ? payload.getInstanceParams() : new LinkedList<>();
List<Map<String, String>> filteredInstanceParams = removeUnNeededParams(unFilteredInstanceParams);
ServiceInstantiationRequestDetails.ServiceInstantiationService serviceInstantiationService1 = new ServiceInstantiationRequestDetails.ServiceInstantiationService(
- payload.getModelInfo(),
- serviceInstanceName,
- filteredInstanceParams,
- createServiceInstantiationVnfList(payload)
+ payload.getModelInfo(),
+ serviceInstanceName,
+ filteredInstanceParams,
+ createServiceInstantiationVnfList(payload)
);
serviceInstantiationService.add(serviceInstantiationService1);
- ServiceInstantiationRequestDetails.RequestParameters requestParameters = new ServiceInstantiationRequestDetails.RequestParameters(payload.getSubscriptionServiceType(), false, serviceInstantiationService);
+ ServiceInstantiationRequestDetails.RequestParameters requestParameters = new ServiceInstantiationRequestDetails.RequestParameters(
+ payload.getSubscriptionServiceType(), false, serviceInstantiationService);
- ServiceInstantiationRequestDetails.Project project = payload.getProjectName() != null ? new ServiceInstantiationRequestDetails.Project(payload.getProjectName()) : null;
+ ServiceInstantiationRequestDetails.Project project =
+ payload.getProjectName() != null ? new ServiceInstantiationRequestDetails.Project(payload.getProjectName())
+ : null;
- ServiceInstantiationRequestDetails requestDetails = new ServiceInstantiationRequestDetails(payload.getModelInfo(), owningEntity, subscriberInfo,
- project, requestInfo, requestParameters);
+ ServiceInstantiationRequestDetails requestDetails = new ServiceInstantiationRequestDetails(
+ payload.getModelInfo(), owningEntity, subscriberInfo,
+ project, requestInfo, requestParameters);
- RequestDetailsWrapper<ServiceInstantiationRequestDetails> requestDetailsWrapper = new RequestDetailsWrapper(requestDetails);
+ RequestDetailsWrapper<ServiceInstantiationRequestDetails> requestDetailsWrapper = new RequestDetailsWrapper(
+ requestDetails);
debugRequestDetails(requestDetailsWrapper, logger);
return requestDetailsWrapper;
}
@@ -204,10 +242,11 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
List<String> keysToRemove = new ArrayList<>();
if (instanceParams != null && !instanceParams.isEmpty()) {
for (String key : instanceParams.get(0).keySet()) {
- for (String paramToIgnore : PARAMS_TO_IGNORE)
+ for (String paramToIgnore : PARAMS_TO_IGNORE) {
if ((key.equalsIgnoreCase(paramToIgnore))) {
keysToRemove.add(key);
}
+ }
}
for (String key : keysToRemove) {
instanceParams.get(0).remove(key);
@@ -220,7 +259,8 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
return instanceParams;
}
- private ServiceInstantiationRequestDetails.ServiceInstantiationVnfList createServiceInstantiationVnfList(ServiceInstantiation payload) {
+ private ServiceInstantiationRequestDetails.ServiceInstantiationVnfList createServiceInstantiationVnfList(
+ ServiceInstantiation payload) {
CloudConfiguration cloudConfiguration = new CloudConfiguration();
cloudConfiguration.setTenantId(payload.getTenantId());
cloudConfiguration.setLcpCloudRegionId(payload.getLcpCloudRegionId());
@@ -230,16 +270,17 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
for (Vnf vnf : vnfs.values()) {
Map<String, Map<String, VfModule>> vfModules = vnf.getVfModules();
List<VfModule> convertedUnFilteredVfModules = convertVfModuleMapToList(vfModules);
- List<VfModule> filteredVfModules = filterInstanceParamsFromVfModuleAndUniqueNames(convertedUnFilteredVfModules, vnf.isUserProvidedNaming());
+ List<VfModule> filteredVfModules = filterInstanceParamsFromVfModuleAndUniqueNames(
+ convertedUnFilteredVfModules, vnf.isUserProvidedNaming());
ServiceInstantiationRequestDetails.ServiceInstantiationVnf serviceInstantiationVnf = new ServiceInstantiationRequestDetails.ServiceInstantiationVnf(
- vnf.getModelInfo(),
- cloudConfiguration,
- vnf.getPlatformName(),
- vnf.getLineOfBusiness(),
- payload.getProductFamilyId(),
- removeUnNeededParams(vnf.getInstanceParams()),
- filteredVfModules,
- vnf.isUserProvidedNaming() ? getUniqueName(vnf.getInstanceName(), ResourceType.GENERIC_VNF) : null
+ vnf.getModelInfo(),
+ cloudConfiguration,
+ vnf.getPlatformName(),
+ vnf.getLineOfBusiness(),
+ payload.getProductFamilyId(),
+ removeUnNeededParams(vnf.getInstanceParams()),
+ filteredVfModules,
+ vnf.isUserProvidedNaming() ? getUniqueName(vnf.getInstanceName(), ResourceType.GENERIC_VNF) : null
);
vnfList.add(serviceInstantiationVnf);
}
@@ -251,27 +292,29 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
return vfModules.values().stream().flatMap(vfModule -> vfModule.values().stream()).collect(Collectors.toList());
}
- private List<VfModule> filterInstanceParamsFromVfModuleAndUniqueNames(List<VfModule> unFilteredVfModules, boolean isUserProvidedNaming) {
+ private List<VfModule> filterInstanceParamsFromVfModuleAndUniqueNames(List<VfModule> unFilteredVfModules,
+ boolean isUserProvidedNaming) {
return unFilteredVfModules.stream().map(vfModule ->
- new VfModule(
- vfModule.getModelInfo(),
- getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getInstanceName(), ResourceType.VF_MODULE),
- getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getVolumeGroupInstanceName(), ResourceType.VOLUME_GROUP),
- removeUnNeededParams(vfModule.getInstanceParams())))
- .collect(Collectors.toList());
+ new VfModule(
+ vfModule.getModelInfo(),
+ getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getInstanceName(), ResourceType.VF_MODULE),
+ getUniqueNameIfNeeded(isUserProvidedNaming, vfModule.getVolumeGroupInstanceName(),
+ ResourceType.VOLUME_GROUP),
+ removeUnNeededParams(vfModule.getInstanceParams())))
+ .collect(Collectors.toList());
}
private String getUniqueNameIfNeeded(boolean isUserProvidedNaming, String name, ResourceType resourceType) {
return isUserProvidedNaming && !StringUtils.isEmpty(name) ?
- getUniqueName(name, resourceType) : null;
+ getUniqueName(name, resourceType) : null;
}
@Override
public String getServiceInstantiationPath(ServiceInstantiation serviceInstantiationRequest) {
//in case pause flag is true - use assign , else - use create.
return MsoBusinessLogicImpl.validateEndpointPath(
- serviceInstantiationRequest.isPause() ?
- "mso.restapi.serviceInstanceAssign" : "mso.restapi.serviceInstanceCreate"
+ serviceInstantiationRequest.isPause() ?
+ "mso.restapi.serviceInstanceAssign" : "mso.restapi.serviceInstanceCreate"
);
}
@@ -290,7 +333,7 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
@Override
public ServiceInfo updateServiceInfoAndAuditStatus(UUID jobUuid, JobStatus jobStatus) {
- auditVidStatus(jobUuid,jobStatus);
+ auditVidStatus(jobUuid, jobStatus);
return updateServiceInfo(jobUuid, x -> setServiceInfoStatus(x, jobStatus));
}
@@ -300,9 +343,12 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
}
public ServiceInfo getServiceInfoByJobId(UUID jobUUID) {
- List<ServiceInfo> serviceInfoList = dataAccessService.getList(ServiceInfo.class, String.format(" where jobId = '%s' ", jobUUID), null, null);
+ List<ServiceInfo> serviceInfoList = dataAccessService
+ .getList(ServiceInfo.class, String.format(" where jobId = '%s' ", jobUUID), null, null);
if (serviceInfoList.size() != 1) {
- throw new GenericUncheckedException("Failed to retrieve job with uuid " + jobUUID + " from ServiceInfo table. Instances found: " + serviceInfoList.size());
+ throw new GenericUncheckedException(
+ "Failed to retrieve job with uuid " + jobUUID + " from ServiceInfo table. Instances found: "
+ + serviceInfoList.size());
}
return serviceInfoList.get(0);
}
@@ -310,43 +356,46 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
public List<JobAuditStatus> getAuditStatuses(UUID jobUUID, JobAuditStatus.SourceStatus source) {
return dataAccessService.getList(
JobAuditStatus.class,
- String.format(" where SOURCE = '%s' and JOB_ID = '%s'",source, jobUUID),
+ String.format(" where SOURCE = '%s' and JOB_ID = '%s'", source, jobUUID),
" CREATED_DATE ", null);
}
- private JobAuditStatus getLatestAuditStatus(UUID jobUUID, JobAuditStatus.SourceStatus source){
- List<JobAuditStatus> list = getAuditStatuses(jobUUID,source);
- return !list.isEmpty() ? list.get(list.size()-1) : null;
+ private JobAuditStatus getLatestAuditStatus(UUID jobUUID, JobAuditStatus.SourceStatus source) {
+ List<JobAuditStatus> list = getAuditStatuses(jobUUID, source);
+ return !list.isEmpty() ? list.get(list.size() - 1) : null;
}
@Override
- public void auditVidStatus(UUID jobUUID, JobStatus jobStatus){
+ public void auditVidStatus(UUID jobUUID, JobStatus jobStatus) {
JobAuditStatus vidStatus = new JobAuditStatus(jobUUID, jobStatus.toString(), JobAuditStatus.SourceStatus.VID);
auditStatus(vidStatus);
}
@Override
- public void auditMsoStatus(UUID jobUUID, AsyncRequestStatus.Request msoRequestStatus){
- auditMsoStatus(jobUUID, msoRequestStatus.requestStatus.getRequestState(), msoRequestStatus.requestId, msoRequestStatus.requestStatus.getStatusMessage());
+ public void auditMsoStatus(UUID jobUUID, AsyncRequestStatus.Request msoRequestStatus) {
+ auditMsoStatus(jobUUID, msoRequestStatus.requestStatus.getRequestState(), msoRequestStatus.requestId,
+ msoRequestStatus.requestStatus.getStatusMessage());
}
@Override
- public void auditMsoStatus(UUID jobUUID, String jobStatus, String requestId, String additionalInfo){
+ public void auditMsoStatus(UUID jobUUID, String jobStatus, String requestId, String additionalInfo) {
JobAuditStatus msoStatus = new JobAuditStatus(jobUUID, jobStatus, JobAuditStatus.SourceStatus.MSO,
- requestId != null ? UUID.fromString(requestId) : null,
- additionalInfo);
+ requestId != null ? UUID.fromString(requestId) : null,
+ additionalInfo);
auditStatus(msoStatus);
}
- private void auditStatus(JobAuditStatus jobAuditStatus){
- JobAuditStatus latestStatus = getLatestAuditStatus(jobAuditStatus.getJobId(),jobAuditStatus.getSource());
- if (latestStatus == null || !latestStatus.equals(jobAuditStatus))
+ private void auditStatus(JobAuditStatus jobAuditStatus) {
+ JobAuditStatus latestStatus = getLatestAuditStatus(jobAuditStatus.getJobId(), jobAuditStatus.getSource());
+ if (latestStatus == null || !latestStatus.equals(jobAuditStatus)) {
dataAccessService.saveDomainObject(jobAuditStatus, DaoUtils.getPropsMap());
+ }
}
public Job.JobStatus calcStatus(AsyncRequestStatus asyncRequestStatus) {
- String msoRequestState = asyncRequestStatus.request.requestStatus.getRequestState().toLowerCase().replaceAll("[^a-z]+", "");
+ String msoRequestState = asyncRequestStatus.request.requestStatus.getRequestState().toLowerCase()
+ .replaceAll("[^a-z]+", "");
JobStatus jobStatus = msoStateToJobStatusMap.get(msoRequestState);
return (jobStatus != null ? jobStatus : JobStatus.IN_PROGRESS);
}
@@ -355,11 +404,11 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
public void handleFailedInstantiation(UUID jobUUID) {
ServiceInfo serviceInfo = updateServiceInfoAndAuditStatus(jobUUID, JobStatus.FAILED);
List<ServiceInfo> serviceInfoList = dataAccessService.getList(
- ServiceInfo.class,
- String.format(" where templateId = '%s' and jobStatus = '%s'",
- serviceInfo.getTemplateId(),
- JobStatus.PENDING),
- null, null);
+ ServiceInfo.class,
+ String.format(" where templateId = '%s' and jobStatus = '%s'",
+ serviceInfo.getTemplateId(),
+ JobStatus.PENDING),
+ null, null);
serviceInfoList.forEach(si -> updateServiceInfoAndAuditStatus(si.getJobId(), JobStatus.STOPPED));
}
@@ -374,9 +423,9 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
public void hideServiceInfo(UUID jobUUID) {
ServiceInfo serviceInfo = getServiceInfoByJobId(jobUUID);
if (!serviceInfo.getJobStatus().isFinal()) {
- String message = String.format( "jobId %s: Service status does not allow hide service, status = %s",
- serviceInfo.getJobId(),
- serviceInfo.getJobStatus());
+ String message = String.format("jobId %s: Service status does not allow hide service, status = %s",
+ serviceInfo.getJobId(),
+ serviceInfo.getJobStatus());
logger.error(EELFLoggerDelegate.errorLogger, message);
throw new OperationNotAllowedException(message);
}
@@ -387,31 +436,29 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
@Override
public int
-
getCounterForName(String name) {
String hqlSelectNC = "from NameCounter where name = :name";
String hqlUpdateCounter = "update NameCounter set counter = :newCounter " +
- "where name= :name " +
- "and counter= :prevCounter";
+ "where name= :name " +
+ "and counter= :prevCounter";
Integer counter = null;
GenericUncheckedException lastException = null;
- for (int i = 0; i< MAX_RETRIES_GETTING_COUNTER && counter==null; i++) {
+ for (int i = 0; i < MAX_RETRIES_GETTING_COUNTER && counter == null; i++) {
try {
counter = calcCounter(name, hqlSelectNC, hqlUpdateCounter);
- }
- catch (GenericUncheckedException exception) {
+ } catch (GenericUncheckedException exception) {
lastException = exception; //do nothing, we will try again in the loop
}
}
- if (counter!=null) {
+ if (counter != null) {
return counter;
}
- throw lastException!=null ? new DbFailureUncheckedException(lastException) :
- new DbFailureUncheckedException("Failed to get counter for "+name+" due to unknown error");
+ throw lastException != null ? new DbFailureUncheckedException(lastException) :
+ new DbFailureUncheckedException("Failed to get counter for " + name + " due to unknown error");
}
@@ -419,14 +466,14 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
Integer counter;
counter = DaoUtils.tryWithSessionAndTransaction(sessionFactory, session -> {
NameCounter nameCounter = (NameCounter) session.createQuery(hqlSelectNC)
- .setText("name", name)
- .uniqueResult();
+ .setText("name", name)
+ .uniqueResult();
if (nameCounter != null) {
int updatedRows = session.createQuery(hqlUpdateCounter)
- .setText("name", nameCounter.getName())
- .setInteger("prevCounter", nameCounter.getCounter())
- .setInteger("newCounter", nameCounter.getCounter() + 1)
- .executeUpdate();
+ .setText("name", nameCounter.getName())
+ .setInteger("prevCounter", nameCounter.getCounter())
+ .setInteger("newCounter", nameCounter.getCounter() + 1)
+ .executeUpdate();
if (updatedRows == 1) {
return nameCounter.getCounter() + 1;
}
@@ -459,7 +506,7 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
//Prevents unnecessary increasing of the counter while AAI doesn't response
isNameFreeInAai(NAME_FOR_CHECK_AAI_STATUS, resourceType);
- for (int i=0; i<getMaxRetriesGettingFreeNameFromAai(); i++) {
+ for (int i = 0; i < getMaxRetriesGettingFreeNameFromAai(); i++) {
int counter = getCounterForName(name);
String newName = formatNameAndCounter(name, counter);
if (isNameFreeInAai(newName, resourceType)) {
@@ -467,7 +514,7 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
}
}
- throw new MaxRetriesException("find unused name for "+name, getMaxRetriesGettingFreeNameFromAai());
+ throw new MaxRetriesException("find unused name for " + name, getMaxRetriesGettingFreeNameFromAai());
}
//the method is protected so we can call it in the UT
@@ -476,11 +523,17 @@ public class AsyncInstantiationBusinessLogicImpl implements AsyncInstantiationBu
}
private boolean isNameFreeInAai(String name, ResourceType resourceType) throws InvalidAAIResponseException {
- AaiResponse<AaiNodeQueryResponse> aaiResponse = aaiClient.searchNodeTypeByName(name, resourceType);
- if (aaiResponse.getHttpCode() > 399 || aaiResponse.getT() == null) {
- throw new InvalidAAIResponseException(aaiResponse);
+ HttpResponse<AaiNodeQueryResponse> aaiResponse = aaiOverTLSClient
+ .searchNodeTypeByName(name, resourceType);
+ if (aaiResponse.getStatus() > 399 || aaiResponse.getBody() == null) {
+ try {
+ String message = IOUtils.toString(aaiResponse.getRawBody(), "UTF-8");
+ throw new InvalidAAIResponseException(aaiResponse.getStatus(), message);
+ } catch (IOException e) {
+ throw new InvalidAAIResponseException(aaiResponse.getStatus(), aaiResponse.getStatusText());
+ }
}
- return CollectionUtils.isEmpty(aaiResponse.getT().resultData);
+ return CollectionUtils.isEmpty(aaiResponse.getBody().resultData);
}
}
diff --git a/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java b/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java
index 635cb4855..500f5ac7f 100644
--- a/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java
+++ b/vid-app-common/src/main/java/org/onap/vid/services/RoleGenaratorServiceImpl.java
@@ -1,7 +1,30 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * VID
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2018 Nokia. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
package org.onap.vid.services;
+import io.joshworks.restclient.http.HttpResponse;
import jline.internal.Log;
import org.onap.vid.aai.AaiClientInterface;
+import org.onap.vid.aai.AaiOverTLSClientInterface;
import org.onap.vid.aai.AaiResponse;
import org.onap.vid.aai.ServiceSubscription;
import org.onap.vid.aai.Services;
@@ -9,6 +32,7 @@ import org.onap.vid.model.ModelConstants;
import org.onap.vid.model.Subscriber;
import org.onap.vid.model.SubscriberList;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.HashMap;
@@ -17,9 +41,14 @@ import java.util.HashMap;
public class RoleGenaratorServiceImpl implements RoleGeneratorService {
public static final String ROLE_ID_COLUMN = "ROLE_ID";
+
@Autowired
AaiClientInterface client;
+ @Autowired
+ @Qualifier("aaiClientForCodehausMapping")
+ AaiOverTLSClientInterface aaiOverTLSClient;
+
public static final String DB_NAME = "vid_portal";
public static final String TBL_NAME = "fn_role";
public static final String TEMP_DELIMITER ="***";
@@ -30,11 +59,11 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService {
String query = "USE " + DB_NAME + ";\r\n" +
"SET SQL_SAFE_UPDATES = 0;\r\n";
try {
- AaiResponse<SubscriberList> subscribers = client.getAllSubscribers();
+ HttpResponse<SubscriberList> allSubscribers = aaiOverTLSClient.getAllSubscribers();
if (firstRun) {
- query += replaceRolesToTempDelimiter("subscriber",buildSubscribersValuesForMappingsTable(subscribers.getT()));
+ query += replaceRolesToTempDelimiter("subscriber",buildSubscribersValuesForMappingsTable(allSubscribers.getBody()));
}
- query += addAvailableRolesCombination(firstRun, subscribers);
+ query += addAvailableRolesCombination(firstRun, allSubscribers.getBody());
}
catch (Exception e) {
@@ -43,10 +72,10 @@ public class RoleGenaratorServiceImpl implements RoleGeneratorService {
return query;
}
- private String addAvailableRolesCombination(Boolean firstRun, AaiResponse<SubscriberList> subscribers) {
+ private String addAvailableRolesCombination(Boolean firstRun, SubscriberList subscribers) {
String query, availableRoles="";
HashMap<String,String> servicesNames = new HashMap<String,String>();
- for (Subscriber subscriber: subscribers.getT().customer) {
+ for (Subscriber subscriber: subscribers.customer) {
AaiResponse<Services> subscriberResponse = client.getSubscriberData(subscriber.globalCustomerId);
for(ServiceSubscription service: subscriberResponse.getT().serviceSubscriptions.serviceSubscription) {
servicesNames.put(service.serviceType,"");