From c88676ec64c4c870252502bc1cfaa8990c8fd964 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Mon, 13 Jul 2020 16:06:57 -0400 Subject: Remove legacy actor code from models Deleted legacy actor code. That includes deleting most of the XxxManager classes. Issue-ID: POLICY-2559 Change-Id: I1ef1b900ca1d23e88da64b2c95a18986feb1b765 Signed-off-by: Jim Hahn --- .../java/org/onap/policy/sdnc/SdncManager.java | 158 --------- .../java/org/onap/policy/sdnc/SdncManagerTest.java | 192 ---------- .../main/java/org/onap/policy/so/SoManager.java | 389 --------------------- .../java/org/onap/policy/so/SoManagerTest.java | 344 ------------------ .../main/java/org/onap/policy/vfc/VfcManager.java | 196 ----------- .../java/org/onap/policy/vfc/VfcManagerTest.java | 209 ----------- 6 files changed, 1488 deletions(-) delete mode 100644 models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java delete mode 100644 models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java delete mode 100644 models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java delete mode 100644 models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java delete mode 100644 models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java delete mode 100644 models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java (limited to 'models-interactions/model-impl') diff --git a/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java b/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java deleted file mode 100644 index ec423c758..000000000 --- a/models-interactions/model-impl/sdnc/src/main/java/org/onap/policy/sdnc/SdncManager.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * ============LICENSE_START======================================================= - * Copyright (C) 2018 Huawei. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved - * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.policy.sdnc; - -import com.google.gson.JsonSyntaxException; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; -import org.onap.policy.rest.RestManager; -import org.onap.policy.sdnc.util.Serialization; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -// TODO this class will be deleted - -public final class SdncManager implements Runnable { - - private String sdncUrlBase; - private String username; - private String password; - private SdncRequest sdncRequest; - private SdncCallback callback; - private static final Logger logger = LoggerFactory.getLogger(SdncManager.class); - - // The REST manager used for processing REST calls for this Sdnc manager - private RestManager restManager; - - @FunctionalInterface - public interface SdncCallback { - public void onCallback(SdncResponse response); - } - - /** - * Constructor. - * - * @param cb Callback method - * @param request request - */ - public SdncManager(SdncCallback cb, SdncRequest request, String url, - String user, String password) { - if (cb == null || request == null) { - throw new IllegalArgumentException( - "the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null" - ); - } - this.callback = cb; - this.sdncRequest = request; - if (url == null) { - throw new IllegalArgumentException( - "the \"url\" parameter on the SdncManager constructor may not be null" - ); - } - this.sdncUrlBase = url; - this.username = user; - this.password = password; - - restManager = new RestManager(); - } - - /** - * Set the parameters. - * - * @param baseUrl base URL - * @param name username - * @param pwd password - */ - public void setSdncParams(String baseUrl, String name, String pwd) { - sdncUrlBase = baseUrl; - username = name; - password = pwd; - } - - @Override - public void run() { - Map headers = new HashMap<>(); - Pair httpDetails; - - SdncResponse responseError = new SdncResponse(); - SdncResponseOutput responseOutput = new SdncResponseOutput(); - responseOutput.setResponseCode("404"); - responseError.setResponseOutput(responseOutput); - - headers.put("Accept", "application/json"); - String sdncUrl = sdncUrlBase + sdncRequest.getUrl(); - - try { - String sdncRequestJson = Serialization.gsonPretty.toJson(sdncRequest); - NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, sdncUrl, sdncRequestJson); - logger.info("[OUT|{}|{}|]{}{}", CommInfrastructure.REST, sdncUrl, NetLoggerUtil.SYSTEM_LS, sdncRequestJson); - - httpDetails = restManager.post(sdncUrl, username, password, headers, "application/json", - sdncRequestJson); - } catch (Exception e) { - logger.info(e.getMessage(), e); - this.callback.onCallback(responseError); - return; - } - - if (httpDetails == null) { - this.callback.onCallback(responseError); - return; - } - - try { - SdncResponse response = Serialization.gsonPretty.fromJson(httpDetails.getRight(), SdncResponse.class); - NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, sdncUrl, httpDetails.getRight()); - logger.info("[IN|{}|{}|]{}{}", "Sdnc", sdncUrl, NetLoggerUtil.SYSTEM_LS, httpDetails.getRight()); - String body = Serialization.gsonPretty.toJson(response); - logger.info("Response to Sdnc Heal post:"); - logger.info(body); - response.setRequestId(sdncRequest.getRequestId().toString()); - - if (!"200".equals(response.getResponseOutput().getResponseCode())) { - logger.info( - "Sdnc Heal Restcall failed with http error code {} {}", - httpDetails.getLeft(), httpDetails.getRight() - ); - } - - this.callback.onCallback(response); - } catch (JsonSyntaxException e) { - logger.info("Failed to deserialize into SdncResponse {}", e.getLocalizedMessage(), e); - } catch (Exception e) { - logger.info("Unknown error deserializing into SdncResponse {}", e.getLocalizedMessage(), e); - } - } - - /** - * Protected setter for rest manager to allow mocked rest manager to be used for testing. - * @param restManager the test REST manager - */ - protected void setRestManager(final RestManager restManager) { - this.restManager = restManager; - } -} diff --git a/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java b/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java deleted file mode 100644 index 45461de43..000000000 --- a/models-interactions/model-impl/sdnc/src/test/java/org/onap/policy/sdnc/SdncManagerTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * sdnc - * ================================================================================ - * Copyright (C) 2018 Huawei. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2019-2020 AT&T Intellectual Property. All rights reserved - * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.policy.sdnc; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.startsWith; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.UUID; -import org.apache.commons.lang3.tuple.Pair; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.rest.RestManager; -import org.onap.policy.sdnc.SdncManager.SdncCallback; -import org.onap.policy.sdnc.util.Serialization; - -public class SdncManagerTest implements SdncCallback { - private static final String SOMEWHERE_OVER_THE_RAINBOW = "http://somewhere.over.the.rainbow"; - - private static final String DOROTHY = "Dorothy"; - - private RestManager mockedRestManager; - - private Pair httpResponsePutOk; - private Pair httpResponseBadResponse; - private Pair httpResponseErr; - - private SdncRequest request; - private SdncResponse response; - - /** - * Set up the mocked REST manager. - */ - @Before - public void setupMockedRest() { - mockedRestManager = mock(RestManager.class); - - httpResponsePutOk = Pair.of(202, Serialization.gsonPretty.toJson(response)); - httpResponseBadResponse = Pair.of(202, Serialization.gsonPretty.toJson(null)); - httpResponseErr = Pair.of(200, null); - } - - /** - * Create the request and response before. - */ - @Before - public void createRequestAndResponse() { - SdncHealServiceInfo serviceInfo = new SdncHealServiceInfo(); - serviceInfo.setServiceInstanceId("E-City"); - - SdncHealRequestHeaderInfo additionalParams = new SdncHealRequestHeaderInfo(); - additionalParams.setSvcAction("Go Home"); - additionalParams.setSvcRequestId("My Request"); - - SdncHealRequest healRequest = new SdncHealRequest(); - healRequest.setRequestHeaderInfo(additionalParams); - healRequest.setServiceInfo(serviceInfo); - - UUID requestId = UUID.randomUUID(); - request = new SdncRequest(); - request.setRequestId(requestId); - request.setHealRequest(healRequest); - request.setNsInstanceId(DOROTHY); - - SdncResponseOutput responseDescriptor = new SdncResponseOutput(); - responseDescriptor.setSvcRequestId("1234"); - responseDescriptor.setResponseCode("200"); - responseDescriptor.setAckFinalIndicator("final-indicator-00"); - - response = new SdncResponse(); - response.setRequestId(request.getRequestId().toString()); - response.setResponseOutput(responseDescriptor); - } - - @Test - public void testSdncInitiation() { - - assertThatIllegalArgumentException().isThrownBy(() -> new SdncManager(null, null, null, null, null)) - .withMessage("the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null"); - - assertThatIllegalArgumentException().isThrownBy(() -> new SdncManager(this, null, null, null, null)) - .withMessage("the parameters \"callback\" and \"request\" on the SdncManager constructor may not be null"); - - assertThatIllegalArgumentException().isThrownBy(() -> new SdncManager(this, request, null, null, null)) - .withMessage("the \"url\" parameter on the SdncManager constructor may not be null"); - - new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Toto"); - } - - @Test - public void testSdncExecutionException() throws InterruptedException { - SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Exception"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("Exception"), anyMap(), - anyString(), anyString())).thenThrow(new RuntimeException("OzException")); - - Thread managerThread = new Thread(manager); - managerThread.start(); - - managerThread.join(1000); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Test - public void testSdncExecutionNull() throws InterruptedException { - SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Null"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("Null"), anyMap(), - anyString(), anyString())).thenReturn(null); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - - @Test - public void testSdncExecutionError0() throws InterruptedException { - SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "Error0"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("Error0"), anyMap(), - anyString(), anyString())).thenReturn(httpResponseErr); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Test - public void testSdncExecutionBadResponse() throws InterruptedException { - SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "BadResponse"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("OK"), anyMap(), - anyString(), anyString())).thenReturn(httpResponseBadResponse); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Test - public void testSdncExecutionOk() throws InterruptedException { - SdncManager manager = new SdncManager(this, request, SOMEWHERE_OVER_THE_RAINBOW, DOROTHY, "OOK"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOMEWHERE_OVER_THE_RAINBOW), eq(DOROTHY), eq("OK"), anyMap(), - anyString(), anyString())).thenReturn(httpResponsePutOk); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Override - public void onCallback(SdncResponse response) { - // - // Nothing really to do - // - } -} diff --git a/models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java b/models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java deleted file mode 100644 index 5b8aef264..000000000 --- a/models-interactions/model-impl/so/src/main/java/org/onap/policy/so/SoManager.java +++ /dev/null @@ -1,389 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * so - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.policy.so; - -import com.google.gson.GsonBuilder; -import com.google.gson.JsonSyntaxException; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; -import org.onap.policy.rest.RestManager; -import org.onap.policy.so.util.Serialization; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class handles the interface towards SO (Service Orchestrator) for the ONAP Policy Framework. The SO API is - * defined at this link: - * http://onap.readthedocs.io/en/latest/submodules/so.git/docs/SO_R1_Interface.html#get-orchestration-request - * - */ -public final class SoManager { - - // TODO remove this class - - private static final Logger logger = LoggerFactory.getLogger(SoManager.class); - - private static ExecutorService executors = Executors.newCachedThreadPool(); - - private static final int SO_RESPONSE_ERROR = 999; - private static final String MEDIA_TYPE = "application/json"; - private static final String LINE_SEPARATOR = System.lineSeparator(); - - // REST get timeout value in milliseconds - private static final int GET_REQUESTS_BEFORE_TIMEOUT = 20; - private static final long GET_REQUEST_WAIT_INTERVAL = 20000; - - // The REST manager used for processing REST calls for this VFC manager - private RestManager restManager; - - private long restGetTimeout = GET_REQUEST_WAIT_INTERVAL; - - private String url; - private String user; - private String password; - - @FunctionalInterface - public interface SoCallback { - public void onSoResponseWrapper(SoResponseWrapper wrapper); - } - - /** - * Default constructor. - */ - public SoManager(String url, String user, String password) { - this.url = url; - this.user = user; - this.password = password; - restManager = new RestManager(); - } - - /** - * Create a service instance in SO. - * - * @param url the SO URL - * @param urlBase the base URL - * @param username user name on SO - * @param password password on SO - * @param request the request to issue to SO - * @return the SO Response object - */ - public SoResponse createModuleInstance(final String url, final String urlBase, final String username, - final String password, final SoRequest request) { - // Issue the HTTP POST request to SO to create the service instance - String requestJson = Serialization.gsonPretty.toJson(request); - NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|{}|{}|{}|{}|]{}{}", "SO", url, username, password, - createSimpleHeaders(), MEDIA_TYPE, LINE_SEPARATOR, requestJson); - Pair httpResponse = - restManager.post(url, username, password, createSimpleHeaders(), MEDIA_TYPE, requestJson); - - // Process the response from SO - SoResponse response = waitForSoOperationCompletion(urlBase, username, password, url, httpResponse); - if (SO_RESPONSE_ERROR != response.getHttpResponseCode()) { - return response; - } else { - return null; - } - } - - /** - * Works just like SOManager#asyncSORestCall(String, WorkingMemory, String, String, String, SORequest) except the - * vfModuleInstanceId is always null. - * - */ - public Future asyncSoRestCall(final String requestId, final SoCallback callback, - final String serviceInstanceId, final String vnfInstanceId, final SoRequest request) { - return asyncSoRestCall(requestId, callback, serviceInstanceId, vnfInstanceId, null, request); - } - - /** - * This method makes an asynchronous Rest call to MSO and inserts the response into Drools working memory. - * - * @param requestId the request id - * @param callback callback method - * @param serviceInstanceId service instance id to construct the request url - * @param vnfInstanceId vnf instance id to construct the request url - * @param vfModuleInstanceId vfModule instance id to construct the request url (required in case of delete vf - * module) - * @param request the SO request - * @return a concurrent Future for the thread that handles the request - */ - public Future asyncSoRestCall(final String requestId, final SoCallback callback, - final String serviceInstanceId, final String vnfInstanceId, final String vfModuleInstanceId, - final SoRequest request) { - return executors.submit(new AsyncSoRestCallThread(requestId, callback, serviceInstanceId, vnfInstanceId, - vfModuleInstanceId, request, this)); - } - - /** - * This class handles an asynchronous request to SO as a thread. - */ - private class AsyncSoRestCallThread implements Callable { - final String requestId; - final SoCallback callback; - final String serviceInstanceId; - final String vnfInstanceId; - final String vfModuleInstanceId; - final SoRequest request; - final String baseUrl; - final String user; - final String password; - - /** - * Constructor, sets the context of the request. - * - * @param requestID The request ID - * @param wm reference to the Drools working memory - * @param serviceInstanceId the service instance in SO to use - * @param vnfInstanceId the VNF instance that is the subject of the request - * @param vfModuleInstanceId the vf module instance id (not null in case of delete vf module request) - * @param request the request itself - */ - private AsyncSoRestCallThread(final String requestId, final SoCallback callback, final String serviceInstanceId, - final String vnfInstanceId, final String vfModuleInstanceId, final SoRequest request, - final SoManager callingSoManager) { - this.requestId = requestId; - this.callback = callback; - this.serviceInstanceId = serviceInstanceId; - this.vnfInstanceId = vnfInstanceId; - this.vfModuleInstanceId = vfModuleInstanceId; - this.request = request; - this.baseUrl = callingSoManager.url; - this.user = callingSoManager.user; - this.password = callingSoManager.password; - } - - /** - * Process the asynchronous SO request. - */ - @Override - public SoResponse call() { - - // Create a JSON representation of the request - String soJson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(request); - String initialUrl = null; - Pair httpResponse = null; - - if (request.getOperationType() != null && request.getOperationType().equals(SoOperationType.SCALE_OUT)) { - initialUrl = this.baseUrl + "/serviceInstantiation/v7/serviceInstances/" + serviceInstanceId + "/vnfs/" - + vnfInstanceId + "/vfModules/scaleOut"; - NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, initialUrl, soJson); - httpResponse = restManager.post(initialUrl, this.user, this.password, createSimpleHeaders(), MEDIA_TYPE, - soJson); - } else if (request.getOperationType() != null - && request.getOperationType().equals(SoOperationType.DELETE_VF_MODULE)) { - initialUrl = this.baseUrl + "/serviceInstances/v7/" + serviceInstanceId + "/vnfs/" + vnfInstanceId - + "/vfModules/" + vfModuleInstanceId; - NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, initialUrl, soJson); - httpResponse = restManager.delete(initialUrl, this.user, this.password, createSimpleHeaders(), - MEDIA_TYPE, soJson); - } else { - return null; - } - - // Process the response from SO - SoResponse response = - waitForSoOperationCompletion(this.baseUrl, this.user, this.password, initialUrl, httpResponse); - - // Return the response to Drools in its working memory - SoResponseWrapper soWrapper = new SoResponseWrapper(response, requestId); - if (this.callback != null) { - this.callback.onSoResponseWrapper(soWrapper); - } - - return response; - } - } - - /** - * Wait for the SO operation we have ordered to complete. - * - * @param urlBaseSo The base URL for SO - * @param username user name on SO - * @param password password on SO - * @param initialRequestUrl The URL of the initial HTTP request - * @param initialHttpResponse The initial HTTP message returned from SO - * @return The parsed final response of SO to the request - */ - private SoResponse waitForSoOperationCompletion(final String urlBaseSo, final String username, - final String password, final String initialRequestUrl, final Pair initialHttpResponse) { - // Process the initial response from SO, the response to a post - SoResponse response = processSoResponse(initialRequestUrl, initialHttpResponse); - if (SO_RESPONSE_ERROR == response.getHttpResponseCode()) { - return response; - } - - // The SO URL to use to get the status of orchestration requests - String urlGet = urlBaseSo + "/orchestrationRequests/v5/" + response.getRequestReferences().getRequestId(); - - // The HTTP status code of the latest response - Pair latestHttpResponse = initialHttpResponse; - - // Wait for the response from SO - for (int attemptsLeft = GET_REQUESTS_BEFORE_TIMEOUT; attemptsLeft >= 0; attemptsLeft--) { - // The SO request may have completed even on the first request so we check the - // response - // here before - // issuing any other requests - if (isRequestStateFinished(latestHttpResponse, response)) { - return response; - } - - // Wait for the defined interval before issuing a get - try { - Thread.sleep(restGetTimeout); - } catch (InterruptedException e) { - logger.error("Interrupted exception: ", e); - Thread.currentThread().interrupt(); - response.setHttpResponseCode(SO_RESPONSE_ERROR); - return response; - } - - // Issue a GET to find the current status of our request - NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|{}|{}|{}|{}|]{}", "SO", urlGet, username, password, - createSimpleHeaders(), MEDIA_TYPE, LINE_SEPARATOR); - Pair httpResponse = restManager.get(urlGet, username, password, createSimpleHeaders()); - - // Get our response - response = processSoResponse(urlGet, httpResponse); - if (SO_RESPONSE_ERROR == response.getHttpResponseCode()) { - return response; - } - - // Our latest HTTP response code - latestHttpResponse = httpResponse; - } - - // We have timed out on the SO request - response.setHttpResponseCode(SO_RESPONSE_ERROR); - return response; - } - - /** - * Parse the response message from SO into a SOResponse object. - * - * @param requestURL The URL of the HTTP request - * @param httpResponse The HTTP message returned from SO - * @return The parsed response - */ - private SoResponse processSoResponse(final String requestUrl, final Pair httpResponse) { - SoResponse response = new SoResponse(); - - // A null httpDetails indicates a HTTP problem, a valid response from SO must be - // either 200 - // or 202 - if (!httpResultIsNullFree(httpResponse) || (httpResponse.getLeft() != 200 && httpResponse.getLeft() != 202)) { - logger.error("Invalid HTTP response received from SO"); - response.setHttpResponseCode(SO_RESPONSE_ERROR); - return response; - } - - // Parse the JSON of the response into our POJO - try { - response = Serialization.gsonPretty.fromJson(httpResponse.getRight(), SoResponse.class); - } catch (JsonSyntaxException e) { - logger.error("Failed to deserialize HTTP response into SOResponse: ", e); - response.setHttpResponseCode(SO_RESPONSE_ERROR); - return response; - } - - // Set the HTTP response code of the response if needed - if (response.getHttpResponseCode() == 0) { - response.setHttpResponseCode(httpResponse.getLeft()); - } - - NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, requestUrl, httpResponse.getRight()); - - if (logger.isDebugEnabled()) { - logger.debug("***** Response to SO Request to URL {}:", requestUrl); - logger.debug(httpResponse.getRight()); - } - - return response; - } - - /** - * Method to allow tuning of REST get timeout. - * - * @param restGetTimeout the timeout value - */ - protected void setRestGetTimeout(final long restGetTimeout) { - this.restGetTimeout = restGetTimeout; - } - - /** - * Check that the request state of a response is defined. - * - * @param response The response to check - * @return true if the request for the response is defined - */ - private boolean isRequestStateDefined(final SoResponse response) { - return response != null && response.getRequest() != null && response.getRequest().getRequestStatus() != null - && response.getRequest().getRequestStatus().getRequestState() != null; - } - - /** - * Check that the request state of a response is finished. - * - * @param latestHttpDetails the HTTP details of the response - * @param response The response to check - * @return true if the request for the response is finished - */ - private boolean isRequestStateFinished(final Pair latestHttpDetails, final SoResponse response) { - if (latestHttpDetails != null && 200 == latestHttpDetails.getLeft() && isRequestStateDefined(response)) { - String requestState = response.getRequest().getRequestStatus().getRequestState(); - return "COMPLETE".equalsIgnoreCase(requestState) || "FAILED".equalsIgnoreCase(requestState); - } else { - return false; - } - } - - /** - * Check that a HTTP operation result has no nulls. - * - * @param httpOperationResult the result to check - * @return true if no nulls are found - */ - private boolean httpResultIsNullFree(Pair httpOperationResult) { - return httpOperationResult != null && httpOperationResult.getLeft() != null - && httpOperationResult.getRight() != null; - } - - /** - * Create simple HTTP headers for unauthenticated requests to SO. - * - * @return the HTTP headers - */ - private Map createSimpleHeaders() { - Map headers = new HashMap<>(); - headers.put("Accept", MEDIA_TYPE); - return headers; - } -} diff --git a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java b/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java deleted file mode 100644 index aa3562ae5..000000000 --- a/models-interactions/model-impl/so/src/test/java/org/onap/policy/so/SoManagerTest.java +++ /dev/null @@ -1,344 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * TestSOManager - * ================================================================================ - * Copyright (C) 2018 Ericsson. All rights reserved. - * ================================================================================ - * Modifications Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. - * ================================================================================ - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.policy.so; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.net.URI; -import java.util.UUID; -import java.util.concurrent.Future; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.util.EntityUtils; -import org.glassfish.grizzly.http.server.HttpServer; -import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; -import org.glassfish.jersey.server.ResourceConfig; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.onap.policy.so.SoManager.SoCallback; - -public class SoManagerTest implements SoCallback { - private static final String LOCALHOST_99999999 = "http:/localhost:99999999"; - private static final String CITIZEN = "citizen"; - private static final String RETURN_ONGING202 = "ReturnOnging202"; - private static final String RETURN_ONGING200 = "ReturnOnging200"; - private static final String RETURN_FAILED = "ReturnFailed"; - private static final String RETURN_COMPLETED = "ReturnCompleted"; - private static final String RETURN_BAD_JSON = "ReturnBadJson"; - private static final String RETURN_BAD_AFTER_WAIT = "ReturnBadAfterWait"; - private static final String ONGOING = "ONGOING"; - private static final String FAILED = "FAILED"; - private static final String COMPLETE = "COMPLETE"; - private static final String DATE1 = "2018-03-23 16:31"; - private static final String SERVICE_INSTANTIATION_V7 = "/serviceInstantiation/v7"; - private static final String BASE_URI = "http://localhost:46553/TestSOManager"; - private static final String BASE_SO_URI = BASE_URI + "/SO"; - private static HttpServer server; - - /** - * Set up test class. - */ - @BeforeClass - public static void setUp() throws IOException { - final ResourceConfig rc = new ResourceConfig(SoDummyServer.class); - //Grizzly by default doesn't allow payload for HTTP methods (ex: DELETE), for which HTTP spec doesn't - // explicitly state that. - //allow it before starting the server - server = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc, false); - server.getServerConfiguration().setAllowPayloadForUndefinedHttpMethods(true); - server.start(); - } - - @AfterClass - public static void tearDown() { - server.shutdown(); - } - - @Test - public void testGrizzlyServer() throws IOException { - try (CloseableHttpClient httpclient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://localhost:46553/TestSOManager/SO/Stats"); - CloseableHttpResponse response = httpclient.execute(httpGet); - - String returnBody = EntityUtils.toString(response.getEntity(), "UTF-8"); - assertTrue(returnBody.matches("^\\{\"GET\": [0-9]*,\"STAT\": [0-9]*,\"POST\": [0-9]*,\"PUT\": [0-9]*," - + "\"DELETE\": [0-9]*\\}$")); - } - } - - @Test - public void testServiceInstantiation() { - SoManager manager = new SoManager(null, null, null); - assertNotNull(manager); - manager.setRestGetTimeout(100); - - SoResponse response = manager.createModuleInstance(LOCALHOST_99999999, BASE_SO_URI, "sean", - CITIZEN, null); - assertNull(response); - - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, null); - assertNull(response); - - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, new SoRequest()); - assertNull(response); - - SoRequest request = new SoRequest(); - request.setRequestId(UUID.randomUUID()); - request.setRequestScope("Test"); - request.setRequestType(RETURN_BAD_JSON); - request.setStartTime(DATE1); - request.setRequestStatus(new SoRequestStatus()); - request.getRequestStatus().setRequestState(ONGOING); - - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, request); - assertNull(response); - - request.setRequestType(RETURN_COMPLETED); - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, request); - assertNotNull(response); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType(RETURN_FAILED); - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, request); - assertNotNull(response); - assertEquals(FAILED, response.getRequest().getRequestStatus().getRequestState()); - - // Use scope to set the number of iterations we'll wait for - - request.setRequestType(RETURN_ONGING200); - request.setRequestScope("10"); - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, request); - assertNotNull(response); - assertNotNull(response.getRequest()); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType(RETURN_ONGING202); - request.setRequestScope("20"); - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, request); - assertNotNull(response); - assertNotNull(response.getRequest()); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - // Test timeout after 20 attempts for a response - request.setRequestType(RETURN_ONGING202); - request.setRequestScope("21"); - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, request); - assertNull(response); - - // Test bad response after 3 attempts for a response - request.setRequestType(RETURN_BAD_AFTER_WAIT); - request.setRequestScope("3"); - response = manager.createModuleInstance(BASE_SO_URI + SERVICE_INSTANTIATION_V7, BASE_SO_URI, "sean", - CITIZEN, request); - assertNull(response); - } - - @Test - public void testVfModuleCreation() throws Exception { - SoManager manager = new SoManager(LOCALHOST_99999999, "sean", CITIZEN); - assertNotNull(manager); - manager.setRestGetTimeout(100); - - SoRequest soRequest = new SoRequest(); - soRequest.setOperationType(SoOperationType.SCALE_OUT); - Future asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, - UUID.randomUUID().toString(), UUID.randomUUID().toString(), soRequest); - SoResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - manager = new SoManager(BASE_SO_URI, "sean", CITIZEN); - manager.setRestGetTimeout(100); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), soRequest); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - SoRequest request = new SoRequest(); - request.setRequestId(UUID.randomUUID()); - request.setRequestScope("Test"); - request.setRequestType(RETURN_BAD_JSON); - request.setStartTime(DATE1); - request.setRequestStatus(new SoRequestStatus()); - request.getRequestStatus().setRequestState(ONGOING); - request.setOperationType(SoOperationType.SCALE_OUT); - - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - request.setRequestType(RETURN_COMPLETED); - - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType(RETURN_FAILED); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(FAILED, response.getRequest().getRequestStatus().getRequestState()); - - // Use scope to set the number of iterations we'll wait for - - request.setRequestType(RETURN_ONGING200); - request.setRequestScope("10"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertNotNull(response.getRequest()); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType(RETURN_ONGING202); - request.setRequestScope("20"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertNotNull(response.getRequest()); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - // Test timeout after 20 attempts for a response - request.setRequestType(RETURN_ONGING202); - request.setRequestScope("21"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - // Test bad response after 3 attempts for a response - request.setRequestType(RETURN_BAD_AFTER_WAIT); - request.setRequestScope("3"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } - - @Test - public void testVfModuleDeletion() throws Exception { - SoManager manager = new SoManager(LOCALHOST_99999999, "sean", CITIZEN); - assertNotNull(manager); - manager.setRestGetTimeout(100); - - SoRequest soRequest = new SoRequest(); - soRequest.setOperationType(SoOperationType.DELETE_VF_MODULE); - Future asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, - UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), soRequest); - SoResponse response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - manager = new SoManager(BASE_SO_URI, "sean", CITIZEN); - manager.setRestGetTimeout(100); - - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), soRequest); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - SoRequest request = new SoRequest(); - request.setRequestId(UUID.randomUUID()); - request.setRequestScope("Test"); - request.setRequestType(RETURN_BAD_JSON); - request.setStartTime(DATE1); - request.setRequestStatus(new SoRequestStatus()); - request.getRequestStatus().setRequestState(ONGOING); - request.setOperationType(SoOperationType.DELETE_VF_MODULE); - - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - request.setRequestType(RETURN_COMPLETED); - - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType(RETURN_FAILED); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(FAILED, response.getRequest().getRequestStatus().getRequestState()); - - // Use scope to set the number of iterations we'll wait for - - request.setRequestType(RETURN_ONGING200); - request.setRequestScope("10"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertNotNull(response.getRequest()); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - request.setRequestType(RETURN_ONGING202); - request.setRequestScope("20"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertNotNull(response.getRequest()); - assertEquals(COMPLETE, response.getRequest().getRequestStatus().getRequestState()); - - // Test timeout after 20 attempts for a response - request.setRequestType(RETURN_ONGING202); - request.setRequestScope("21"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - - // Test bad response after 3 attempts for a response - request.setRequestType(RETURN_BAD_AFTER_WAIT); - request.setRequestScope("3"); - asyncRestCallFuture = manager.asyncSoRestCall(UUID.randomUUID().toString(), this, UUID.randomUUID().toString(), - UUID.randomUUID().toString(), UUID.randomUUID().toString(), request); - response = asyncRestCallFuture.get(); - assertEquals(999, response.getHttpResponseCode()); - } - - @Override - public void onSoResponseWrapper(SoResponseWrapper wrapper) { - // - // Nothing really needed to do - // - } -} diff --git a/models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java b/models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java deleted file mode 100644 index 64d60ba1e..000000000 --- a/models-interactions/model-impl/vfc/src/main/java/org/onap/policy/vfc/VfcManager.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * Copyright (C) 2017-2019 Intel Corp. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation. - * Modifications Copyright (C) 2018-2019 AT&T Corporation. All rights reserved. - * Modifications Copyright (C) 2019 Samsung Electronics Co., Ltd. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.policy.vfc; - -import com.google.gson.JsonSyntaxException; -import java.util.HashMap; -import java.util.Map; -import org.apache.commons.lang3.tuple.Pair; -import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil; -import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; -import org.onap.policy.rest.RestManager; -import org.onap.policy.vfc.util.Serialization; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public final class VfcManager implements Runnable { - - private String vfcUrlBase; - private String username; - private String password; - private VfcRequest vfcRequest; - private VfcCallback callback; - private static final Logger logger = LoggerFactory.getLogger(VfcManager.class); - - // The REST manager used for processing REST calls for this VFC manager - private RestManager restManager; - - @FunctionalInterface - public interface VfcCallback { - void onResponse(VfcResponse responseError); - } - - /** - * Constructor. - * - * @param cb Callback method to call when response - * @param request request - * @param url URL to VFC component - * @param user username - * @param pwd password - */ - public VfcManager(VfcCallback cb, VfcRequest request, String url, String user, String pwd) { - if (cb == null || request == null) { - throw new IllegalArgumentException( - "the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null"); - } - if (url == null) { - throw new IllegalArgumentException( - "the \"url\" parameter on the VfcManager constructor may not be null"); - } - callback = cb; - vfcRequest = request; - vfcUrlBase = url; - username = user; - password = pwd; - - restManager = new RestManager(); - } - - /** - * Set the parameters. - * - * @param baseUrl base URL - * @param name username - * @param pwd password - */ - public void setVfcParams(String baseUrl, String name, String pwd) { - vfcUrlBase = baseUrl + "/api/nslcm/v1"; - username = name; - password = pwd; - } - - @Override - public void run() { - Map headers = new HashMap<>(); - Pair httpDetails; - - VfcResponse responseError = new VfcResponse(); - responseError.setResponseDescriptor(new VfcResponseDescriptor()); - responseError.getResponseDescriptor().setStatus("error"); - - headers.put("Accept", "application/json"); - String vfcUrl = vfcUrlBase + "/ns/" + vfcRequest.getNsInstanceId() + "/heal"; - try { - String vfcRequestJson = Serialization.gsonPretty.toJson(vfcRequest); - NetLoggerUtil.log(EventType.OUT, CommInfrastructure.REST, vfcUrl, vfcRequestJson); - - httpDetails = restManager.post(vfcUrl, username, password, headers, "application/json", vfcRequestJson); - } catch (Exception e) { - logger.error(e.getMessage(), e); - this.callback.onResponse(responseError); - return; - } - - if (httpDetails == null) { - this.callback.onResponse(responseError); - return; - } - - if (httpDetails.getLeft() != 202) { - logger.warn("VFC Heal Restcall failed"); - return; - } - - try { - handleVfcResponse(headers, httpDetails, vfcUrl); - } catch (JsonSyntaxException e) { - logger.error("Failed to deserialize into VfcResponse {}", e.getLocalizedMessage(), e); - } catch (InterruptedException e) { - logger.error("Interrupted exception: {}", e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (Exception e) { - logger.error("Unknown error deserializing into VfcResponse {}", e.getLocalizedMessage(), e); - } - } - - /** - * Handle a VFC response message. - * - * @param headers the headers in the response - * @param httpDetails the HTTP details in the response - * @param vfcUrl the response URL - * @throws InterruptedException on errors in the response - */ - private void handleVfcResponse(Map headers, Pair httpDetails, String vfcUrl) - throws InterruptedException { - VfcResponse response = Serialization.gsonPretty.fromJson(httpDetails.getRight(), VfcResponse.class); - NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, vfcUrl, httpDetails.getRight()); - String body = Serialization.gsonPretty.toJson(response); - logger.debug("Response to VFC Heal post:"); - logger.debug(body); - - String jobId = response.getJobId(); - int attemptsLeft = 20; - - String urlGet = vfcUrlBase + "/jobs/" + jobId; - VfcResponse responseGet = null; - - while (attemptsLeft-- > 0) { - NetLoggerUtil.getNetworkLogger().info("[OUT|{}|{}|]", "VFC", urlGet); - Pair httpDetailsGet = restManager.get(urlGet, username, password, headers); - responseGet = Serialization.gsonPretty.fromJson(httpDetailsGet.getRight(), VfcResponse.class); - NetLoggerUtil.log(EventType.IN, CommInfrastructure.REST, vfcUrl, httpDetailsGet.getRight()); - responseGet.setRequestId(vfcRequest.getRequestId().toString()); - body = Serialization.gsonPretty.toJson(responseGet); - logger.debug("Response to VFC Heal get:"); - logger.debug(body); - - String responseStatus = responseGet.getResponseDescriptor().getStatus(); - if (httpDetailsGet.getLeft() == 200 - && ("finished".equalsIgnoreCase(responseStatus) || "error".equalsIgnoreCase(responseStatus))) { - logger.debug("VFC Heal Status {}", responseGet.getResponseDescriptor().getStatus()); - this.callback.onResponse(responseGet); - return; - } - Thread.sleep(20000); - } - boolean isTimeout = (attemptsLeft <= 0) && (responseGet != null) - && (responseGet.getResponseDescriptor() != null); - isTimeout = isTimeout && (responseGet.getResponseDescriptor().getStatus() != null) - && (!responseGet.getResponseDescriptor().getStatus().isEmpty()); - if (isTimeout) { - logger.debug("VFC timeout. Status: ({})", responseGet.getResponseDescriptor().getStatus()); - this.callback.onResponse(responseGet); - } - } - - /** - * Protected setter for rest manager to allow mocked rest manager to be used for testing. - * - * @param restManager the test REST manager - */ - protected void setRestManager(final RestManager restManager) { - this.restManager = restManager; - } -} diff --git a/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java b/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java deleted file mode 100644 index fbe29c384..000000000 --- a/models-interactions/model-impl/vfc/src/test/java/org/onap/policy/vfc/VfcManagerTest.java +++ /dev/null @@ -1,209 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * vfc - * ================================================================================ - * Copyright (C) 2018-2020 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019-2020 Nordix Foundation.. All rights reserved. - * Modifications Copyright (C) 2018-2019 AT&T Corporation. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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.policy.vfc; - -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.startsWith; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import org.apache.commons.lang3.tuple.Pair; -import org.junit.Before; -import org.junit.Test; -import org.onap.policy.rest.RestManager; -import org.onap.policy.vfc.VfcManager.VfcCallback; -import org.onap.policy.vfc.util.Serialization; - -public class VfcManagerTest implements VfcCallback { - - private static final String SOME_URL = "http://somewhere.over.the.rainbow"; - - private static final String DOROTHY = "Dorothy"; - - private RestManager mockedRestManager; - - private Pair httpResponsePutOk; - private Pair httpResponseBadResponse; - private Pair httpResponseErr; - - private VfcRequest request; - private VfcResponse response; - - /** - * Set up the mocked REST manager. - */ - @Before - public void setupMockedRest() { - mockedRestManager = mock(RestManager.class); - - httpResponsePutOk = Pair.of(202, Serialization.gsonPretty.toJson(response)); - httpResponseBadResponse = Pair.of(202, Serialization.gsonPretty.toJson(null)); - httpResponseErr = Pair.of(200, null); - } - - /** - * Create the request and response before. - */ - @Before - public void createRequestAndResponse() { - VfcHealActionVmInfo actionInfo = new VfcHealActionVmInfo(); - actionInfo.setVmid("TheWizard"); - actionInfo.setVmname("The Wizard of Oz"); - - VfcHealAdditionalParams additionalParams = new VfcHealAdditionalParams(); - additionalParams.setAction("Go Home"); - additionalParams.setActionInfo(actionInfo); - - VfcHealRequest healRequest = new VfcHealRequest(); - healRequest.setAdditionalParams(additionalParams); - healRequest.setCause("WestWitch"); - healRequest.setVnfInstanceId("EmeraldCity"); - - final UUID requestId = UUID.randomUUID(); - request = new VfcRequest(); - request.setHealRequest(healRequest); - request.setNsInstanceId(DOROTHY); - request.setRequestId(requestId); - - List responseHistoryList = new ArrayList<>();; - - VfcResponseDescriptor responseDescriptor = new VfcResponseDescriptor(); - responseDescriptor.setErrorCode("1234"); - responseDescriptor.setProgress("Follow The Yellow Brick Road"); - responseDescriptor.setResponseHistoryList(responseHistoryList); - responseDescriptor.setResponseId(UUID.randomUUID().toString()); - responseDescriptor.setStatus("finished"); - responseDescriptor.setStatusDescription("There's no place like home"); - - response = new VfcResponse(); - response.setJobId("1234"); - response.setRequestId(request.getRequestId().toString()); - response.setResponseDescriptor(responseDescriptor); - } - - @Test - public void testVfcInitiation() { - assertThatIllegalArgumentException().isThrownBy(() -> new VfcManager(null, null, null, null, null)).withMessage( - "the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null"); - - assertThatIllegalArgumentException().isThrownBy(() -> new VfcManager(this, null, null, null, null)).withMessage( - "the parameters \"cb\" and \"request\" on the VfcManager constructor may not be null"); - - assertThatIllegalArgumentException().isThrownBy(() -> new VfcManager(this, request, null, null, null)) - .withMessage("the \"url\" parameter on the VfcManager constructor may not be null"); - - new VfcManager(this, request, SOME_URL, null, null); - - new VfcManager(this, request, SOME_URL, DOROTHY, "Toto"); - } - - @Test - public void testVfcExecutionException() throws InterruptedException { - VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Exception"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post( - startsWith(SOME_URL), - eq(DOROTHY), - eq("Exception"), - anyMap(), - anyString(), - anyString())) - .thenThrow(new RuntimeException("OzException")); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Test - public void testVfcExecutionNull() throws InterruptedException { - VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Null"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOME_URL), - eq(DOROTHY), eq("Null"), anyMap(), anyString(), anyString())) - .thenReturn(null); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Test - public void testVfcExecutionError0() throws InterruptedException { - VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Error0"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOME_URL), - eq(DOROTHY), eq("Error0"), anyMap(), anyString(), anyString())) - .thenReturn(httpResponseErr); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Test - public void testVfcExecutionBadResponse() throws InterruptedException { - VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "BadResponse"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOME_URL), - eq(DOROTHY), eq("OK"), anyMap(), anyString(), anyString())) - .thenReturn(httpResponseBadResponse); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Test - public void testVfcExecutionOk() throws InterruptedException { - VfcManager manager = new VfcManager(this, request, SOME_URL, DOROTHY, "Ok"); - manager.setRestManager(mockedRestManager); - - when(mockedRestManager.post(startsWith(SOME_URL), - eq(DOROTHY), eq("OK"), anyMap(), anyString(), anyString())) - .thenReturn(httpResponsePutOk); - - manager.run(); - - verify(mockedRestManager).post(any(), any(), any(), any(), any(), any()); - } - - @Override - public void onResponse(VfcResponse responseError) { - // - // Nothing needs to be done - // - } -} -- cgit 1.2.3-korg