diff options
43 files changed, 1454 insertions, 989 deletions
diff --git a/.gitignore b/.gitignore index 40efedd6b..978c4cbd7 100644 --- a/.gitignore +++ b/.gitignore @@ -4,33 +4,9 @@ epsdk-app-onap/target/ vid-app-common/target/ vid-parent_bdio.jsonld deliveries/target/ -/vid-app-common/debug-logs/EELF/debug.log -/vid-app-common/logs/EELF/application.log -/vid-app-common/logs/EELF/audit.log -/vid-app-common/logs/EELF/error.log -/vid-app-common/logs/EELF/metrics.log -/vid-app-common/logs/EELF/performance.log -/vid-app-common/logs/EELF/policy.log -/vid-app-common/logs/EELF/security.log -/vid-app-common/logs/EELF/server.log -/epsdk-app-onap/catalina.base_IS_UNDEFINED/logs/ep_sdk_app/application.log -/epsdk-app-onap/catalina.base_IS_UNDEFINED/logs/ep_sdk_app/audit.log -/epsdk-app-onap/catalina.base_IS_UNDEFINED/logs/ep_sdk_app/debug.log -/epsdk-app-onap/catalina.base_IS_UNDEFINED/logs/ep_sdk_app/error.log -/epsdk-app-onap/catalina.base_IS_UNDEFINED/logs/ep_sdk_app/metrics.log -/epsdk-app-onap/debug-logs/EELF/debug.log -/epsdk-app-onap/logs/EELF/application.log -/epsdk-app-onap/logs/EELF/audit.log -/epsdk-app-onap/logs/EELF/error.log -/epsdk-app-onap/logs/EELF/metrics.log -/epsdk-app-onap/logs/EELF/performance.log -/epsdk-app-onap/logs/EELF/policy.log -/epsdk-app-onap/logs/EELF/security.log -/epsdk-app-onap/logs/EELF/server.log -/vid-app-common/.idea/encodings.xml -/vid-app-common/.idea/misc.xml -/vid-app-common/.idea/modules.xml -/vid-app-common/.idea/vid-app-common.iml +*.log +*/.idea/ +*.iml /vid-app-common/.idea/workspace.xml /vid-app-common/.settings/org.eclipse.core.resources.prefs /vid-webpack-master/target/antrun/build-main.xml diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java index 4e0254cde..fdbf2c288 100644 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/AsdcClient.java @@ -29,7 +29,10 @@ import java.util.UUID; * The Interface AsdcClient. */ public interface AsdcClient { - + class URIS{ + public static final String METADATA_URL_TEMPLATE = "%s%s/%s/metadata"; + public static final String TOSCA_MODEL_URL_TEMPLATE = "%s%s/%s/toscaModel"; + } /** * Gets the service. * diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/RestfulAsdcClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/RestfulAsdcClient.java deleted file mode 100644 index 5dd0f4cce..000000000 --- a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/RestfulAsdcClient.java +++ /dev/null @@ -1,242 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.vid.asdc.rest; - -import com.att.eelf.configuration.EELFLogger; -import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; -import org.onap.portalsdk.core.util.SystemProperties; -import org.onap.vid.asdc.AsdcCatalogException; -import org.onap.vid.asdc.AsdcClient; -import org.onap.vid.asdc.beans.Service; -import org.onap.vid.model.ModelConstants; -import org.onap.vid.properties.VidProperties; -import org.onap.vid.utils.Logging; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.http.HttpMethod; - -import javax.ws.rs.ProcessingException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ResponseProcessingException; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardCopyOption; -import java.util.Collections; -import java.util.UUID; - -import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; -/** - * The Class RestfulAsdcClient. - */ -@SuppressWarnings("Duplicates") -public class RestfulAsdcClient implements AsdcClient { - - - /** - * The Class Builder. - */ - public static class Builder { - - /** - * The client. - */ - private final Client client; - - /** - * The uri. - */ - private final URI uri; - - /** - * The auth. - */ - private String auth = null; - - /** - * Instantiates a new builder. - * - * @param client the client - * @param uri the uri - */ - public Builder(Client client, URI uri) { - this.client = client; - this.client.register(JacksonJsonProvider.class); - this.uri = uri; - } - - /** - * Auth. - * - * @param auth the auth - * @return the builder - */ - public Builder auth(String auth) { - this.auth = auth; - return this; - } - - /** - * Builds the. - * - * @return the restful asdc client - */ - public RestfulAsdcClient build() { - return new RestfulAsdcClient(this); - } - } - - /** - * The Constant LOG. - */ - static final EELFLoggerDelegate LOG = EELFLoggerDelegate.getLogger(RestfulAsdcClient.class); - - final private static EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("asdc"); - - /** - * The client. - */ - private final Client client; - - /** - * The uri. - */ - private final URI uri; - - /** - * The common headers. - */ - private final MultivaluedHashMap<String, Object> commonHeaders; - - /** - * The auth. - */ - private final String auth; - - /** - * Instantiates a new restful asdc client. - * - * @param builder the builder - */ - RestfulAsdcClient(Builder builder) { - client = builder.client; - uri = builder.uri; - auth = builder.auth; - - commonHeaders = new MultivaluedHashMap<String, Object>(); - commonHeaders.put("X-ECOMP-InstanceID", Collections.singletonList((Object) (SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)))); - commonHeaders.put("Authorization", Collections.singletonList((Object) (auth))); - } - - private Path createTmpFile(InputStream csarInputStream) throws AsdcCatalogException { - final Path csarFile; - try { - csarFile = Files.createTempFile("csar", ".zip"); - Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING); - } catch (IOException e) { - throw new AsdcCatalogException("Caught IOException while creating CSAR", e); - } - return csarFile; - } - - /** - * Gets the client. - * - * @return the client - */ - private Client getClient() { - return client; - } - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getService(java.util.UUID) - */ - public Service getService(UUID uuid) throws AsdcCatalogException { - - String path = VidProperties.getPropertyWithDefault( - ModelConstants.ASDC_SVC_API_PATH, - ModelConstants.DEFAULT_ASDC_SVC_API_PATH); - - String url = uri+path + "/" + uuid.toString() + "/metadata"; - Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); - try { - Response response = getClient() - .target(uri) - .path(path + "/" + uuid.toString() + "/metadata") - .request(MediaType.APPLICATION_JSON) - .headers(commonHeaders) - .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) - .get(); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response); - return response.readEntity(Service.class); - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service", e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - - - /* (non-Javadoc) - * @see org.onap.vid.asdc.AsdcClient#getServiceToscaModel(java.util.UUID) - */ - public Path getServiceToscaModel(UUID serviceUuid) throws AsdcCatalogException { - String path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, - ModelConstants.DEFAULT_ASDC_SVC_API_PATH); - - String url = uri+path + "/" + serviceUuid + "/toscaModel"; - Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); - try { - final InputStream csarInputStream = getClient() - .target(uri) - .path(path + "/" + serviceUuid + "/toscaModel") - .request(MediaType.APPLICATION_OCTET_STREAM_TYPE) - .headers(commonHeaders) - .header("Content-Type", MediaType.APPLICATION_OCTET_STREAM) - .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) - .get(InputStream.class); - Path toscaFilePath = createTmpFile(csarInputStream); - outgoingRequestsLogger.debug("Received {} {} . Tosca file was saved at: {}", HttpMethod.GET.name(), url, toscaFilePath.toAbsolutePath()); - return toscaFilePath; - } catch (ResponseProcessingException e) { - //Couldn't convert response to Java type - throw new AsdcCatalogException("SDC response could not be processed", e); - } catch (ProcessingException e) { - //IO problems during request - throw new AsdcCatalogException("Failed to get a response from SDC service. Cause: "+e.getMessage(), e); - } catch (WebApplicationException e) { - //Web service returned data, but the response status wasn't a good one (i.e. non 2xx) - throw new AsdcCatalogException(e); - } - } - -} - diff --git a/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java new file mode 100644 index 000000000..b4096f9b2 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/asdc/rest/SdcRestClient.java @@ -0,0 +1,123 @@ +/*- + * ============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.asdc.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.google.common.collect.ImmutableMap; +import io.vavr.control.Try; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.AsdcClient; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.client.SyncRestClientInterface; +import org.onap.vid.model.ModelConstants; +import org.onap.vid.properties.VidProperties; +import org.onap.vid.utils.Logging; +import org.springframework.http.HttpMethod; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static javax.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM; +import static org.onap.portalsdk.core.util.SystemProperties.APP_DISPLAY_NAME; +import static org.onap.vid.asdc.AsdcClient.URIS.METADATA_URL_TEMPLATE; +import static org.onap.vid.asdc.AsdcClient.URIS.TOSCA_MODEL_URL_TEMPLATE; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.AUTHORIZATION; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.CONTENT_TYPE; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID; +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; +import static org.onap.vid.utils.Logging.logRequest; + +public class SdcRestClient implements AsdcClient { + + private String baseUrl; + private String path; + private String auth; + private static final EELFLogger LOGGER = Logging.getRequestsLogger("asdc"); + + private SyncRestClientInterface syncRestClient; + + + public SdcRestClient(String baseUrl, String auth, SyncRestClientInterface client) { + this.syncRestClient = client; + this.auth = auth; + this.baseUrl = baseUrl; + this.path = VidProperties.getPropertyWithDefault(ModelConstants.ASDC_SVC_API_PATH, ModelConstants.DEFAULT_ASDC_SVC_API_PATH); + } + + + @Override + public Service getService(UUID uuid) throws AsdcCatalogException { + String finalUrl = String.format(METADATA_URL_TEMPLATE, baseUrl, path, uuid); + logRequest(LOGGER, HttpMethod.GET, finalUrl); + + return Try + .of(() -> syncRestClient.get(finalUrl, prepareHeaders(auth, APPLICATION_JSON), Collections.emptyMap(), Service.class)) + .getOrElseThrow(AsdcCatalogException::new) + .getBody(); + + } + + @Override + public Path getServiceToscaModel(UUID uuid) throws AsdcCatalogException { + String finalUrl = String.format(TOSCA_MODEL_URL_TEMPLATE, baseUrl, path, uuid); + logRequest(LOGGER, HttpMethod.GET, finalUrl); + + InputStream inputStream = Try + .of(() -> syncRestClient.getStream(finalUrl, prepareHeaders(auth, APPLICATION_OCTET_STREAM), Collections.emptyMap())) + .getOrElseThrow(AsdcCatalogException::new) + .getBody(); + + return createTmpFile(inputStream); + } + + + private Map<String, String> prepareHeaders(String auth, String contentType) { + return ImmutableMap.of( + X_ECOMP_INSTANCE_ID, SystemProperties.getProperty(APP_DISPLAY_NAME), + AUTHORIZATION, auth, + REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId(), + CONTENT_TYPE, contentType + ); + } + + private Path createTmpFile(InputStream csarInputStream) throws AsdcCatalogException { + return Try + .of(() -> tryToCreateTmpFile(csarInputStream)) + .getOrElseThrow(throwable -> new AsdcCatalogException("Caught IOException while creating CSAR", throwable)); + } + + private Path tryToCreateTmpFile(InputStream csarInputStream) throws IOException { + Path csarFile = Files.createTempFile("csar", ".zip"); + Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING); + + LOGGER.debug("Tosca file was saved at: {} ", csarFile.toAbsolutePath()); + + return csarFile; + } +} diff --git a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientInterface.java b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientInterface.java index 80663d65b..142adde15 100644 --- a/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/client/SyncRestClientInterface.java @@ -2,16 +2,22 @@ package org.onap.vid.client; import io.joshworks.restclient.http.HttpResponse; import io.joshworks.restclient.http.JsonNode; + import java.io.InputStream; import java.util.Map; public interface SyncRestClientInterface { + class HEADERS { + public static final String CONTENT_TYPE = "Content-Type"; + public static final String AUTHORIZATION = "Authorization"; + public static final String X_ECOMP_INSTANCE_ID = "X-ECOMP-InstanceID"; + } HttpResponse<JsonNode> post(String url, Map<String, String> headers, Object body); <T> HttpResponse<T> post(String url, Map<String, String> headers, Object body, Class<T> aClass); - HttpResponse<JsonNode> get(String url, Map<String, String> headers, Map<String, String> routeParams); + HttpResponse<JsonNode> get(String url, Map<String, String> headers, Map<String, String> routeParams); <T> HttpResponse<T> get(String url, Map<String, String> headers, Map<String, String> routeParams, Class<T> aClass); @@ -19,9 +25,9 @@ public interface SyncRestClientInterface { HttpResponse<JsonNode> put(String url, Map<String, String> headers, Object body); - <T> HttpResponse<T> put(String url, Map<String, String> headers, Object body, Class<T> aClass); + <T> HttpResponse<T> put(String url, Map<String, String> headers, Object body, Class<T> aClass); - <T> HttpResponse<T> delete(String url, Map<String, String> headers, Class<T> aClass); + <T> HttpResponse<T> delete(String url, Map<String, String> headers, Class<T> aClass); HttpResponse<JsonNode> delete(String url, Map<String, String> headers); diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java index aa0b1ad3d..020018ade 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/MsoConfig.java @@ -1,10 +1,34 @@ +/*- + * ============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.controllers; import com.fasterxml.jackson.databind.ObjectMapper; +import org.onap.portalsdk.core.util.SystemProperties; + +import org.onap.vid.client.SyncRestClient; import org.onap.vid.factories.MsoRequestFactory; import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.rest.MsoRestClientNew; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -31,7 +55,8 @@ public class MsoConfig { @Bean public MsoInterface getMsoClient(){ - return new MsoRestClientNew(); + return new MsoRestClientNew(new SyncRestClient(MsoInterface.objectMapper()), SystemProperties.getProperty( + MsoProperties.MSO_SERVER_URL)); } @Bean diff --git a/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java b/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java index 3b6a3f784..6a4527cb4 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controllers/OperationalEnvironmentController.java @@ -1,20 +1,40 @@ +/*- + * ============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.controllers; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.MoreObjects; +import io.joshworks.restclient.http.HttpResponse; +import java.util.HashMap; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.model.ExceptionResponse; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.mso.MsoBusinessLogic; +import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.MsoResponseWrapper2; -import org.onap.vid.mso.RestMsoImplementation; -import org.onap.vid.mso.RestObject; import org.onap.vid.mso.model.OperationalEnvironmentActivateInfo; import org.onap.vid.mso.model.OperationalEnvironmentDeactivateInfo; -import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.OperationalEnvironment.OperationEnvironmentRequestDetails; import org.onap.vid.mso.rest.RequestDetails; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -24,7 +44,6 @@ import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; @@ -39,14 +58,14 @@ import static org.onap.vid.utils.Logging.getMethodName; @RequestMapping("operationalEnvironment") public class OperationalEnvironmentController extends VidRestrictedBaseController { - private final RestMsoImplementation restMso; + private final MsoInterface restMso; private final MsoBusinessLogic msoBusinessLogic; private static final Pattern RECOVERY_ACTION_MESSAGE_PATTERN = Pattern.compile("String value \'(.*)\': value not"); @Autowired - public OperationalEnvironmentController(MsoBusinessLogic msoBusinessLogic, MsoRestClientNew msoClientInterface) { + public OperationalEnvironmentController(MsoBusinessLogic msoBusinessLogic, MsoInterface msoClientInterface) { this.restMso = msoClientInterface; this.msoBusinessLogic = msoBusinessLogic; } @@ -57,8 +76,8 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle String userId = ControllersUtils.extractUserId(request); RequestDetailsWrapper<OperationEnvironmentRequestDetails> requestDetailsWrapper = msoBusinessLogic.convertParametersToRequestDetails(operationalEnvironment, userId); String path = msoBusinessLogic.getOperationalEnvironmentCreationPath(); - RestObject<RequestReferencesContainer> msoResponse = restMso.PostForObject(requestDetailsWrapper, "", - path, RequestReferencesContainer.class); + + HttpResponse<RequestReferencesContainer> msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); debugEnd(msoResponse); return new MsoResponseWrapper2<>(msoResponse); } @@ -83,8 +102,7 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle String path = msoBusinessLogic.getOperationalEnvironmentActivationPath(activateInfo); RequestDetailsWrapper<RequestDetails> requestDetailsWrapper = msoBusinessLogic.createOperationalEnvironmentActivationRequestDetails(activateInfo); - RestObject<RequestReferencesContainer> msoResponse = restMso.PostForObject(requestDetailsWrapper, "", - path, RequestReferencesContainer.class); + HttpResponse<RequestReferencesContainer> msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); debugEnd(msoResponse); return new MsoResponseWrapper2<>(msoResponse); @@ -105,8 +123,7 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle String path = msoBusinessLogic.getOperationalEnvironmentDeactivationPath(deactivateInfo); RequestDetailsWrapper<RequestDetails> requestDetailsWrapper = msoBusinessLogic.createOperationalEnvironmentDeactivationRequestDetails(deactivateInfo); - RestObject<RequestReferencesContainer> msoResponse = restMso.PostForObject(requestDetailsWrapper, "", - path, RequestReferencesContainer.class); + HttpResponse<RequestReferencesContainer> msoResponse = restMso.post(path, requestDetailsWrapper, RequestReferencesContainer.class); debugEnd(msoResponse); return new MsoResponseWrapper2<>(msoResponse); @@ -120,7 +137,7 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle verifyIsNotEmpty(requestId, "requestId"); String path = msoBusinessLogic.getCloudResourcesRequestsStatusPath(requestId); - final RestObject<HashMap> msoResponse = restMso.GetForObject("", path, HashMap.class); + HttpResponse<HashMap> msoResponse = restMso.get(path, HashMap.class); LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), msoResponse); return new MsoResponseWrapper2<>(msoResponse); @@ -322,7 +339,7 @@ public class OperationalEnvironmentController extends VidRestrictedBaseControlle } } - private void debugEnd(RestObject<RequestReferencesContainer> msoResponse) { + private void debugEnd(HttpResponse<RequestReferencesContainer> msoResponse) { LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodCallerName(), msoResponse); } 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 cf32e92e0..0f4b536a1 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 @@ -22,14 +22,30 @@ package org.onap.vid.controllers; import com.fasterxml.jackson.databind.ObjectMapper; -import org.onap.vid.aai.*; +import org.onap.vid.aai.AaiClient; +import org.onap.vid.aai.AaiClientInterface; +import org.onap.vid.aai.AaiResponseTranslator; +import org.onap.vid.aai.PombaClientImpl; +import org.onap.vid.aai.PombaClientInterface; +import org.onap.vid.aai.PombaRestInterface; import org.onap.vid.aai.model.PortDetailsTranslator; -import org.onap.vid.aai.util.*; +import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.aai.util.SSLContextProvider; +import org.onap.vid.aai.util.ServletRequestHelper; +import org.onap.vid.aai.util.SystemPropertyHelper; import org.onap.vid.asdc.AsdcClient; import org.onap.vid.asdc.parser.ToscaParserImpl2; -import org.onap.vid.asdc.rest.RestfulAsdcClient; -import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.asdc.rest.SdcRestClient; +import org.onap.vid.client.SyncRestClient; +import org.onap.vid.client.SyncRestClientInterface; import org.onap.vid.properties.AsdcClientConfiguration; +import org.onap.vid.services.AaiService; +import org.onap.vid.services.AaiServiceImpl; +import org.onap.vid.services.PombaService; +import org.onap.vid.services.PombaServiceImpl; +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.*; @@ -38,15 +54,8 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.togglz.core.manager.FeatureManager; -import javax.net.ssl.SSLContext; import javax.servlet.ServletContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; import java.io.File; -import java.net.URI; -import java.net.URISyntaxException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; @Configuration public class WebConfig { @@ -119,35 +128,18 @@ public class WebConfig { } @Bean - public AsdcClient asdcClient(AsdcClientConfiguration asdcClientConfig) { - - final String protocol = asdcClientConfig.getAsdcClientProtocol(); - final String host = asdcClientConfig.getAsdcClientHost(); - final int port = asdcClientConfig.getAsdcClientPort(); - final String auth = asdcClientConfig.getAsdcClientAuth(); - Client cl = null; - if (protocol.equalsIgnoreCase("https")) { - try { - SSLContext ctx = SSLContext.getInstance("TLSv1.2"); - ctx.init(null, null, null); - cl = ClientBuilder.newBuilder().sslContext(ctx).build(); - } catch (NoSuchAlgorithmException n) { - throw new GenericUncheckedException("SDC Client could not be instantiated due to unsupported protocol TLSv1.2", n); - } catch (KeyManagementException k) { - throw new GenericUncheckedException("SDC Client could not be instantiated due to a key management exception", k); - } - } else { - cl = ClientBuilder.newBuilder().build(); - } - - try { - final URI uri = new URI(protocol + "://" + host + ":" + port + "/"); - return new RestfulAsdcClient.Builder(cl, uri) - .auth(auth) - .build(); - } catch (URISyntaxException e) { - throw new GenericUncheckedException("SDC Client could not be instantiated due to a syntax error in the URI", e); - } + public AsdcClient sdcClient(AsdcClientConfiguration asdcClientConfiguration, SyncRestClientInterface syncRestClient) { + String auth = asdcClientConfiguration.getAsdcClientAuth(); + String host = asdcClientConfiguration.getAsdcClientHost(); + String protocol = asdcClientConfiguration.getAsdcClientProtocol(); + int port = asdcClientConfiguration.getAsdcClientPort(); + + return new SdcRestClient(protocol + "://" + host + ":" + port + "/", auth, syncRestClient); + } + + @Bean + public SyncRestClientInterface syncRestClient() { + return new SyncRestClient(); } @Bean diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java index 64c782c00..cee5af697 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/InProgressStatusCommand.java @@ -1,12 +1,32 @@ +/*- + * ============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.job.command; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; +import io.joshworks.restclient.http.HttpResponse; import org.onap.vid.job.Job.JobStatus; import org.onap.vid.job.JobCommand; import org.onap.vid.job.NextCommand; -import org.onap.vid.mso.RestMsoImplementation; -import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.rest.AsyncRequestStatus; import org.onap.vid.services.AsyncInstantiationBusinessLogic; import org.onap.vid.services.AuditService; @@ -32,7 +52,7 @@ public class InProgressStatusCommand implements JobCommand { private AsyncInstantiationBusinessLogic asyncInstantiationBL; @Inject - private RestMsoImplementation restMso; + private MsoInterface restMso; @Inject private AuditService auditService; @@ -53,20 +73,22 @@ public class InProgressStatusCommand implements JobCommand { try { String path = asyncInstantiationBL.getOrchestrationRequestsPath()+"/"+requestId; - RestObject<AsyncRequestStatus> msoResponse = restMso.GetForObject("", path, AsyncRequestStatus.class); + HttpResponse<AsyncRequestStatus> msoResponse = restMso.get(path, AsyncRequestStatus.class); + + JobStatus jobStatus; - if (msoResponse.getStatusCode() >= 400 || msoResponse.get() == null) { - auditService.setFailedAuditStatusFromMso(jobUuid, requestId, msoResponse.getStatusCode(), msoResponse.getRaw()); + if (msoResponse.getStatus() >= 400 || msoResponse.getBody() == null) { + auditService.setFailedAuditStatusFromMso(jobUuid, requestId, msoResponse.getStatus(), msoResponse.getBody().toString()); LOGGER.error(EELFLoggerDelegate.errorLogger, "Failed to get orchestration status for {}. Status code: {}, Body: {}", - requestId, msoResponse.getStatusCode(), msoResponse.getRaw()); + requestId, msoResponse.getStatus(), msoResponse.getRawBody().toString()); return new NextCommand(JobStatus.IN_PROGRESS, this); } else { - jobStatus = asyncInstantiationBL.calcStatus(msoResponse.get()); + jobStatus = asyncInstantiationBL.calcStatus(msoResponse.getBody()); } - asyncInstantiationBL.auditMsoStatus(jobUuid,msoResponse.get().request); + asyncInstantiationBL.auditMsoStatus(jobUuid,msoResponse.getBody().request); if (jobStatus == JobStatus.FAILED) { diff --git a/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java index 6afacf23e..9d22b8bfa 100644 --- a/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java +++ b/vid-app-common/src/main/java/org/onap/vid/job/command/ServiceInstantiationCommand.java @@ -1,7 +1,28 @@ +/*- + * ============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.job.command; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; +import io.joshworks.restclient.http.HttpResponse; import org.onap.vid.aai.exceptions.InvalidAAIResponseException; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.exceptions.MaxRetriesException; @@ -10,8 +31,7 @@ import org.onap.vid.job.JobCommand; import org.onap.vid.job.NextCommand; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.model.serviceInstantiation.ServiceInstantiation; -import org.onap.vid.mso.RestMsoImplementation; -import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.model.ServiceInstantiationRequestDetails; import org.onap.vid.services.AsyncInstantiationBusinessLogic; import org.onap.vid.services.AuditService; @@ -40,7 +60,7 @@ public class ServiceInstantiationCommand implements JobCommand { private AuditService auditService; @Inject - private RestMsoImplementation restMso; + private MsoInterface restMso; private UUID uuid; private ServiceInstantiation serviceInstantiationRequest; @@ -78,13 +98,14 @@ public class ServiceInstantiationCommand implements JobCommand { String path = asyncInstantiationBL.getServiceInstantiationPath(serviceInstantiationRequest); - RestObject<RequestReferencesContainer> msoResponse = restMso.PostForObject(requestDetailsWrapper, "", - path, RequestReferencesContainer.class); + HttpResponse<RequestReferencesContainer> msoResponse = restMso.post(path, + requestDetailsWrapper, RequestReferencesContainer.class); - if (msoResponse.getStatusCode() >= 200 && msoResponse.getStatusCode() < 400) { + + if (msoResponse.getStatus() >= 200 && msoResponse.getStatus() < 400) { final Job.JobStatus jobStatus = Job.JobStatus.IN_PROGRESS; - final String requestId = msoResponse.get().getRequestReferences().getRequestId(); - final String instanceId = msoResponse.get().getRequestReferences().getInstanceId(); + final String requestId = msoResponse.getBody().getRequestReferences().getRequestId(); + final String instanceId = msoResponse.getBody().getRequestReferences().getInstanceId(); asyncInstantiationBL.auditVidStatus(uuid, jobStatus); setInitialRequestAuditStatusFromMso(requestId); asyncInstantiationBL.updateServiceInfo(uuid, x-> { @@ -94,7 +115,8 @@ public class ServiceInstantiationCommand implements JobCommand { return new NextCommand(jobStatus, new InProgressStatusCommand(uuid, requestId)); } else { - auditService.setFailedAuditStatusFromMso(uuid,null, msoResponse.getStatusCode(),msoResponse.getRaw()); + auditService.setFailedAuditStatusFromMso(uuid,null, msoResponse.getStatus(), + msoResponse.getBody().toString()); return handleCommandFailed(); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java index a2e32bab5..00db464ab 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoBusinessLogicImpl.java @@ -1,3 +1,23 @@ +/*- + * ============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.mso; import com.fasterxml.jackson.annotation.JsonCreator; @@ -266,13 +286,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ); String path = p + "/" + requestId; - RestObject<String> restObjStr = new RestObject<>(); - String str = new String(); - restObjStr.set(str); - - msoClientInterface.getOrchestrationRequest(str, "", path, restObjStr); - - return MsoUtil.wrapResponse(restObjStr); + return msoClientInterface.getOrchestrationRequest(path); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); @@ -289,13 +303,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { String p = SystemProperties.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQS); String path = p + filterString; - RestObject<String> restObjStr = new RestObject<>(); - String str = new String(); - restObjStr.set(str); - - msoClientInterface.getOrchestrationRequest(str, "", path, restObjStr); - - return MsoUtil.wrapResponse(restObjStr); + return msoClientInterface.getOrchestrationRequest(path); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); 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 a5fb76027..3cba12f67 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 @@ -1,5 +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.mso; +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; @@ -62,7 +86,7 @@ public interface MsoInterface { MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint); - void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject); + MsoResponseWrapper getOrchestrationRequest(String endpoint); MsoResponseWrapper getOrchestrationRequestsForDashboard(String t , String sourceId , String endpoint , RestObject restObject); @@ -87,5 +111,28 @@ public interface MsoInterface { MsoResponseWrapper removeRelationshipFromServiceInstance(RequestDetails requestDetails, String endpoint); MsoResponseWrapper addRelationshipToServiceInstance(RequestDetails requestDetails, String addRelationshipsPath); + + <T> HttpResponse<T> get(String path, Class<T> responseClass); + + <T> HttpResponse<T> post(String path, RequestDetailsWrapper<?> requestDetailsWrapper, + Class<T> responseClass); + + static ObjectMapper objectMapper() { + return new ObjectMapper() { + CustomJacksonJaxBJsonProvider mapper = new CustomJacksonJaxBJsonProvider(); + + @SneakyThrows + @Override + public <T> T readValue(String s, Class<T> aClass) { + return mapper.getMapper().readValue(s, aClass); + } + + @SneakyThrows + @Override + public String writeValue(Object o) { + return mapper.getMapper().writeValueAsString(o); + } + }; + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java index 5a73a048a..2372e7fb7 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoResponseWrapper2.java @@ -1,9 +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.mso; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import io.joshworks.restclient.http.HttpResponse; @JsonPropertyOrder({ "status", @@ -29,6 +50,12 @@ public class MsoResponseWrapper2<T> implements MsoResponseWrapperInterface { this.raw = msoResponse.getRaw(); } + public MsoResponseWrapper2(HttpResponse<T> msoResponse) { + this.status = msoResponse.getStatus(); + this.entity = msoResponse.getBody(); + this.raw = msoResponse.getBody().toString(); + } + public MsoResponseWrapper2( @JsonProperty(value = "status", required = true) int status, @JsonProperty(value = "entity", required = true) T entity) { diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java b/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java index d2ccd0bd5..722a1c4cd 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/MsoUtil.java @@ -3,13 +3,14 @@ * 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. @@ -22,6 +23,8 @@ package org.onap.vid.mso; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import io.joshworks.restclient.http.HttpResponse; +import org.apache.commons.lang3.ObjectUtils; import org.glassfish.jersey.client.ClientResponse; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -88,8 +91,17 @@ public class MsoUtil { } MsoResponseWrapper w = MsoUtil.wrapResponse ( resp_str, status ); return (w); - } - + } + + public static <T> MsoResponseWrapper wrapResponse (HttpResponse<T> rs) { + MsoResponseWrapper w = new MsoResponseWrapper(); + w.setStatus (rs.getStatus()); + if(rs.getRawBody() != null) { + w.setEntity(ObjectUtils.toString(rs.getBody())); + } + return w; + } + /** * Convert pojo to string. * diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java index ae1b7a2ac..9cac3e4e2 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/rest/MsoRestClientNew.java @@ -1,46 +1,88 @@ +/*- + * ============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.mso.rest; +import com.google.common.collect.ImmutableMap; +import io.joshworks.restclient.http.HttpResponse; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import org.apache.commons.codec.binary.Base64; +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.changeManagement.MsoRequestDetails; import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.client.SyncRestClient; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.mso.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; +import org.onap.vid.utils.Logging; /** * Created by pickjonathan on 21/06/2017. */ -public class MsoRestClientNew extends RestMsoImplementation implements MsoInterface { +public class MsoRestClientNew implements MsoInterface { /** * The Constant dateFormat. */ + public static final String X_FROM_APP_ID = "X-FromAppId"; final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); private static final String START = " start"; - private final String ORIGINAL_REQUEST_ID = "originalRequestId"; + private final SyncRestClient client; + private final String baseUrl; + private final Map<String, String> commonHeaders; /** * The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoRestClientNew.class); + public MsoRestClientNew(SyncRestClient client, String baseUrl) { + this.client = client; + this.baseUrl = baseUrl; + this.commonHeaders = initCommonHeaders(); + } + @Override public MsoResponseWrapper createSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createSvcInstance "; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return createInstance(requestDetails, endpoint); + return createInstance(requestDetails, path); } @Override public MsoResponseWrapper createE2eSvcInstance(Object requestDetails, String endpoint) { String methodName = "createE2eSvcInstance "; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return createInstance(requestDetails, endpoint); + return createInstance(requestDetails, path); } @Override @@ -48,8 +90,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf String methodName = "createVnf"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return createInstance(requestDetails, endpoint); + return createInstance(requestDetails, path); } @Override @@ -57,160 +100,119 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf String methodName = "createNwInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return createInstance(requestDetails, endpoint); + return createInstance(requestDetails, path); } @Override public MsoResponseWrapper createVolumeGroupInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createVolumeGroupInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return createInstance(requestDetails, endpoint); + return createInstance(requestDetails, path); } @Override public MsoResponseWrapper createVfModuleInstance(RequestDetails requestDetails, String endpoint) { String methodName = "createVfModuleInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return createInstance(requestDetails, endpoint); + return createInstance(requestDetails, path); } @Override public MsoResponseWrapper createConfigurationInstance(org.onap.vid.mso.rest.RequestDetailsWrapper requestDetailsWrapper, String endpoint) { String methodName = "createConfigurationInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); - return createInstance(requestDetailsWrapper, endpoint); + String path = baseUrl + endpoint; + + return createInstance(requestDetailsWrapper, path); } @Override public MsoResponseWrapper deleteE2eSvcInstance(Object requestDetails, String endpoint) { String methodName = "deleteE2eSvcInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); - - return deleteInstance(requestDetails, endpoint); + String path = baseUrl + endpoint; + return deleteInstance(requestDetails, path); } @Override public MsoResponseWrapper deleteSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteSvcInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); - - return deleteInstance(requestDetails, endpoint); + String path = baseUrl + endpoint; + return deleteInstance(requestDetails, path); } @Override public MsoResponseWrapper unassignSvcInstance(RequestDetails requestDetails, String endpoint) { String methodName = "unassignSvcInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); - - RestObject<String> msoResponse = PostForObject(requestDetails, "", endpoint, String.class); - return MsoUtil.wrapResponse(msoResponse); + HttpResponse<String> response = client.post(endpoint, commonHeaders, requestDetails, String.class); + return MsoUtil.wrapResponse(response); } @Override public MsoResponseWrapper deleteVnf(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVnf"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return deleteInstance(requestDetails, endpoint); + return deleteInstance(requestDetails, path); } @Override public MsoResponseWrapper deleteVfModule(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVfModule"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return deleteInstance(requestDetails, endpoint); + return deleteInstance(requestDetails, path); } @Override public MsoResponseWrapper deleteVolumeGroupInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteVolumeGroupInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return deleteInstance(requestDetails, endpoint); + return deleteInstance(requestDetails, path); } @Override public MsoResponseWrapper deleteNwInstance(RequestDetails requestDetails, String endpoint) { String methodName = "deleteNwInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; - return deleteInstance(requestDetails, endpoint); + return deleteInstance(requestDetails, path); } @Override - public void getOrchestrationRequest(String t, String sourceId, String endpoint, RestObject restObject) { - Get(t, sourceId, endpoint, restObject); - } + public MsoResponseWrapper getOrchestrationRequest(String endpoint) { + String path = baseUrl + endpoint; - public void getManualTasks(String t, String sourceId, String endpoint, RestObject restObject) { - Get(t, sourceId, endpoint, restObject); + HttpResponse<String> response = client.get(path, commonHeaders, new HashMap<>(), String.class); + return MsoUtil.wrapResponse(response); } - public MsoResponseWrapper createInstance(Object request, String path) { - String methodName = "createInstance"; - logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); - - try { - RestObject<String> restObjStr = new RestObject<String>(); - - String str = new String(); - - restObjStr.set(str); - - Post(str, request, "", path, restObjStr); - MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr); + public MsoResponseWrapper getManualTasks(String endpoint) { + String path = baseUrl + endpoint; - return w; - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - throw e; - } + HttpResponse<String> response = client.get(path, commonHeaders, new HashMap<>(), String.class); + return MsoUtil.wrapResponse(response); } - /** - * Delete instance. - * - * @param request the request - * @param path the path - * @return the mso response wrapper - * @throws Exception the exception - */ - public MsoResponseWrapper deleteInstance(Object request, String path) { - String methodName = "deleteInstance"; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); - - try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); - - RestObject<String> restObjStr = new RestObject<String>(); - String str = new String(); - restObjStr.set(str); - Delete(str, request, "", path, restObjStr); - MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr); - - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); - return w; - - } catch (Exception e) { - logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); - throw e; - } - - } - - public MsoResponseWrapper getOrchestrationRequestsForDashboard(String t, String sourceId, String endpoint, RestObject restObject) { + public MsoResponseWrapper getOrchestrationRequestsForDashboard(String t, String sourceId, String path, RestObject restObject) { String methodName = "getOrchestrationRequestsForDashboard"; logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); try { - getOrchestrationRequest(t, sourceId, endpoint, restObject); - MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + MsoResponseWrapper w = getOrchestrationRequest(path); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); return w; @@ -227,11 +229,12 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); try { - getManualTasks(t, sourceId, endpoint, restObject); - MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + String path = baseUrl + endpoint; + + MsoResponseWrapper w =getManualTasks(path); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); - return MsoUtil.wrapResponse(restObject); + return w; } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); @@ -245,9 +248,10 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf String methodName = "completeManualTask"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Complete "); try { + String path = baseUrl + endpoint; - Post(t, requestDetails, sourceId, endpoint, restObject); - MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); + HttpResponse<String> response = client.post(path, commonHeaders, requestDetails, String.class); + MsoResponseWrapper w = MsoUtil.wrapResponse(response); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); return w; @@ -263,7 +267,8 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf public MsoResponseWrapper replaceVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) { String methodName = "replaceVnf"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); - return replaceInstance(requestDetails, endpoint); + String path = baseUrl + endpoint; + return replaceInstance(requestDetails, path); } @Override @@ -271,25 +276,23 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf String methodName = "deleteConfiguration"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + pmc_endpoint; - return deleteInstance(requestDetailsWrapper, pmc_endpoint); + return deleteInstance(requestDetailsWrapper, path); } @Override - public MsoResponseWrapper setConfigurationActiveStatus(RequestDetails request, String path) { + public MsoResponseWrapper setConfigurationActiveStatus(RequestDetails request, String endpoint) { String methodName = "setConfigurationActiveStatus"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling change configuration active status, path =[" + path + "]"); - - RestObject<String> restObjStr = new RestObject<String>(); - String str = new String(); - restObjStr.set(str); - Post(str, request, "", path, restObjStr); - MsoResponseWrapper msoResponseWrapperObject = MsoUtil.wrapResponse(restObjStr); + String path = baseUrl + endpoint; - return msoResponseWrapperObject; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + + methodName + " calling change configuration active status, path =[" + path + "]"); + HttpResponse<String> response = client.post(path, commonHeaders, request, String.class); + return MsoUtil.wrapResponse(response); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); @@ -298,20 +301,16 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf } @Override - public MsoResponseWrapper setPortOnConfigurationStatus(RequestDetails request, String path) { + public MsoResponseWrapper setPortOnConfigurationStatus(RequestDetails request, String endpoint) { String methodName = "setPortOnConfigurationStatus"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling change port configuration status, path =[" + path + "]"); - - RestObject<String> restObjStr = new RestObject<String>(); - String str = new String(); - restObjStr.set(str); - Post(str, request, "", path, restObjStr); - MsoResponseWrapper msoResponseWrapperObject = MsoUtil.wrapResponse(restObjStr); - - return msoResponseWrapperObject; + String path = baseUrl + endpoint; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + + methodName + " calling change port configuration status, path =[" + path + "]"); + HttpResponse<String> response = client.post(path, commonHeaders, request, String.class); + return MsoUtil.wrapResponse(response); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); @@ -321,8 +320,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf @Override public MsoResponseWrapperInterface changeManagementUpdate(RequestDetailsWrapper requestDetails, String endpoint) { - RestObject<RequestReferencesContainer> msoResponse = PostForObject(requestDetails, "", endpoint, RequestReferencesContainer.class); - return new MsoResponseWrapper2<>(msoResponse); + String path = baseUrl + endpoint; + HttpResponse<RequestReferencesContainer> response = client.post(path, commonHeaders, requestDetails, RequestReferencesContainer.class); + return MsoUtil.wrapResponse(response); } public MsoResponseWrapper replaceInstance(org.onap.vid.changeManagement.RequestDetails request, String path) { @@ -330,17 +330,10 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); try { - - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Replace VNF, path =[" + path + "]"); - RestObject<String> restObjStr = new RestObject<String>(); - String str = new String(); - restObjStr.set(str); - RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); - requestDetailsWrapper.requestDetails = new MsoRequestDetails(request); - - Post(str, requestDetailsWrapper, "", path, restObjStr); - MsoResponseWrapper msoResponseWrapperObject = MsoUtil.wrapResponse(restObjStr); + + HttpResponse<String> response = client.post(path, commonHeaders, request, String.class); + MsoResponseWrapper msoResponseWrapperObject = MsoUtil.wrapResponse(response); int status = msoResponseWrapperObject.getStatus(); if (status == 202) { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + @@ -365,9 +358,11 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf public MsoResponseWrapper updateVnf(org.onap.vid.changeManagement.RequestDetails requestDetails, String endpoint) { String methodName = "updateVnf"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + String path = baseUrl + endpoint; + RequestDetailsWrapper wrapper = new RequestDetailsWrapper(); wrapper.requestDetails = new MsoRequestDetails(requestDetails); - return updateInstance(requestDetails, endpoint); + return updateInstance(requestDetails, path); } public MsoResponseWrapper updateInstance(org.onap.vid.changeManagement.RequestDetails request, String path) { @@ -376,13 +371,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); - RestObject<String> restObjStr = new RestObject<String>(); - String str = new String(); - restObjStr.set(str); - RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); - requestDetailsWrapper.requestDetails = new MsoRequestDetails(request); - Put(str, requestDetailsWrapper, "", path, restObjStr); - MsoResponseWrapper w = MsoUtil.wrapResponse(restObjStr); + + HttpResponse<String> response = client.post(path, commonHeaders, request, String.class); + MsoResponseWrapper w = MsoUtil.wrapResponse(response); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); return w; @@ -399,10 +390,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf String methodName = "activateServiceInstance"; logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start "); try { - - Post(t, requestDetails, sourceId, endpoint, restObject); - MsoResponseWrapper w = MsoUtil.wrapResponse(restObject); - + String path = baseUrl + endpoint; + HttpResponse<String> response = client.post(path, commonHeaders, requestDetails, String.class); + MsoResponseWrapper w = MsoUtil.wrapResponse(response); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w =" + w.getResponse()); } catch (Exception e) { @@ -419,13 +409,9 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Remove relationship from service instance, path =[" + endpoint + "]"); - - RestObject<String> restObjStr = new RestObject<String>(); - String str = ""; - restObjStr.set(str); - Post(str, requestDetails, "", endpoint, restObjStr); - - return MsoUtil.wrapResponse(restObjStr); + String path = baseUrl + endpoint; + HttpResponse<String> response = client.post(path, commonHeaders, requestDetails, String.class); + return MsoUtil.wrapResponse(response); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); @@ -440,16 +426,89 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf try { logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Add relationship to service instance, path =[" + addRelationshipsPath + "]"); + String path = baseUrl + addRelationshipsPath; - RestObject<String> restObjStr = new RestObject<>(); - restObjStr.set(""); - Post("", requestDetails, "", addRelationshipsPath, restObjStr); - - return MsoUtil.wrapResponse(restObjStr); + HttpResponse<String> response = client.post(path, commonHeaders, requestDetails, String.class); + return MsoUtil.wrapResponse(response); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); throw e; } } + + @Override + public <T> HttpResponse<T> get(String path, Class<T> responseClass) { + return client.get(path, commonHeaders, new HashMap<>(), responseClass); + } + + @Override + public <T> HttpResponse<T> post(String path, RequestDetailsWrapper<?> requestDetailsWrapper, + Class<T> responseClass) { + return client.post(path, commonHeaders, requestDetailsWrapper, responseClass); + } + + + private MsoResponseWrapper createInstance(Object request, String endpoint) { + String methodName = "createInstance"; + logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START); + + try { + HttpResponse<String> response = client.post(endpoint, commonHeaders, request, String.class); + return MsoUtil.wrapResponse(response); + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + } + + /** + * Delete instance. + * + * @param request the request + * @param path the path + * @return the mso response wrapper + * @throws Exception the exception + */ + private MsoResponseWrapper deleteInstance(Object request, String path) { + String methodName = "deleteInstance"; + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START); + + try { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " calling Delete, path =[" + path + "]"); + + HttpResponse<String> response = client.delete(path, commonHeaders, String.class); + MsoResponseWrapper w = MsoUtil.wrapResponse(response); + + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " w=" + w.getResponse()); + return w; + + } catch (Exception e) { + logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString()); + throw e; + } + + } + + private Map<String, String> initCommonHeaders() { + String username = SystemProperties.getProperty(MsoProperties.MSO_USER_NAME); + String password = SystemProperties.getProperty(MsoProperties.MSO_PASSWORD); + String decrypted_password = Password.deobfuscate(password); + + String authString = username + ":" + decrypted_password; + + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + + Map<String, String> map = new HashMap<>(); + map.put(HttpHeaders.AUTHORIZATION, "Basic " + authStringEnc); + map.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + map.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + map.put(X_FROM_APP_ID, SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME)); + map.put(SystemProperties.ECOMP_REQUEST_ID, Logging.extractOrGenerateRequestId()); + return ImmutableMap.copyOf(map); + } + }
\ No newline at end of file diff --git a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java index d66ed4947..a4c5b00a8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/scheduler/SchedulerRestInterface.java @@ -1,23 +1,22 @@ package org.onap.vid.scheduler; import com.att.eelf.configuration.EELFLogger; -import org.apache.commons.codec.binary.Base64; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import io.joshworks.restclient.http.HttpResponse; import org.eclipse.jetty.util.security.Password; -import org.onap.vid.aai.util.HttpClientMode; -import org.onap.vid.aai.util.HttpsAuthClient; -import org.onap.vid.client.HttpBasicClient; -import org.onap.vid.exceptions.GenericUncheckedException; -import org.onap.vid.utils.Logging; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; +import org.onap.vid.client.SyncRestClient; +import org.onap.vid.client.SyncRestClientInterface; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.vid.utils.Logging; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; -import javax.ws.rs.client.Client; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; +import java.util.Base64; import java.util.Collections; +import java.util.Map; import java.util.function.Function; import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; @@ -25,126 +24,88 @@ import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; @Service public class SchedulerRestInterface implements SchedulerRestInterfaceIfc { - private Client client = null; - private Function<String, String> propertyGetter; - - @Autowired - HttpsAuthClient httpsAuthClient; - - private MultivaluedHashMap<String, Object> commonHeaders; - - /** The logger. */ - private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); final private static EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("scheduler"); + private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SchedulerRestInterface.class); + private SyncRestClientInterface syncRestClient; + private Function<String, String> propertyGetter; + private Map<String, String> commonHeaders; - public SchedulerRestInterface(){ + public SchedulerRestInterface() { this.propertyGetter = SystemProperties::getProperty; } - public SchedulerRestInterface(Function<String, String> propertyGetter){ + public SchedulerRestInterface(Function<String, String> propertyGetter) { this.propertyGetter = propertyGetter; } public void initRestClient() { logger.info("Starting to initialize rest client "); + String authStringEnc = calcEncodedAuthString(); - final String username; - final String password; - - /*Setting user name based on properties*/ - String retrievedUsername = propertyGetter.apply(SchedulerProperties.SCHEDULER_USER_NAME_VAL); - if(retrievedUsername.isEmpty()) { - username = ""; - } else { - username = retrievedUsername; - } - - /*Setting password based on properties*/ - String retrievedPassword = propertyGetter.apply(SchedulerProperties.SCHEDULER_PASSWORD_VAL); - if(retrievedPassword.isEmpty()) { - password = ""; - } else { - if (retrievedPassword.contains("OBF:")) { - password = Password.deobfuscate(retrievedPassword); - } else { - password = retrievedPassword; - } - } - - String authString = username + ":" + password; - - byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); - String authStringEnc = new String(authEncBytes); + commonHeaders = Maps.newHashMap(); + commonHeaders.put("Authorization", "Basic " + authStringEnc); - commonHeaders = new MultivaluedHashMap<> (); - commonHeaders.put("Authorization", Collections.singletonList("Basic " + authStringEnc)); - - try { - if ( !username.isEmpty() ) { - client = httpsAuthClient.getClient(HttpClientMode.WITHOUT_KEYSTORE); - } - else { - - client = HttpBasicClient.getClient(); - } - } catch (Exception e) { - logger.error(" <== Unable to initialize rest client ", e); - } + syncRestClient = new SyncRestClient(); logger.info("\t<== Client Initialized \n"); } - public <T> void Get (T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject ) { - - String methodName = "Get"; - String url = String.format("%s%s",propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path); + public <T> void Get(T t, String sourceId, String path, org.onap.vid.scheduler.RestObject<T> restObject) { initRestClient(); + String methodName = "Get"; + String url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path); Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); - final Response cres = client.target(url) - .request() - .accept("application/json") - .headers(commonHeaders) - .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) - .get(); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); - int status = cres.getStatus(); - restObject.setStatusCode (status); + Map<String, String> requestHeaders = ImmutableMap.<String, String>builder() + .putAll(commonHeaders) + .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()).build(); + final HttpResponse<T> response = ((HttpResponse<T>) syncRestClient.get(url, requestHeaders, + Collections.emptyMap(), t.getClass())); + Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, response); + int status = response.getStatus(); + restObject.setStatusCode(status); if (status == 200) { - t = (T) cres.readEntity(t.getClass()); + t = response.getBody(); restObject.set(t); } else { - throw new GenericUncheckedException(String.format("%s with status=%d, url=%s", methodName, status,url)); + throw new GenericUncheckedException(String.format("%s with status=%d, url=%s", methodName, status, url)); } - } public <T> void Delete(T t, String sourceID, String path, org.onap.vid.scheduler.RestObject<T> restObject) { - initRestClient(); - - String url = String.format( "%s%s",propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path); + String url = String.format("%s%s", propertyGetter.apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL), path); Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url); - Response cres = client.target(url) - .request() - .accept("application/json") - .headers(commonHeaders) - .header(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()) - .delete(); - Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres); - - int status = cres.getStatus(); + Map<String, String> requestHeaders = ImmutableMap.<String, String>builder() + .putAll(commonHeaders) + .put(REQUEST_ID_HEADER_KEY, Logging.extractOrGenerateRequestId()).build(); + final HttpResponse<T> response = (HttpResponse<T>) syncRestClient.delete(url, requestHeaders, t.getClass()); + + Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, response); + + int status = response.getStatus(); restObject.setStatusCode(status); - t = (T) cres.readEntity(t.getClass()); + t = response.getBody(); restObject.set(t); - } - public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException - { + public <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException { return clazz.newInstance(); } + private String calcEncodedAuthString() { + String retrievedUsername = propertyGetter.apply(SchedulerProperties.SCHEDULER_USER_NAME_VAL); + final String username = retrievedUsername.isEmpty() ? "" : retrievedUsername; + + String retrievedPassword = propertyGetter.apply(SchedulerProperties.SCHEDULER_PASSWORD_VAL); + final String password = retrievedPassword.isEmpty() ? "" : getDeobfuscatedPassword(retrievedPassword); + + return Base64.getEncoder().encodeToString((username + ":" + password).getBytes()); + } + + private static String getDeobfuscatedPassword(String password) { + return password.contains("OBF:") ? Password.deobfuscate(password) : password; + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java index e0ee6fbf0..3ac905884 100644 --- a/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java +++ b/vid-app-common/src/main/java/org/onap/vid/utils/Logging.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.google.common.collect.ImmutableList; +import io.joshworks.restclient.http.HttpResponse; import org.apache.commons.lang3.StringUtils; import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; @@ -101,6 +102,15 @@ public class Logging { } } + public static <T> void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final HttpResponse<T> response) { + try { + logger.debug("Received {} {} Status: {} . Body: {}", method.name(), url, response.getStatus(), response.getBody()); + } + catch (ProcessingException | IllegalStateException e) { + logger.debug("Received {} {} Status: {} . Failed to read response", method.name(), url, response.getStatus()); + } + } + public static void logResponse(final EELFLogger logger, final HttpMethod method, final String url, final Response response) { logResponse(logger, method, url, response, String.class); } diff --git a/vid-app-common/src/main/resources/adiod.zip b/vid-app-common/src/main/resources/adiod.zip Binary files differindex 415fa4833..6c928a354 100644 --- a/vid-app-common/src/main/resources/adiod.zip +++ b/vid-app-common/src/main/resources/adiod.zip diff --git a/vid-app-common/src/main/resources/csar317927061915233480.zip b/vid-app-common/src/main/resources/csar317927061915233480.zip Binary files differindex 36ac9f9bc..ce58b17dc 100644 --- a/vid-app-common/src/main/resources/csar317927061915233480.zip +++ b/vid-app-common/src/main/resources/csar317927061915233480.zip diff --git a/vid-app-common/src/main/resources/csar3933948645405128424.zip b/vid-app-common/src/main/resources/csar3933948645405128424.zip Binary files differindex b92d5339f..ee9b4fb0c 100644 --- a/vid-app-common/src/main/resources/csar3933948645405128424.zip +++ b/vid-app-common/src/main/resources/csar3933948645405128424.zip diff --git a/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip b/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip Binary files differindex 6d5002c6c..1591a48ff 100644 --- a/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip +++ b/vid-app-common/src/main/resources/service-AmpPhSvc-csar.zip diff --git a/vid-app-common/src/main/resources/service-VdbeSrv-csar.zip b/vid-app-common/src/main/resources/service-VdbeSrv-csar.zip Binary files differindex 3defd1e90..0b8db2789 100644 --- a/vid-app-common/src/main/resources/service-VdbeSrv-csar.zip +++ b/vid-app-common/src/main/resources/service-VdbeSrv-csar.zip diff --git a/vid-app-common/src/main/resources/service-vf-csar.zip b/vid-app-common/src/main/resources/service-vf-csar.zip Binary files differindex f66d08464..c3a9fbbe9 100644 --- a/vid-app-common/src/main/resources/service-vf-csar.zip +++ b/vid-app-common/src/main/resources/service-vf-csar.zip diff --git a/vid-app-common/src/main/resources/service-vf-with-annotations.zip b/vid-app-common/src/main/resources/service-vf-with-annotations.zip Binary files differindex a742d60cb..a6fcce7ae 100644 --- a/vid-app-common/src/main/resources/service-vf-with-annotations.zip +++ b/vid-app-common/src/main/resources/service-vf-with-annotations.zip diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js b/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js index c85e86529..89660fb18 100755 --- a/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js +++ b/vid-app-common/src/main/webapp/app/vid/scripts/controller/ServiceModelController.js @@ -187,6 +187,7 @@ "category":serviceModel.service.category
});
DataService.setALaCarte (true);
+ DataService.setPnf(!angular.equals(serviceModel.pnfs, {}));
$scope.createType = COMPONENT.A_LA_CARTE;
var broadcastType = COMPONENT.CREATE_COMPONENT;
if (AsdcService.isMacro(serviceModel)) {
diff --git a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html index 4f7cc3c02..654226636 100644 --- a/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html +++ b/vid-app-common/src/main/webapp/app/vid/scripts/view-models/change-management.html @@ -1,4 +1,4 @@ -<script src="../controller/change-management.controller.js"></script> +<script src="app/vid/scripts/controller/change-management.controller.js"></script> <link rel="stylesheet" type="text/css" href="app/vid/styles/change-management.css" /> <link rel="stylesheet" type="text/css" href="app/vid/styles/change-management-icons.css" /> <div class="changes-management"> diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java deleted file mode 100644 index 75b84b2db..000000000 --- a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/RestfulAsdcClientTest.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.onap.vid.asdc.rest; - -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.onap.vid.testUtils.TestUtils; -import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import javax.ws.rs.NotFoundException; -import javax.ws.rs.ProcessingException; -import javax.ws.rs.client.Client; -import java.net.URI; -import java.util.UUID; -import java.util.function.Consumer; - -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.when; -import static org.testng.AssertJUnit.fail; - -public class RestfulAsdcClientTest { - - @DataProvider - public static Object[][] javaxExceptions() { - - return new Object[][] { - {NotFoundException.class, (Consumer<Client>) javaxClientMock -> - when(javaxClientMock.target(any(URI.class))).thenThrow( - new NotFoundException("HTTP 404 Not Found"))}, - {ProcessingException.class, (Consumer<Client>) javaxClientMock -> - when(javaxClientMock.target(any(URI.class))).thenThrow( - new ProcessingException("java.net.ConnectException: Connection refused: connect"))}, - }; - } - - - @Test(dataProvider = "javaxExceptions") - public void whenJavaxClientThrowException_thenExceptionRethrown(Class<? extends Throwable> expectedType, Consumer<Client> setupMocks) throws Exception { - /* - Call chain is like: - this test -> RestfulAsdcClient -> javax's Client - - In this test, *RestfulAsdcClient* is under test (actual implementation is used), while javax's Client is - mocked to return pseudo-responses or - better - throw exceptions. - */ - - // prepare mocks - TestUtils.JavaxRsClientMocks mocks = new TestUtils.JavaxRsClientMocks(); - Client javaxClientMock = mocks.getFakeClient(); - - // prepare real RestfulAsdcClient (Under test) - RestfulAsdcClient restfulAsdcClient = new RestfulAsdcClient.Builder(javaxClientMock, new URI("")) - .auth("") - .build(); - - /// TEST: - setupMocks.accept(javaxClientMock); - - try { - restfulAsdcClient.getServiceToscaModel(UUID.randomUUID()); - } catch (Exception e) { - assertThat("root cause incorrect for " + ExceptionUtils.getStackTrace(e), ExceptionUtils.getRootCause(e), instanceOf(expectedType)); - return; //OK - } - - fail("exception shall rethrown by getServiceToscaModel once javax client throw exception "); - } - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java new file mode 100644 index 000000000..2ef337424 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientITTest.java @@ -0,0 +1,154 @@ +/*- + * ============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.asdc.rest; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.xebialabs.restito.semantics.Call; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLContextBuilder; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.client.SyncRestClient; +import org.onap.vid.testUtils.StubServerUtil; + +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.GeneralSecurityException; +import java.util.Collections; +import java.util.Optional; +import java.util.UUID; + +import static com.xebialabs.restito.semantics.Action.ok; +import static com.xebialabs.restito.semantics.Action.stringContent; +import static org.apache.http.client.config.RequestConfig.custom; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.matchesPattern; +import static org.hamcrest.collection.IsIterableContainingInOrder.contains; +import static org.junit.Assert.assertTrue; +import static org.onap.vid.client.SyncRestClientInterface.HEADERS.X_ECOMP_INSTANCE_ID; +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; + + +public class SdcRestClientITTest { + private static final String UUID_REGEX = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; + private static final String[] SUPPORTED_SSL_VERSIONS = {"TLSv1", "TLSv1.2"}; + private static StubServerUtil stubServer; + private static SdcRestClient sdcRestClient; + + @BeforeClass + public static void setUpClass() throws GeneralSecurityException { + stubServer = new StubServerUtil(); + stubServer.runSecuredServer(); + SyncRestClient syncRestClient = new SyncRestClient(createNaiveHttpClient()); + String serverUrl = stubServer.constructTargetUrl("https", ""); + sdcRestClient = new SdcRestClient(serverUrl, "", syncRestClient); + } + + @AfterClass + public static void tearDown() { + stubServer.stopServer(); + } + + @Test + public void shouldDownloadToscaArtifactUsingSecuredEndpoint() throws AsdcCatalogException, IOException { + UUID uuid = UUID.randomUUID(); + String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/toscaModel", uuid); + + stubServer.prepareGetCall( + expectedEndpoint, stringContent("sampleFileContent"), "sampleFileContent", ok(), "application/octet-stream"); + + + Path serviceToscaModel = sdcRestClient.getServiceToscaModel(uuid); + serviceToscaModel.toFile().deleteOnExit(); + + + assertThat(Files.readAllLines(serviceToscaModel), contains("sampleFileContent")); + assertThatRequestHasRequiredHeaders(expectedEndpoint); + } + + @Test + public void shouldGetServiceDetailsUsingSecuredEndpoint() throws AsdcCatalogException, JsonProcessingException { + UUID uuid = UUID.randomUUID(); + String expectedEndpoint = String.format("/sdc/v1/catalog/services/%s/metadata", uuid); + Service expectedService = getExpectedService(uuid.toString()); + + + stubServer.prepareGetCall(expectedEndpoint, expectedService, ok()); + + + Service actualService = sdcRestClient.getService(uuid); + + + assertThat(actualService, is(expectedService)); + assertThatRequestHasRequiredHeaders(expectedEndpoint); + } + + private void assertThatRequestHasRequiredHeaders(String expectedEndpoint) { + Optional<Call> first = stubServer + .getServerCalls() + .stream() + .filter(x -> x.getUri().contains(expectedEndpoint)) + .findFirst(); + + assertTrue(first.isPresent()); + + assertThat(first.get().getHeaders().keySet(), hasItems(X_ECOMP_INSTANCE_ID.toLowerCase(), REQUEST_ID_HEADER_KEY.toLowerCase())); + assertThat(first.get().getHeaders().get(REQUEST_ID_HEADER_KEY.toLowerCase()).get(0), matchesPattern(UUID_REGEX)); + } + + private Service getExpectedService(String stringId) { + return new Service(stringId, stringId, + "sampleCategory", "sampleVersion", + "sampleName", "sampleDistStatus", + "sampleToscaUrl", Service.LifecycleState.CERTIFIED, Collections.emptyList(), Collections.emptyList()); + } + + + private static CloseableHttpClient createNaiveHttpClient() throws GeneralSecurityException { + final SSLContext context = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) + .build(); + + final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(context, SUPPORTED_SSL_VERSIONS, + null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() + .register("https", socketFactory) + .build(); + + return HttpClientBuilder.create() + .setDefaultRequestConfig(custom().setConnectionRequestTimeout(10000).build()) + .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) + .setSSLSocketFactory(socketFactory).build(); + } +} diff --git a/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientTest.java new file mode 100644 index 000000000..c1d6ab78a --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/asdc/rest/SdcRestClientTest.java @@ -0,0 +1,137 @@ +/*- + * ============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.asdc.rest; + +import io.joshworks.restclient.http.HttpResponse; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; +import org.onap.vid.asdc.AsdcCatalogException; +import org.onap.vid.asdc.beans.Service; +import org.onap.vid.client.SyncRestClient; + +import java.io.InputStream; +import java.nio.file.Path; +import java.util.UUID; + +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMapOf; +import static org.mockito.Matchers.matches; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class SdcRestClientTest { + + private static final String SAMPLE_SERVICE_NAME = "sampleService"; + private static final String SAMPLE_BASE_URL = "baseUrl"; + private static final String SAMPLE_AUTH = "sampleAuth"; + private static final String METADATA_URL_REGEX = ".*sdc/v1/catalog/services/%s/metadata"; + private static final String MODEL_URL_REGEX = ".*sdc/v1/catalog/services/%s/toscaModel"; + + + @Mock + private SyncRestClient mockedSyncRestClient; + + @Mock + private HttpResponse<Object> httpResponse; + + @Mock + private HttpResponse<InputStream> httpStreamResponse; + + @Mock + private InputStream inputStream; + + private UUID randomId; + + private Service sampleService; + + private SdcRestClient restClient; + + + @Before + public void setUp() { + randomId = UUID.randomUUID(); + sampleService = createTestService(); + restClient = new SdcRestClient(SAMPLE_BASE_URL, SAMPLE_AUTH, mockedSyncRestClient); + } + + + @Test + public void shouldReturnServiceForGivenUUID() throws AsdcCatalogException { + String url = String.format(METADATA_URL_REGEX, randomId); + when(mockedSyncRestClient.get(matches(url), anyMapOf(String.class, String.class), anyMapOf(String.class, String.class), any())).thenReturn(httpResponse); + when(httpResponse.getBody()).thenReturn(sampleService); + + Service service = restClient.getService(randomId); + + + assertThat(service, is(sampleService)); + } + + @Test(expected = AsdcCatalogException.class) + public void shouldRaiseAsdcExceptionWhenClientFails() throws AsdcCatalogException { + String url = String.format(METADATA_URL_REGEX, randomId); + when(mockedSyncRestClient.get(matches(url), anyMapOf(String.class, String.class), anyMapOf(String.class, String.class), any())).thenThrow(new RuntimeException()); + + restClient.getService(randomId); + } + + + @Test + public void shouldProperlyDownloadAndCopyToscaArtifact() throws AsdcCatalogException { + String url = String.format(MODEL_URL_REGEX, randomId); + when(mockedSyncRestClient.getStream(matches(url), any(), any())).thenReturn(httpStreamResponse); + when(httpStreamResponse.getBody()).thenReturn(inputStream); + + + Path serviceToscaModel = restClient.getServiceToscaModel(randomId); + + + assertThat(serviceToscaModel, notNullValue()); + assertThat(serviceToscaModel.toFile().isFile(), is(true)); + + serviceToscaModel.toFile().deleteOnExit(); + } + + @Test(expected = AsdcCatalogException.class) + public void shouldRaiseAsdcExceptionWhenDownloadFails() throws AsdcCatalogException { + String url = String.format(MODEL_URL_REGEX, randomId); + when(mockedSyncRestClient.getStream(matches(url), anyMapOf(String.class, String.class), anyMapOf(String.class, String.class))).thenThrow(new RuntimeException()); + + + restClient.getServiceToscaModel(randomId); + } + + + private Service createTestService() { + Service service = new Service(); + service.setInvariantUUID(randomId.toString()); + service.setUuid(randomId.toString()); + service.setName(SAMPLE_SERVICE_NAME); + return service; + } + +}
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java index 738e8df03..af7f74b3d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicTest.java @@ -1,16 +1,16 @@ package org.onap.vid.mso; import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; +import org.mockito.runners.MockitoJUnitRunner; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.RequestDetailsWrapper; -import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.net.URL; @@ -18,7 +18,7 @@ import java.net.URL; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; -@Test +@RunWith(MockitoJUnitRunner.class) public class MsoBusinessLogicTest { @InjectMocks @@ -27,11 +27,6 @@ public class MsoBusinessLogicTest { @Mock private MsoInterface msoClient; - @BeforeMethod - public void initMocks(){ - MockitoAnnotations.initMocks(this); - } - @Test public void testCreateInstance() throws Exception { String instanceId = "3f93c7cb-2fd0-4557-9514-e189b7b04f9d"; diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java index 59c2c704f..402386a50 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientNewTest.java @@ -1,88 +1,158 @@ +/*- + * ============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.mso.rest; +import com.xebialabs.restito.server.StubServer; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Properties; +import java.util.UUID; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.Test; +import org.onap.vid.client.SyncRestClient; +import org.onap.vid.controllers.MsoController; +import org.onap.vid.mso.MsoInterface; +import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapperInterface; import org.onap.vid.mso.RestObject; public class MsoRestClientNewTest { - private MsoRestClientNew createTestSubject() { - return new MsoRestClientNew(); + private static StubServer server; + private static StubServer securedServer; + private static Properties props = new Properties(); + private static String msoCreateServiceInstanceJson; + private final static String CREATE_INSTANCE_RESPONSE_STR = + "{\"requestReferences\":{\"instanceId\":\"baa13544-0e95-4644-9565-9a198a29a294\"," + + "\"requestId\":\"a42a1a35-3d63-4629-bbe0-4989fa7414cb\"}}"; + private final static String SERVICE_INSTANCE_ID = "12345"; + private static final String SAMPLE_VNF_INSTANCE_ID = "111"; + private static final String SAMPLE_VNF_MODULE_ID = "987"; + private static final String SAMPLE_NETWORK_INSTANCE_ID = "666"; + private static final String SAMPLE_CONFIGURATION_ID = "997"; + private static final String SAMPLE_REQUEST_ID = "7777"; + + + @BeforeClass + public static void start() throws IOException { + server = new StubServer().run(); + securedServer = new StubServer().secured().run(); + + Path resourceDirectory = + Paths.get("src", "test", "resources", "WEB-INF", "conf", "system.properties"); + try(InputStream is = Files.newInputStream(resourceDirectory)) { + props.load(is); + } + + Path msoServiceInstantiationJsonFilePath = + Paths.get("src", "test", "resources", "payload_jsons", "mso_service_instantiation.json"); + msoCreateServiceInstanceJson = + String.join("\n", Files.readAllLines(msoServiceInstantiationJsonFilePath)); + } + + @AfterClass + public static void stop() { + server.stop(); + securedServer.stop(); + } + + + private String baseUrl() { + return String.format("http://localhost:%d", server.getPort()); } @Test public void testCreateSvcInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createSvcInstance(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_CONFIGURATIONS); + endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createSvcInstance); } } @Test public void testCreateVnf() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createVnf(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE); + endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createVnf); } } @Test public void testCreateNwInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createNwInstance(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); + String nw_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + nw_endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createNwInstance); } } @Test public void testCreateVolumeGroupInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createVolumeGroupInstance(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); + String vnf_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + vnf_endpoint = vnf_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + vnf_endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createVolumeGroupInstance); } } @Test public void testCreateVfModuleInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createVfModuleInstance(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + String partial_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + String vf_module_endpoint = + partial_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); + + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + vf_module_endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::createVfModuleInstance); } } @@ -103,138 +173,105 @@ public class MsoRestClientNewTest { @Test public void testDeleteSvcInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); + endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteSvcInstance(requestDetails, endpoint); - } catch (Exception e) { + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteSvcInstance); } } @Test public void testDeleteVnf() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteVnf(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VNF_INSTANCE); + endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteVnf); } } @Test public void testDeleteVfModule() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteVfModule(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VF_MODULE_INSTANCE); + String part_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + String vf_modules_endpoint = part_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); + String delete_vf_endpoint = vf_modules_endpoint + '/' + SAMPLE_VNF_MODULE_ID; + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + delete_vf_endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteVfModule); } } @Test public void testDeleteVolumeGroupInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteVolumeGroupInstance(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_VOLUME_GROUP_INSTANCE); + String svc_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + String vnf_endpoint = svc_endpoint.replaceFirst(MsoController.VNF_INSTANCE_ID, SAMPLE_VNF_INSTANCE_ID); + String delete_volume_group_endpoint = vnf_endpoint + "/" + SAMPLE_VNF_MODULE_ID; + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + delete_volume_group_endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteVolumeGroupInstance); } } @Test public void testDeleteNwInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteNwInstance(requestDetails, endpoint); - } catch (Exception e) { + String endpoint = props.getProperty(MsoProperties.MSO_REST_API_NETWORK_INSTANCE); + String svc_endpoint = endpoint.replaceFirst(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + String delete_nw_endpoint = svc_endpoint + "/" + SAMPLE_NETWORK_INSTANCE_ID; + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + delete_nw_endpoint, + HttpStatus.NO_CONTENT_204, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executeDelete(msoCreateServiceInstanceJson, msoRestClient()::deleteNwInstance); } } @Test - public void testGetOrchestrationRequest() throws Exception { - MsoRestClientNew testSubject; - String t = ""; - String sourceId = ""; - String endpoint = ""; - RestObject restObject = null; - - // default test - try { - testSubject = createTestSubject(); - testSubject.getOrchestrationRequest(t, sourceId, endpoint, restObject); - } catch (Exception e) { + public void testGetOrchestrationRequest() { + String p = props.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ); + String path = p + "/" + SAMPLE_REQUEST_ID; + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + path, + HttpStatus.OK_200, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executeGet(msoRestClient()::getOrchestrationRequest); } } @Test - public void testGetManualTasks() throws Exception { - MsoRestClientNew testSubject; - String t = ""; - String sourceId = ""; - String endpoint = ""; - RestObject restObject = null; - - // default test - try { - testSubject = createTestSubject(); - testSubject.getManualTasks(t, sourceId, endpoint, restObject); - } catch (Exception e) { - } - } - - @Test - public void testCreateInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails request = null; - String path = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.createInstance(request, path); - } catch (Exception e) { - } - } - - @Test - public void testDeleteInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails request = null; - String path = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.deleteInstance(request, path); - } catch (Exception e) { + public void testGetManualTasks() { + String p = props.getProperty(MsoProperties.MSO_REST_API_GET_ORC_REQ); + String path = p + "/" + UUID.randomUUID(); + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + path, + HttpStatus.OK_200, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executeGet(msoRestClient()::getManualTasks); } } @@ -307,16 +344,17 @@ public class MsoRestClientNewTest { @Test public void testSetConfigurationActiveStatus() throws Exception { - MsoRestClientNew testSubject; - RequestDetails request = null; - String path = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.setConfigurationActiveStatus(request, path); - } catch (Exception e) { + String endpoint = "/serviceInstances/v5/<service_instance_id>/configurations/<configuration_id>"; + endpoint = endpoint.replace(MsoController.SVC_INSTANCE_ID, SERVICE_INSTANCE_ID); + endpoint = endpoint.replace(MsoController.CONFIGURATION_ID, SAMPLE_CONFIGURATION_ID); + endpoint = endpoint + "/activate"; + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + endpoint, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::setConfigurationActiveStatus); } } @@ -369,16 +407,15 @@ public class MsoRestClientNewTest { @Test public void testRemoveRelationshipFromServiceInstance() throws Exception { - MsoRestClientNew testSubject; - RequestDetails requestDetails = null; - String endpoint = ""; - MsoResponseWrapper result; - - // default test - try { - testSubject = createTestSubject(); - result = testSubject.removeRelationshipFromServiceInstance(requestDetails, endpoint); - } catch (Exception e) { + String serviceEndpoint = props.getProperty(MsoProperties.MSO_REST_API_SVC_INSTANCE); + String removeRelationshipsPath = serviceEndpoint + "/" + SERVICE_INSTANCE_ID + "/removeRelationships"; + + try(MsoRestClientTestUtil closure = new MsoRestClientTestUtil( + server, + removeRelationshipsPath, + HttpStatus.ACCEPTED_202, + CREATE_INSTANCE_RESPONSE_STR,CREATE_INSTANCE_RESPONSE_STR)) { + closure.executePost(msoCreateServiceInstanceJson, msoRestClient()::removeRelationshipFromServiceInstance); } } @@ -396,4 +433,12 @@ public class MsoRestClientNewTest { } catch (Exception e) { } } + + private MsoRestClientNew msoRestClient() { + return new MsoRestClientNew(new SyncRestClient(MsoInterface.objectMapper()), baseUrl()); + } + + private MsoRestClientNew createTestSubject() { + return new MsoRestClientNew(null, ""); + } }
\ No newline at end of file diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java index 0cfc0be1c..2b067b287 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTest.java @@ -1,9 +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.mso.rest; import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONObject; import org.junit.Assert; import org.onap.vid.changeManagement.RequestDetails; +import org.onap.vid.client.SyncRestClient; import org.onap.vid.domain.mso.CloudConfiguration; import org.onap.vid.domain.mso.ModelInfo; import org.onap.vid.domain.mso.RequestInfo; @@ -24,7 +45,7 @@ import org.togglz.core.manager.FeatureManager; public class MsoRestClientTest { - private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(new MsoRestClientNew(), null); + private MsoBusinessLogic msoBusinessLogic = new MsoBusinessLogicImpl(new MsoRestClientNew(new SyncRestClient(), ""), null); private ObjectMapper om = new ObjectMapper(); @Test diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java new file mode 100644 index 000000000..e8f556999 --- /dev/null +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/MsoRestClientTestUtil.java @@ -0,0 +1,108 @@ +package org.onap.vid.mso.rest; + +import static com.xebialabs.restito.builder.stub.StubHttp.whenHttp; +import static com.xebialabs.restito.builder.verify.VerifyHttp.verifyHttp; +import static com.xebialabs.restito.semantics.Action.contentType; +import static com.xebialabs.restito.semantics.Action.status; +import static com.xebialabs.restito.semantics.Action.stringContent; +import static com.xebialabs.restito.semantics.Condition.delete; +import static com.xebialabs.restito.semantics.Condition.get; +import static com.xebialabs.restito.semantics.Condition.method; +import static com.xebialabs.restito.semantics.Condition.post; +import static com.xebialabs.restito.semantics.Condition.uri; +import static com.xebialabs.restito.semantics.Condition.withHeader; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xebialabs.restito.semantics.Action; +import com.xebialabs.restito.server.StubServer; +import java.io.IOException; +import java.util.function.BiFunction; +import java.util.function.Function; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import org.glassfish.grizzly.http.Method; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.json.JSONObject; +import org.junit.Assert; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.vid.mso.MsoResponseWrapper; + +class MsoRestClientTestUtil implements AutoCloseable { + private final StubServer server; + private final String endpoint; + private final String responsePayload; + private final HttpStatus expectedStatus; + private final String expectedResponseStr; + + MsoRestClientTestUtil(StubServer server, String endpoint, HttpStatus expectedStatus, + String responsePayload, + String expectedResponseStr) { + this.server = server; + this.endpoint = endpoint; + this.responsePayload = responsePayload; + this.expectedStatus = expectedStatus; + this.expectedResponseStr = expectedResponseStr; + } + + void executePost(String jsonPayload, BiFunction<RequestDetails, String, MsoResponseWrapper> func) throws IOException { + whenHttp(server) + .match(post(endpoint)) + .then(status(expectedStatus), jsonContent(responsePayload), contentType(MediaType.APPLICATION_JSON)); + + RequestDetails sampleRequestDetails = + new ObjectMapper().readValue(jsonPayload, RequestDetails.class); + + MsoResponseWrapper response = func.apply(sampleRequestDetails, endpoint); + JSONObject actualJson = new JSONObject(response.getEntity()); + + Assert.assertEquals(expectedStatus.getStatusCode(), response.getStatus()); + Assert.assertEquals(expectedResponseStr, actualJson.toString()); + verifyServer(server, endpoint, Method.POST); + + } + + void executeDelete(String jsonPayload, BiFunction<RequestDetails, String, MsoResponseWrapper> func) + throws IOException { + whenHttp(server) + .match(delete(endpoint)) + .then(status(expectedStatus), jsonContent(responsePayload), contentType(MediaType.APPLICATION_JSON)); + + RequestDetails sampleRequestDetails = + new ObjectMapper().readValue(jsonPayload, RequestDetails.class); + MsoResponseWrapper response = func.apply(sampleRequestDetails, endpoint); + + Assert.assertEquals(expectedStatus.getStatusCode(), response.getStatus()); + verifyServer(server, endpoint, Method.DELETE); + } + + void executeGet(Function<String, MsoResponseWrapper> func) { + whenHttp(server) + .match(get(endpoint)) + .then(status(expectedStatus), jsonContent(responsePayload), contentType(MediaType.APPLICATION_JSON)); + + MsoResponseWrapper response = func.apply(endpoint); + + Assert.assertEquals(expectedStatus.getStatusCode(), response.getStatus()); + verifyServer(server, endpoint, Method.GET); + } + + private void verifyServer(StubServer server, String endpoint, Method httpMethod) { + verifyHttp(server).once( + method(httpMethod), + uri(endpoint), + withHeader(HttpHeaders.AUTHORIZATION), + withHeader(HttpHeaders.ACCEPT), + withHeader(HttpHeaders.CONTENT_TYPE), + withHeader(MsoRestClientNew.X_FROM_APP_ID), + withHeader(SystemProperties.ECOMP_REQUEST_ID)); + } + + private Action jsonContent(String str) { + return stringContent(str); + } + + @Override + public void close() { + } +} + diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java index da2600eaf..909975fb8 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestIdTest.java @@ -2,9 +2,13 @@ package org.onap.vid.mso.rest; import com.google.common.collect.ImmutableList; import org.apache.commons.lang3.reflect.FieldUtils; -import org.mockito.*; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; import org.onap.vid.aai.util.AAIRestInterface; -import org.onap.vid.asdc.rest.RestfulAsdcClient; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.controller.filter.PromiseEcompRequestIdFilter; import org.onap.vid.mso.RestMsoImplementation; @@ -27,10 +31,13 @@ import java.util.function.Consumer; import java.util.stream.Collectors; import java.util.stream.Stream; -import static java.util.UUID.randomUUID; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.*; -import static org.mockito.Mockito.mock; +import static org.hamcrest.Matchers.allOf; +import static org.hamcrest.Matchers.equalToIgnoringCase; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasToString; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.matchesPattern; public class OutgoingRequestIdTest { @@ -42,7 +49,6 @@ public class OutgoingRequestIdTest { @InjectMocks private AAIRestInterface aaiRestInterface; - private RestfulAsdcClient restfulAsdcClient = new RestfulAsdcClient.Builder(mock(Client.class), null).build(); @Captor private ArgumentCaptor<MultivaluedMap<String, Object>> multivaluedMapArgumentCaptor; @@ -58,23 +64,6 @@ public class OutgoingRequestIdTest { } @DataProvider - public Object[][] sdcMethods() { - return Stream.<ThrowingConsumer<RestfulAsdcClient>>of( - client -> client.getService(randomUUID()), - client -> client.getServiceToscaModel(randomUUID()) - ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); - } - - @Test(dataProvider = "sdcMethods") - public void sdc(Consumer<RestfulAsdcClient> f) throws Exception { - final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restfulAsdcClient); - - f.accept(restfulAsdcClient); - - verifyRequestIdHeaderWasAdded(mocks.getFakeBuilder()); - } - - @DataProvider public Object[][] msoMethods() { return Stream.<ThrowingConsumer<RestMsoImplementation>>of( diff --git a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java index 7becf8b7e..6390f5800 100644 --- a/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/scheduler/SchedulerRestInterfaceTest.java @@ -21,27 +21,22 @@ package org.onap.vid.scheduler; +import com.fasterxml.jackson.core.JsonProcessingException; import com.xebialabs.restito.semantics.Action; +import org.glassfish.grizzly.http.util.HttpStatus; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.*; import org.mockito.runners.MockitoJUnitRunner; -import org.onap.vid.aai.util.HttpClientMode; -import org.onap.vid.aai.util.HttpsAuthClient; +import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.testUtils.StubServerUtil; -import org.testng.annotations.BeforeMethod; - -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Invocation; -import javax.ws.rs.client.WebTarget; -import javax.ws.rs.core.MultivaluedHashMap; -import javax.ws.rs.core.Response; -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.Collections; -import java.util.function.Function; +import org.testng.annotations.AfterMethod; + +import java.util.HashMap; +import java.util.Map; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @@ -49,33 +44,25 @@ import static org.assertj.core.api.AssertionsForClassTypes.assertThat; @RunWith(MockitoJUnitRunner.class) public class SchedulerRestInterfaceTest { - private static final String USR_PWD_AUTH_STRING = "c2FtcGxlOnBhUyR3MFJk"; - private static final String APPLICATION_JSON = "application/json"; - private static MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap<>(); + private static final String SAMPLE_USERNAME = "sample"; + private static final String SAMPLE_PASSWORD = "paS$w0Rd"; + private static final String SAMPLE_SCHEDULER_SERVER_URL = "http://localhost"; + private static final String SAMPLE_SOURCE_ID = "AAI"; + private static final JSONParser JSON_PARSER = new JSONParser(); + private static final String RESPONSE_CONTENT = "\"schedules\": \"SAMPLE STRING\""; + private static final String ERROR_RESPONSE = "\"error\": \"Internal server error!\""; + private static Map<String, String> DUMMY_SYSTEM_PROPERTIES = new HashMap<String, String>() {{ + put(SchedulerProperties.SCHEDULER_USER_NAME_VAL, SAMPLE_USERNAME); + put(SchedulerProperties.SCHEDULER_PASSWORD_VAL, SAMPLE_PASSWORD); + put(SchedulerProperties.SCHEDULER_SERVER_URL_VAL, SAMPLE_SCHEDULER_SERVER_URL); + }}; private static StubServerUtil serverUtil; - private String sampleBaseUrl; - @Mock - private HttpsAuthClient mockedHttpsAuthClient; - @Mock - private Client mockedClient; - @Mock - private Invocation.Builder mockedBuilder; - @Mock - private Response mockedResponse; - @Mock - private WebTarget mockedWebTarget; - - @Mock - private Function<String, String> propertyGetter; - - @InjectMocks - private SchedulerRestInterface schedulerInterface = new SchedulerRestInterface(); + private static SchedulerRestInterface schedulerInterface = new SchedulerRestInterface((key) -> DUMMY_SYSTEM_PROPERTIES.get(key)); @BeforeClass public static void setUpClass() { serverUtil = new StubServerUtil(); serverUtil.runServer(); - commonHeaders.put("Authorization", Collections.singletonList("Basic " + USR_PWD_AUTH_STRING)); } @AfterClass @@ -83,76 +70,67 @@ public class SchedulerRestInterfaceTest { serverUtil.stopServer(); } - @BeforeMethod - public void setUp() { - MockitoAnnotations.initMocks(this); - sampleBaseUrl = serverUtil.constructTargetUrl("http", ""); + @AfterMethod + public void tearDown() { + serverUtil.stopServer(); } @Test - public void testShouldGetOKWhenStringIsExpected() throws IOException, GeneralSecurityException { - String sampleSourceId = "AAI"; + public void testShouldGetOKWhenStringIsExpected() throws JsonProcessingException, ParseException { + prepareEnvForTest(); RestObject<String> sampleRestObj = new RestObject<>(); - String resultHolder = ""; - - String responseContent = "sample : SAMPLE RESULT STRING"; - Mockito.doReturn(mockedClient).when(mockedHttpsAuthClient).getClient(HttpClientMode.WITHOUT_KEYSTORE); - Mockito.doReturn("sample").when(propertyGetter).apply(SchedulerProperties.SCHEDULER_USER_NAME_VAL); - Mockito.doReturn("paS$w0Rd").when(propertyGetter).apply(SchedulerProperties.SCHEDULER_PASSWORD_VAL); - Mockito.doReturn(sampleBaseUrl).when(propertyGetter).apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL); - Mockito.doReturn(200).when(mockedResponse).getStatus(); - Mockito.doReturn(responseContent).when(mockedResponse).readEntity(String.class); - Mockito.doReturn(mockedResponse).when(mockedBuilder).get(); - Mockito.when(mockedBuilder.header(Matchers.any(), Matchers.any())).thenReturn(mockedBuilder); - Mockito.doReturn(mockedBuilder).when(mockedBuilder).headers(commonHeaders); - Mockito.doReturn(mockedBuilder).when(mockedBuilder).accept(APPLICATION_JSON); - Mockito.doReturn(mockedBuilder).when(mockedWebTarget).request(); - Mockito.doReturn(mockedWebTarget).when(mockedClient).target(sampleBaseUrl + "test"); - - serverUtil.prepareGetCall("/test", responseContent, Action.ok()); - - schedulerInterface.Get(resultHolder, sampleSourceId, "test", sampleRestObj); - - assertResponseData(sampleRestObj, responseContent, 200); + serverUtil.prepareGetCall("/test", RESPONSE_CONTENT, Action.ok()); + + schedulerInterface.Get("", SAMPLE_SOURCE_ID, "", sampleRestObj); + + assertResponseHasExpectedBodyAndStatus(sampleRestObj, RESPONSE_CONTENT, 200); } + @Test(expected = GenericUncheckedException.class) + public void shouldRaiseExceptionWhenErrorOccursDuringGet() throws JsonProcessingException { + prepareEnvForTest(); + RestObject<String> sampleRestObj = new RestObject<>(); + + serverUtil.prepareGetCall("/test", ERROR_RESPONSE, Action.status(HttpStatus.INTERNAL_SERVER_ERROR_500)); + + schedulerInterface.Get("", SAMPLE_SOURCE_ID, "", sampleRestObj); + } @Test - public void testShouldDeleteSuccessfully() throws IOException, GeneralSecurityException { - String sampleTargetUrl = serverUtil.constructTargetUrl("http", ""); - String sampleSourceId = "AAI"; + public void shouldDeleteResourceSuccessfully() throws JsonProcessingException, ParseException { + prepareEnvForTest(); RestObject<String> sampleRestObj = new RestObject<>(); - String resultHolder = ""; - - String responseContent = "sample : SAMPLE RESULT STRING"; - Mockito.doReturn(mockedClient).when(mockedHttpsAuthClient).getClient(HttpClientMode.WITHOUT_KEYSTORE); - Mockito.doReturn("sample").when(propertyGetter).apply(SchedulerProperties.SCHEDULER_USER_NAME_VAL); - Mockito.doReturn("paS$w0Rd").when(propertyGetter).apply(SchedulerProperties.SCHEDULER_PASSWORD_VAL); - Mockito.doReturn(sampleTargetUrl).when(propertyGetter).apply(SchedulerProperties.SCHEDULER_SERVER_URL_VAL); - Mockito.doReturn(200).when(mockedResponse).getStatus(); - Mockito.doReturn(responseContent).when(mockedResponse).readEntity(String.class); - Mockito.doReturn(mockedResponse).when(mockedBuilder).delete(); - Mockito.when(mockedBuilder.header(Matchers.any(), Matchers.any())).thenReturn(mockedBuilder); - Mockito.doReturn(mockedBuilder).when(mockedBuilder).headers(commonHeaders); - Mockito.doReturn(mockedBuilder).when(mockedBuilder).accept(APPLICATION_JSON); - Mockito.doReturn(mockedBuilder).when(mockedWebTarget).request(); - Mockito.doReturn(mockedWebTarget).when(mockedClient).target(sampleTargetUrl + "test"); - - serverUtil.prepareDeleteCall("/test", responseContent, Action.ok()); - - schedulerInterface.Delete(resultHolder, sampleSourceId, "test", sampleRestObj); - - assertResponseData(sampleRestObj, responseContent, 200); + serverUtil.prepareDeleteCall("/test", RESPONSE_CONTENT, Action.ok()); + + schedulerInterface.Delete("", SAMPLE_SOURCE_ID, "", sampleRestObj); + + assertResponseHasExpectedBodyAndStatus(sampleRestObj, RESPONSE_CONTENT, 200); + } + + @Test + public void shouldRaiseExceptionWhenErrorOccursDuringDelete() throws JsonProcessingException, ParseException { + prepareEnvForTest(); + RestObject<String> sampleRestObj = new RestObject<>(); + serverUtil.prepareDeleteCall("/test", ERROR_RESPONSE, Action.status(HttpStatus.INTERNAL_SERVER_ERROR_500)); + + schedulerInterface.Delete("", SAMPLE_SOURCE_ID, "", sampleRestObj); + + assertResponseHasExpectedBodyAndStatus(sampleRestObj, ERROR_RESPONSE, 500); } - private void assertResponseData(RestObject<String> sampleRestObj, String expectedResponse, int expectedStatusCode) { + private void assertResponseHasExpectedBodyAndStatus(RestObject<String> sampleRestObj, String expectedResponse, int expectedStatusCode) throws ParseException { + Object parsedResult = JSON_PARSER.parse(sampleRestObj.get()); assertThat(sampleRestObj.getStatusCode()).isEqualTo(expectedStatusCode); - assertThat(sampleRestObj.get()).isInstanceOf(String.class).isEqualTo(expectedResponse); + assertThat(parsedResult).isInstanceOf(String.class).isEqualTo(expectedResponse); assertThat(sampleRestObj.getUUID()).isNull(); } + private void prepareEnvForTest() { + String targetUrl = serverUtil.constructTargetUrl("http", "test"); + DUMMY_SYSTEM_PROPERTIES.put(SchedulerProperties.SCHEDULER_SERVER_URL_VAL, targetUrl); + } } diff --git a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java index 5a21d8ca4..8aafda3f0 100644 --- a/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/services/ChangeManagementServiceUnitTest.java @@ -1,20 +1,41 @@ +/*- + * ============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.fasterxml.jackson.databind.ObjectMapper; +import io.joshworks.restclient.http.HttpResponse; import org.apache.commons.io.IOUtils; import org.mockito.ArgumentCaptor; import org.onap.vid.changeManagement.ChangeManagementRequest; +import org.onap.vid.changeManagement.RequestDetailsWrapper; +import org.onap.vid.client.SyncRestClient; import org.onap.vid.controllers.MsoConfig; import org.onap.vid.controllers.WebConfig; import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.mso.MsoBusinessLogic; -import org.onap.vid.mso.RestObject; +import org.onap.vid.mso.MsoInterface; import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.properties.AsdcClientConfiguration; import org.onap.vid.scheduler.SchedulerRestInterfaceIfc; -import org.onap.vid.services.ChangeManagementService; -import org.onap.vid.services.ChangeManagementServiceImpl; import org.onap.vid.testUtils.RegExMatcher; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.util.SystemProperties; @@ -47,23 +68,22 @@ public class ChangeManagementServiceUnitTest extends AbstractTestNGSpringContext @Inject private ChangeManagementService changeManagementService; @Inject - private MsoRestClientNew restClientUnderTest; + private MsoInterface restClientUnderTest; // @Test void testInPlaceSoftwareUpdateRequest() throws Exception { - doReturn(new RestObject<RequestReferencesContainer>()).when(restClientUnderTest).PostForObject(anyObject(), anyString(), anyString(), anyObject()); + doReturn(new HttpResponse<>(anyObject(), RequestReferencesContainer.class, anyObject())).when(restClientUnderTest).post(anyString(), anyObject(), anyObject()); URL requestJsonUrl = this.getClass().getResource("/services/change_management_software_update_request.json"); ChangeManagementRequest changeManagementRequest = objectMapper.readValue(requestJsonUrl, ChangeManagementRequest.class); changeManagementService.doChangeManagement(changeManagementRequest, "vidVnf"); ArgumentCaptor<String> endpointCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<String> sourceIdCaptor = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<Object> requestCaptor = ArgumentCaptor.forClass(Object.class); + ArgumentCaptor<RequestDetailsWrapper> requestCaptor = ArgumentCaptor.forClass(RequestDetailsWrapper.class); ArgumentCaptor<Class> responseTypeCaptor = ArgumentCaptor.forClass(Class.class); - verify(restClientUnderTest).PostForObject(requestCaptor.capture(), sourceIdCaptor.capture(), endpointCaptor.capture(), responseTypeCaptor.capture()); + verify(restClientUnderTest).post(endpointCaptor.capture(), requestCaptor.capture(), responseTypeCaptor.capture()); org.onap.vid.changeManagement.RequestDetails expectedRequest = changeManagementRequest.getRequestDetails().get(0); @@ -73,7 +93,7 @@ public class ChangeManagementServiceUnitTest extends AbstractTestNGSpringContext String regEx = String.format("/serviceInstances/v[0-9]+/%s/vnfs/%s/inPlaceSoftwareUpdate", serviceInstanceId, vnfInstanceId); assertThat(endpointCaptor.getValue(), RegExMatcher.matchesRegEx(regEx)); assertThat(requestCaptor.getValue(), instanceOf(RequestDetails.class)); - RequestDetails actualRequest = ((RequestDetails) requestCaptor.getValue()); + RequestDetails actualRequest = ((RequestDetails) requestCaptor.getValue().requestDetails); assertThat(actualRequest.getCloudConfiguration().getTenantId(), equalTo(expectedRequest.getCloudConfiguration().getTenantId())); assertThat(actualRequest.getCloudConfiguration().getLcpCloudRegionId(), equalTo(expectedRequest.getCloudConfiguration().getLcpCloudRegionId())); @@ -98,7 +118,7 @@ public class ChangeManagementServiceUnitTest extends AbstractTestNGSpringContext @Override public MsoRestClientNew getMsoClient() { - MsoRestClientNew spyClient = spy(new MsoRestClientNew()); + MsoRestClientNew spyClient = spy(new MsoRestClientNew(new SyncRestClient(), "")); return spyClient; } diff --git a/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java b/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java index e84655f7e..f7ffd9a9c 100644 --- a/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java +++ b/vid-app-common/src/test/java/org/onap/vid/testUtils/StubServerUtil.java @@ -23,9 +23,12 @@ package org.onap.vid.testUtils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.xebialabs.restito.semantics.Action; +import com.xebialabs.restito.semantics.Call; import com.xebialabs.restito.semantics.Condition; import com.xebialabs.restito.server.StubServer; +import java.util.List; + import static com.xebialabs.restito.builder.stub.StubHttp.whenHttp; import static com.xebialabs.restito.semantics.Action.contentType; import static com.xebialabs.restito.semantics.Action.stringContent; @@ -48,6 +51,10 @@ public class StubServerUtil { stubServer.run(); } + public void runSecuredServer(){ + stubServer.secured().run(); + } + public void stopServer() { stubServer.stop(); } @@ -57,10 +64,15 @@ public class StubServerUtil { return String.format("%s://localhost:%s/%s", protocol, stubServer.getPort(), relativePath); } - public void prepareGetCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { + public void prepareGetCall(String path, Action actionToReturn,Object returnObj, Action expectedAction, String contentType) throws JsonProcessingException { whenHttp(stubServer) .match(Condition.get(path)) - .then(expectedAction, jsonContent(returnObj), contentType(APPLICATION_JSON)); + .then(expectedAction, actionToReturn, contentType(contentType)); + } + + + public void prepareGetCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { + prepareGetCall(path, jsonContent(returnObj),returnObj, expectedAction, APPLICATION_JSON); } public void prepareDeleteCall(String path, Object returnObj, Action expectedAction) throws JsonProcessingException { @@ -83,6 +95,10 @@ public class StubServerUtil { .then(expectedStatus, jsonContent(returnObj), contentType(APPLICATION_JSON)); } + public List<Call> getServerCalls() { + return stubServer.getCalls(); + } + private Action jsonContent(Object returnObj) throws JsonProcessingException { return stringContent(objectMapper.writeValueAsString(returnObj)); } diff --git a/vid-app-common/src/test/resources/WEB-INF/conf/system.properties b/vid-app-common/src/test/resources/WEB-INF/conf/system.properties index a67f57897..689f55e58 100644 --- a/vid-app-common/src/test/resources/WEB-INF/conf/system.properties +++ b/vid-app-common/src/test/resources/WEB-INF/conf/system.properties @@ -83,6 +83,8 @@ aai.server.url.base=https://aai-ext1.test.att.com:8443/aai/ aai.server.url=http://localhost:8080/vidSimulator/aai/v12/ #aai.server.url=http://localhost:1080/aai #aai.server.url=https://aai-int2.test.att.com:8443/aai/v12/ +aai.vid.username=VID +aai.vid.passwd.x=OBF:1jm91i0v1jl9 @@ -178,8 +180,8 @@ mso.dme2.server.url=http://mso-api-handler-anap-v1.mso.ecomp.att.com/services/ec #mso.dme2.server.url=https://ActiveAndAvailableInventory-CloudNetwork-v1.aai.att.com/aai?version=1&envContext=DEV&routeOffer=devINT1 mso.dme2.enabled=false asdc.model.namespace=org.openecomp. -sdc.svc.api.path=asdc/v1/catalog/services -sdc.resource.api.path=asdc/v1/catalog/resource +sdc.svc.api.path=sdc/v1/catalog/services +sdc.resource.api.path=sdc/v1/catalog/resource # Application base URL has the host and app context only; a proper prefix of the on-boarded URL. # Only required for applications using WebJunction or FE/BE separation. For example: diff --git a/vid-app-common/src/test/resources/payload_jsons/mso_service_instantiation.json b/vid-app-common/src/test/resources/payload_jsons/mso_service_instantiation.json index 6c515ec2f..537b8d60c 100644 --- a/vid-app-common/src/test/resources/payload_jsons/mso_service_instantiation.json +++ b/vid-app-common/src/test/resources/payload_jsons/mso_service_instantiation.json @@ -29,7 +29,7 @@ "requestorId": "az2016" }, "requestParameters": { - "subscriptionServiceType":"MOG", // "subscriptionServiceType":"VMX", + "subscriptionServiceType":"MOG", "aLaCarte": false, "userParams": [{ "name": "TODO", diff --git a/vid-automation/pom.xml b/vid-automation/pom.xml index bf34a4f78..75d48a4b5 100644 --- a/vid-automation/pom.xml +++ b/vid-automation/pom.xml @@ -1,7 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<project xmlns="http://maven.apache.org/POM/4.0.0" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.onap.vid</groupId> @@ -12,7 +10,7 @@ <jersey.version>2.23.1</jersey.version> <jackson.version>2.6.3</jackson.version> <aspectj.version>1.8.10</aspectj.version> - + </properties> @@ -20,7 +18,7 @@ <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> - <version>23.0</version> + </dependency> <dependency> <groupId>org.openecomp.sdc</groupId> @@ -230,4 +228,4 @@ </plugin> </plugins> </build> -</project>
\ No newline at end of file +</project> diff --git a/vid-webpack-master/LICENSE b/vid-webpack-master/LICENSE index ad6b74029..90ec86ce4 100644 --- a/vid-webpack-master/LICENSE +++ b/vid-webpack-master/LICENSE @@ -1,3 +1,5 @@ +The vid-webpack-master project is provided under the Apache License, version 2.0 (Apache-2.0). It includes code from the angular-webpack template files, which were originally provided under the following license: + The MIT License (MIT) Copyright (c) 2016 Preboot team diff --git a/vid-webpack-master/README.md b/vid-webpack-master/README.md index 5c37773bd..25a7588b4 100644 --- a/vid-webpack-master/README.md +++ b/vid-webpack-master/README.md @@ -145,5 +145,5 @@ We have good experience using these editors: * [Sublime Text](http://www.sublimetext.com/3) with [Typescript-Sublime-Plugin](https://github.com/Microsoft/Typescript-Sublime-plugin#installation) # License +The vid-webpack-master project is provided under the Apache License, version 2.0 (Apache-2.0). It includes code from the angular-webpack template files, which were originally provided under the MIT license. -[MIT](/LICENSE) diff --git a/vid-webpack-master/package.json b/vid-webpack-master/package.json index 8cb4b927d..168ad95e0 100644 --- a/vid-webpack-master/package.json +++ b/vid-webpack-master/package.json @@ -1,7 +1,7 @@ { "name": "vid-cli", "version": "0.0.0", - "license": "MIT", + "license": "Apache-2.0", "scripts": { "ng": "ng", "start": "ng serve --port 4201", |