diff options
Diffstat (limited to 'vid-app-common')
18 files changed, 479 insertions, 878 deletions
diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java index 034800516..45ced6bdf 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/AAIRestInterface.java @@ -8,9 +8,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,6 +22,7 @@ package org.onap.vid.aai.util; import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; +import static org.onap.vid.logging.Headers.PARTNER_NAME; import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; import com.att.eelf.configuration.EELFLogger; @@ -52,305 +53,308 @@ import org.springframework.http.HttpMethod; */ public class AAIRestInterface { - /** The logger. */ - protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class); - - protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai"); - - /** The client. */ - private Client client = null; - - /** The rest srvr base URL. */ - private String restSrvrBaseURL; - - @Autowired - protected HttpsAuthClient httpsAuthClientFactory; - private final ServletRequestHelper servletRequestHelper; - private final SystemPropertyHelper systemPropertyHelper; - protected final Logging loggingService; - - protected static final String START_STRING = " start"; - protected static final String TRANSACTION_ID_HEADER = "X-TransactionId"; - protected static final String FROM_APP_ID_HEADER = "X-FromAppId"; - protected static final String SUCCESSFUL_API_MESSAGE = " REST api call was successful!"; - protected static final String URL_DECLARATION = ", url="; - - public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory, - ServletRequestHelper servletRequestHelper, - SystemPropertyHelper systemPropertyHelper, - Logging loggingService) { - this.httpsAuthClientFactory = httpsAuthClientFactory; - this.servletRequestHelper = servletRequestHelper; - this.systemPropertyHelper = systemPropertyHelper; - this.loggingService = loggingService; - initRestClient(); - } - - /** - * For testing purpose - */ - AAIRestInterface(Optional<Client> client, - HttpsAuthClient httpsAuthClientFactory, - ServletRequestHelper servletRequestHelper, - SystemPropertyHelper systemPropertyHelper, - Logging loggingService){ - this.httpsAuthClientFactory = httpsAuthClientFactory; - this.servletRequestHelper = servletRequestHelper; - this.systemPropertyHelper = systemPropertyHelper; - this.loggingService = loggingService; - if (client != null && client.isPresent()){ - this.client = client.get(); - } - - } - - /** - * Encode URL. - * - * @param nodeKey the node key - * @return the string - * @throws UnsupportedEncodingException the unsupported encoding exception - */ - public String encodeURL (String nodeKey) throws UnsupportedEncodingException { - return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20"); - } - - protected void initRestClient() { - initRestClient(false); - } - - - private void initRestClient(boolean propagateExceptions) { - if (client == null) { - try { - client = httpsAuthClientFactory.getClient(HttpClientMode.WITH_KEYSTORE); - } catch (Exception e) { - logger.info(EELFLoggerDelegate.errorLogger, "Exception in REST call to DB in initRestClient" + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, "Exception in REST call to DB : " + e.toString()); - if (propagateExceptions) { - ExceptionUtils.rethrow(e); - } - } - } - } - - - - /** - * Sets the rest srvr base URL. - * - * @param baseURL the base URL - */ - public void setRestSrvrBaseURL(String baseURL) - { - if (baseURL == null) { - logger.info(EELFLoggerDelegate.errorLogger, "REST Server base URL cannot be null."); - logger.debug(EELFLoggerDelegate.debugLogger, "REST Server base URL cannot be null."); - } - - restSrvrBaseURL = baseURL; - } - - /** - * Gets the rest srvr base URL. - * - * @return the rest srvr base URL - */ - public String getRestSrvrBaseURL() { - return restSrvrBaseURL; - } - - - /** - * Rest get. - * - * @param fromAppId the from app id - * @param transId the trans id - * @param requestUri the request uri - * @param xml the xml - * @return the string - */ - public ResponseWithRequestInfo RestGet(String fromAppId, String transId, URI requestUri, boolean xml) { - return RestGet(fromAppId, transId, requestUri, xml, false); - } - - public ResponseWithRequestInfo RestGet(String fromAppId, String transId, URI requestUri, boolean xml, boolean propagateExceptions) { - return doRest(fromAppId, transId, requestUri, null, HttpMethod.GET, xml, propagateExceptions); - } - - public ResponseWithRequestInfo doRest(String fromAppId, String transId, URI requestUri, String payload, HttpMethod method, boolean xml, boolean propagateExceptions) { - String url = null; - String methodName = "Rest"+method.name(); - try { - - url = systemPropertyHelper.getFullServicePath(requestUri); - - initRestClient(propagateExceptions); - - logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING); - logger.debug(EELFLoggerDelegate.debugLogger, url + " for the get REST API"); - - loggingService.logRequest(outgoingRequestsLogger, method, url, payload); - - final Response response; - Invocation.Builder requestBuilder = client.target(url) - .request() - .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()); - - requestBuilder = systemPropertyHelper.isClientCertEnabled() ? - requestBuilder : authenticateRequest(requestBuilder); - - Invocation restInvocation = StringUtils.isEmpty(payload) ? - requestBuilder.build(method.name()) : - requestBuilder.build(method.name(), Entity.entity(payload, MediaType.APPLICATION_JSON)); - - response = restInvocation.invoke(); - loggingService.logResponse(outgoingRequestsLogger, method, url, response); - - if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { - logger.debug(EELFLoggerDelegate.debugLogger, methodName + SUCCESSFUL_API_MESSAGE); - logger.info(EELFLoggerDelegate.errorLogger, methodName + SUCCESSFUL_API_MESSAGE); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response)); - } - return new ResponseWithRequestInfo(response, url, method); - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); - if (propagateExceptions) { - throw new ExceptionWithRequestInfo(method, defaultIfNull(url, requestUri.toASCIIString()), e); - } else { - return new ResponseWithRequestInfo(null, url, method); - } - } - } - - protected String extractOrGenerateRequestId() { - return servletRequestHelper.extractOrGenerateRequestId(); - } - - - /** - * Delete. - * - * @param sourceID the source ID - * @param transId the trans id - * @param path the path - * @return true, if successful - */ - public boolean Delete(String sourceID, String transId, String path) { - String methodName = "Delete"; - transId += ":" + UUID.randomUUID().toString(); - logger.debug(methodName + START_STRING); - Boolean response = false; - String url = systemPropertyHelper.getFullServicePath(path); - try { - - initRestClient(); - loggingService.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url); - final Response cres = client.target(url) - .request() - .accept(MediaType.APPLICATION_JSON) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, sourceID) - .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) - .delete(); - loggingService.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres); - if (cres.getStatusInfo().equals(Response.Status.NOT_FOUND)) { - logger.debug(EELFLoggerDelegate.debugLogger, "Resource does not exist...: " + cres.getStatus() - + ":" + cres.readEntity(String.class)); - response = false; - } else if (cres.getStatusInfo().equals(Response.Status.OK) || cres.getStatusInfo().equals(Response.Status.NO_CONTENT)) { - logger.debug(EELFLoggerDelegate.debugLogger, "Resource " + url + " deleted"); - logger.info(EELFLoggerDelegate.errorLogger, "Resource " + url + " deleted"); - response = true; - } else { - logger.debug(EELFLoggerDelegate.debugLogger, "Deleting Resource failed: " + cres.getStatus() - + ":" + cres.readEntity(String.class)); - response = false; - } - - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); - } - return response; - } - - - /** - * Rest put. - * - * @param fromAppId the from app id - * @param path the path - * @param payload the payload - * @param xml the xml - * @param propagateExceptions - * @return the string - */ - public ResponseWithRequestInfo RestPut(String fromAppId, String path, String payload, boolean xml, boolean propagateExceptions) { - return doRest(fromAppId, UUID.randomUUID().toString(), Unchecked.toURI(path), payload, HttpMethod.PUT, xml, propagateExceptions); - } - - - - /** - * Rest post. - * - * @param fromAppId the from app id - * @param path the path - * @param payload the payload - * @param xml the xml - * @return the string - */ - public Response RestPost(String fromAppId, String path, String payload, boolean xml) { - String methodName = "RestPost"; - String url=systemPropertyHelper.getServiceBasePath(path); - String transId = UUID.randomUUID().toString(); - logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING); - - Response response = null; - try { - initRestClient(); - loggingService.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload); - response = authenticateRequest(client.target(url) - .request() - .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId)) - .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) - .post(Entity.entity(payload, MediaType.APPLICATION_JSON)); - loggingService.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, response); - - if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) { - logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName)); - logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName)); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response)); - } - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); - } - return response; - } - - protected String getFailedResponseLogMessage(String path, String methodName, Exception e) { - return methodName + URL_DECLARATION + path + ", Exception: " + e.toString(); - } - - protected String getValidResponseLogMessage(String methodName) { - return methodName + URL_DECLARATION; - } - - protected String getInvalidResponseLogMessage(String path, String methodName, Response cres) { - return methodName + " with status=" + cres.getStatus() + URL_DECLARATION + path; - } - - private Invocation.Builder authenticateRequest(Invocation.Builder requestBuilder) throws InvalidPropertyException, UnsupportedEncodingException { - return requestBuilder - .header("Authorization", "Basic " + systemPropertyHelper.getEncodedCredentials()); - } + /** The logger. */ + protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class); + + protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai"); + + /** The client. */ + private Client client = null; + + /** The rest srvr base URL. */ + private String restSrvrBaseURL; + + @Autowired + protected HttpsAuthClient httpsAuthClientFactory; + private final ServletRequestHelper servletRequestHelper; + private final SystemPropertyHelper systemPropertyHelper; + protected final Logging loggingService; + + protected static final String START_STRING = " start"; + protected static final String TRANSACTION_ID_HEADER = "X-TransactionId"; + protected static final String FROM_APP_ID_HEADER = "X-FromAppId"; + protected static final String SUCCESSFUL_API_MESSAGE = " REST api call was successful!"; + protected static final String URL_DECLARATION = ", url="; + + public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory, + ServletRequestHelper servletRequestHelper, + SystemPropertyHelper systemPropertyHelper, + Logging loggingService) { + this.httpsAuthClientFactory = httpsAuthClientFactory; + this.servletRequestHelper = servletRequestHelper; + this.systemPropertyHelper = systemPropertyHelper; + this.loggingService = loggingService; + initRestClient(); + } + + /** + * For testing purpose + */ + AAIRestInterface(Optional<Client> client, + HttpsAuthClient httpsAuthClientFactory, + ServletRequestHelper servletRequestHelper, + SystemPropertyHelper systemPropertyHelper, + Logging loggingService){ + this.httpsAuthClientFactory = httpsAuthClientFactory; + this.servletRequestHelper = servletRequestHelper; + this.systemPropertyHelper = systemPropertyHelper; + this.loggingService = loggingService; + if (client != null && client.isPresent()){ + this.client = client.get(); + } + + } + + /** + * Encode URL. + * + * @param nodeKey the node key + * @return the string + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + public String encodeURL (String nodeKey) throws UnsupportedEncodingException { + return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20"); + } + + protected void initRestClient() { + initRestClient(false); + } + + + private void initRestClient(boolean propagateExceptions) { + if (client == null) { + try { + client = httpsAuthClientFactory.getClient(HttpClientMode.WITH_KEYSTORE); + } catch (Exception e) { + logger.info(EELFLoggerDelegate.errorLogger, "Exception in REST call to DB in initRestClient" + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, "Exception in REST call to DB : " + e.toString()); + if (propagateExceptions) { + ExceptionUtils.rethrow(e); + } + } + } + } + + + + /** + * Sets the rest srvr base URL. + * + * @param baseURL the base URL + */ + public void setRestSrvrBaseURL(String baseURL) + { + if (baseURL == null) { + logger.info(EELFLoggerDelegate.errorLogger, "REST Server base URL cannot be null."); + logger.debug(EELFLoggerDelegate.debugLogger, "REST Server base URL cannot be null."); + } + + restSrvrBaseURL = baseURL; + } + + /** + * Gets the rest srvr base URL. + * + * @return the rest srvr base URL + */ + public String getRestSrvrBaseURL() { + return restSrvrBaseURL; + } + + + /** + * Rest get. + * + * @param fromAppId the from app id + * @param transId the trans id + * @param requestUri the request uri + * @param xml the xml + * @return the string + */ + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, URI requestUri, boolean xml) { + return RestGet(fromAppId, transId, requestUri, xml, false); + } + + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, URI requestUri, boolean xml, boolean propagateExceptions) { + return doRest(fromAppId, transId, requestUri, null, HttpMethod.GET, xml, propagateExceptions); + } + + public ResponseWithRequestInfo doRest(String fromAppId, String transId, URI requestUri, String payload, HttpMethod method, boolean xml, boolean propagateExceptions) { + String url = null; + String methodName = "Rest"+method.name(); + try { + + url = systemPropertyHelper.getFullServicePath(requestUri); + + initRestClient(propagateExceptions); + + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING); + logger.debug(EELFLoggerDelegate.debugLogger, url + " for the get REST API"); + + loggingService.logRequest(outgoingRequestsLogger, method, url, payload); + + final Response response; + Invocation.Builder requestBuilder = client.target(url) + .request() + .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) + .header(PARTNER_NAME.getHeaderName(), PARTNER_NAME.getHeaderValue()) + .header(TRANSACTION_ID_HEADER, transId) + .header(FROM_APP_ID_HEADER, fromAppId) + .header("Content-Type", MediaType.APPLICATION_JSON) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()); + + requestBuilder = systemPropertyHelper.isClientCertEnabled() ? + requestBuilder : authenticateRequest(requestBuilder); + + Invocation restInvocation = StringUtils.isEmpty(payload) ? + requestBuilder.build(method.name()) : + requestBuilder.build(method.name(), Entity.entity(payload, MediaType.APPLICATION_JSON)); + + response = restInvocation.invoke(); + loggingService.logResponse(outgoingRequestsLogger, method, url, response); + + if (response.getStatusInfo().getFamily() == Response.Status.Family.SUCCESSFUL) { + logger.debug(EELFLoggerDelegate.debugLogger, methodName + SUCCESSFUL_API_MESSAGE); + logger.info(EELFLoggerDelegate.errorLogger, methodName + SUCCESSFUL_API_MESSAGE); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response)); + } + return new ResponseWithRequestInfo(response, url, method); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); + if (propagateExceptions) { + throw new ExceptionWithRequestInfo(method, defaultIfNull(url, requestUri.toASCIIString()), e); + } else { + return new ResponseWithRequestInfo(null, url, method); + } + } + } + + protected String extractOrGenerateRequestId() { + return servletRequestHelper.extractOrGenerateRequestId(); + } + + + /** + * Delete. + * + * @param sourceID the source ID + * @param transId the trans id + * @param path the path + * @return true, if successful + */ + public boolean Delete(String sourceID, String transId, String path) { + String methodName = "Delete"; + transId += ":" + UUID.randomUUID().toString(); + logger.debug(methodName + START_STRING); + Boolean response = false; + String url = systemPropertyHelper.getFullServicePath(path); + try { + + initRestClient(); + loggingService.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url); + final Response cres = client.target(url) + .request() + .accept(MediaType.APPLICATION_JSON) + .header(TRANSACTION_ID_HEADER, transId) + .header(PARTNER_NAME.getHeaderName(), PARTNER_NAME.getHeaderValue()) + .header(FROM_APP_ID_HEADER, sourceID) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) + .delete(); + loggingService.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres); + if (cres.getStatusInfo().equals(Response.Status.NOT_FOUND)) { + logger.debug(EELFLoggerDelegate.debugLogger, "Resource does not exist...: " + cres.getStatus() + + ":" + cres.readEntity(String.class)); + response = false; + } else if (cres.getStatusInfo().equals(Response.Status.OK) || cres.getStatusInfo().equals(Response.Status.NO_CONTENT)) { + logger.debug(EELFLoggerDelegate.debugLogger, "Resource " + url + " deleted"); + logger.info(EELFLoggerDelegate.errorLogger, "Resource " + url + " deleted"); + response = true; + } else { + logger.debug(EELFLoggerDelegate.debugLogger, "Deleting Resource failed: " + cres.getStatus() + + ":" + cres.readEntity(String.class)); + response = false; + } + + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); + } + return response; + } + + + /** + * Rest put. + * + * @param fromAppId the from app id + * @param path the path + * @param payload the payload + * @param xml the xml + * @param propagateExceptions + * @return the string + */ + public ResponseWithRequestInfo RestPut(String fromAppId, String path, String payload, boolean xml, boolean propagateExceptions) { + return doRest(fromAppId, UUID.randomUUID().toString(), Unchecked.toURI(path), payload, HttpMethod.PUT, xml, propagateExceptions); + } + + + + /** + * Rest post. + * + * @param fromAppId the from app id + * @param path the path + * @param payload the payload + * @param xml the xml + * @return the string + */ + public Response RestPost(String fromAppId, String path, String payload, boolean xml) { + String methodName = "RestPost"; + String url=systemPropertyHelper.getServiceBasePath(path); + String transId = UUID.randomUUID().toString(); + logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_STRING); + + Response response = null; + try { + initRestClient(); + loggingService.logRequest(outgoingRequestsLogger, HttpMethod.POST, url, payload); + response = authenticateRequest(client.target(url) + .request() + .accept(xml ? MediaType.APPLICATION_XML : MediaType.APPLICATION_JSON) + .header(TRANSACTION_ID_HEADER, transId) + .header(PARTNER_NAME.getHeaderName(), PARTNER_NAME.getHeaderValue()) + .header(FROM_APP_ID_HEADER, fromAppId)) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) + .post(Entity.entity(payload, MediaType.APPLICATION_JSON)); + loggingService.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, response); + + if (response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) { + logger.info(EELFLoggerDelegate.errorLogger, getValidResponseLogMessage(methodName)); + logger.debug(EELFLoggerDelegate.debugLogger, getValidResponseLogMessage(methodName)); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, getInvalidResponseLogMessage(url, methodName, response)); + } + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, getFailedResponseLogMessage(url, methodName, e)); + } + return response; + } + + protected String getFailedResponseLogMessage(String path, String methodName, Exception e) { + return methodName + URL_DECLARATION + path + ", Exception: " + e.toString(); + } + + protected String getValidResponseLogMessage(String methodName) { + return methodName + URL_DECLARATION; + } + + protected String getInvalidResponseLogMessage(String path, String methodName, Response cres) { + return methodName + " with status=" + cres.getStatus() + URL_DECLARATION + path; + } + + private Invocation.Builder authenticateRequest(Invocation.Builder requestBuilder) throws InvalidPropertyException, UnsupportedEncodingException { + return requestBuilder + .header("Authorization", "Basic " + systemPropertyHelper.getEncodedCredentials()); + } } diff --git a/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java b/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java index 3c061986c..5607018b0 100644 --- a/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/client/HttpBasicClient.java @@ -21,14 +21,11 @@ package org.onap.vid.client; -import org.glassfish.jersey.client.ClientConfig; -import org.glassfish.jersey.client.ClientProperties; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; - import javax.servlet.ServletContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; /** * General HTTP client. @@ -51,10 +48,8 @@ public class HttpBasicClient{ */ public static Client getClient() { - ClientConfig config = new ClientConfig(); - config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); - - return ClientBuilder.newClient(config) - .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); + return ClientBuilder + .newClient() + .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); } } diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java b/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java index 5b05caa7a..4e7a77cd3 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/MsoConfig.java @@ -30,6 +30,7 @@ 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.RestMsoImplementation; import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.services.CloudOwnerService; import org.onap.vid.services.CloudOwnerServiceImpl; @@ -49,14 +50,23 @@ public class MsoConfig { } @Bean - public MsoRestClientNew msoClient(ObjectMapper unirestObjectMapper, - HttpsAuthClient httpsAuthClient, + public MsoRestClientNew msoRestClientNew(ObjectMapper unirestObjectMapper, SystemPropertiesWrapper systemPropertiesWrapper, Logging loggingService){ // Satisfy both interfaces -- MsoInterface and RestMsoImplementation return new MsoRestClientNew( new SyncRestClient(unirestObjectMapper, loggingService), SystemProperties.getProperty(MsoProperties.MSO_SERVER_URL), + systemPropertiesWrapper + ); + } + + @Bean + public RestMsoImplementation restMsoImplementation(HttpsAuthClient httpsAuthClient, + SystemPropertiesWrapper systemPropertiesWrapper, + Logging loggingService){ + // Satisfy both interfaces -- MsoInterface and RestMsoImplementation + return new RestMsoImplementation( httpsAuthClient, systemPropertiesWrapper, loggingService diff --git a/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java b/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java index 535c97ce7..da66e8951 100644 --- a/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java +++ b/vid-app-common/src/main/java/org/onap/vid/controller/MsoController.java @@ -38,7 +38,6 @@ import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapper2; import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; -import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.RequestDetailsWrapper; @@ -90,7 +89,7 @@ public class MsoController extends RestrictedBaseController { private final CloudOwnerService cloudOwnerService; @Autowired - public MsoController(MsoBusinessLogic msoBusinessLogic, MsoRestClientNew msoClientInterface, CloudOwnerService cloudOwnerService) { + public MsoController(MsoBusinessLogic msoBusinessLogic, RestMsoImplementation msoClientInterface, CloudOwnerService cloudOwnerService) { this.msoBusinessLogic = msoBusinessLogic; this.restMso = msoClientInterface; this.cloudOwnerService = cloudOwnerService; diff --git a/vid-app-common/src/main/java/org/onap/vid/logging/Headers.kt b/vid-app-common/src/main/java/org/onap/vid/logging/Headers.kt index a0bbceea1..e9f83ef22 100644 --- a/vid-app-common/src/main/java/org/onap/vid/logging/Headers.kt +++ b/vid-app-common/src/main/java/org/onap/vid/logging/Headers.kt @@ -4,18 +4,35 @@ package org.onap.vid.logging import org.onap.portalsdk.core.util.SystemProperties import org.onap.vid.logging.RequestIdHeader.* +import java.util.* import javax.servlet.http.HttpServletRequest -enum class RequestIdHeader(val headerName: String) { +interface Header { + val headerName: String + fun stringEquals(header: String): Boolean = headerName.equals(header, true) +} + +abstract class NamedHeader(override val headerName: String) : Header { + abstract fun getHeaderValue(): String +} + +@JvmField +val PARTNER_NAME = object : NamedHeader("X-ONAP-PartnerName") { + override fun getHeaderValue() = "VID.VID" +} + +@JvmField +val INVOCATION_ID = object : NamedHeader("X-InvocationID") { + override fun getHeaderValue() = UUID.randomUUID().toString() +} +enum class RequestIdHeader(override val headerName: String) : Header { ONAP_ID("X-ONAP-RequestID"), REQUEST_ID("X-RequestID"), TRANSACTION_ID("X-TransactionID"), ECOMP_ID(SystemProperties.ECOMP_REQUEST_ID), ; - fun stringEquals(header: String) = headerName.equals(header, true) - fun getHeaderValue(request: HttpServletRequest): String? = request.getHeader(headerName) } 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 3d980dce8..8f9b98a55 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 @@ -30,6 +30,7 @@ import static org.onap.vid.controller.MsoController.REQUEST_TYPE; import static org.onap.vid.controller.MsoController.SVC_INSTANCE_ID; import static org.onap.vid.controller.MsoController.VNF_INSTANCE_ID; import static org.onap.vid.controller.MsoController.WORKFLOW_ID; +import static org.onap.vid.logging.Headers.PARTNER_NAME; import static org.onap.vid.mso.MsoProperties.MSO_REST_API_CLOUD_RESOURCES_REQUEST_STATUS; import static org.onap.vid.mso.MsoProperties.MSO_REST_API_OPERATIONAL_ENVIRONMENT_ACTIVATE; import static org.onap.vid.mso.MsoProperties.MSO_REST_API_OPERATIONAL_ENVIRONMENT_CREATE; @@ -230,7 +231,7 @@ public class MsoBusinessLogicImpl implements MsoBusinessLogic { UUID requestId = UUID.randomUUID(); extraHeaders.put("X-ONAP-RequestID",requestId.toString()); - extraHeaders.put("X-ONAP-PartnerName","VID"); + extraHeaders.put(PARTNER_NAME.getHeaderName(), PARTNER_NAME.getHeaderValue()); extraHeaders.put("X-RequestorID",userId); return msoClientInterface.invokeWorkflow(request,final_endpoint,extraHeaders); 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 d1cb3a37b..a16b44925 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 @@ -21,14 +21,13 @@ package org.onap.vid.mso; import io.joshworks.restclient.http.HttpResponse; +import java.util.Map; import org.onap.vid.aai.HttpResponseWithRequestInfo; import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.model.SOWorkflowList; import org.onap.vid.changeManagement.WorkflowRequestDetail; +import org.onap.vid.model.SOWorkflowList; import org.onap.vid.mso.rest.RequestDetails; -import java.util.Map; - /** * Created by pickjonathan on 21/06/2017. */ @@ -124,6 +123,5 @@ public interface MsoInterface { <T> HttpResponse<T> post(String path, RequestDetailsWrapper<?> requestDetailsWrapper, Class<T> responseClass); - <T> HttpResponse<T> post(String path, RequestDetails requestDetails, Class<T> responseClass); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java index ee1eb0429..91b288998 100644 --- a/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java +++ b/vid-app-common/src/main/java/org/onap/vid/mso/RestMsoImplementation.java @@ -20,6 +20,8 @@ package org.onap.vid.mso; +import static org.onap.vid.logging.Headers.INVOCATION_ID; +import static org.onap.vid.logging.Headers.PARTNER_NAME; import static org.onap.vid.utils.Logging.ONAP_REQUEST_ID_HEADER_KEY; import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; import static org.onap.vid.utils.Logging.getMethodCallerName; @@ -36,15 +38,12 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; -import org.apache.http.HttpException; import org.eclipse.jetty.util.security.Password; +import org.glassfish.jersey.client.ClientProperties; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.vid.aai.ExceptionWithRequestInfo; 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.mso.rest.RestInterface; import org.onap.vid.utils.Logging; import org.onap.vid.utils.SystemPropertiesWrapper; import org.springframework.beans.factory.annotation.Autowired; @@ -53,7 +52,7 @@ import org.springframework.http.HttpMethod; /** * Created by pickjonathan on 26/06/2017. */ -public class RestMsoImplementation implements RestInterface { +public class RestMsoImplementation { /** @@ -85,7 +84,7 @@ public class RestMsoImplementation implements RestInterface { */ @Autowired - protected RestMsoImplementation(HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemProperties, Logging loggingService){ + public RestMsoImplementation(HttpsAuthClient httpsAuthClient, SystemPropertiesWrapper systemProperties, Logging loggingService){ this.httpsAuthClient=httpsAuthClient; this.systemProperties = systemProperties; this.loggingService = loggingService; @@ -108,12 +107,12 @@ public class RestMsoImplementation implements RestInterface { MultivaluedHashMap<String, Object> commonHeaders = new MultivaluedHashMap(); commonHeaders.put("Authorization", Collections.singletonList(("Basic " + authStringEnc))); - commonHeaders.put("X-ONAP-PartnerName", Collections.singletonList("VID")); + commonHeaders.put(PARTNER_NAME.getHeaderName(), Collections.singletonList(PARTNER_NAME.getHeaderValue())); String requestIdValue = Logging.extractOrGenerateRequestId(); commonHeaders.put(REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue)); commonHeaders.put(ONAP_REQUEST_ID_HEADER_KEY, Collections.singletonList(requestIdValue)); - + commonHeaders.put(INVOCATION_ID.getHeaderName(), Collections.singletonList(INVOCATION_ID.getHeaderValue())); boolean useSsl = true; if ( (mso_url != null) && ( !(mso_url.isEmpty()) ) ) { @@ -136,52 +135,6 @@ public class RestMsoImplementation implements RestInterface { return commonHeaders; } - public <T> RestObjectWithRequestInfo<T> Get(T t, String path, RestObject<T> restObject, boolean warpException) { - String methodName = "Get"; - - logger.debug(EELFLoggerDelegate.debugLogger, methodName + START_LOG); - - String url = null; - String rawData = null; - Integer status = null; - - try { - restObject.set(t); - url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; - - MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); - loggingService.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); - final Response cres = client.target(url) - .request() - .accept(APPLICATION_JSON) - .headers(commonHeaders) - .get(); - loggingService.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); - - cres.bufferEntity(); - status = cres.getStatus(); - rawData = cres.readEntity(String.class); - - restObject.setStatusCode(status); - - if (status == 200 || status == 202) { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - logger.debug(EELFLoggerDelegate.debugLogger, methodName + REST_API_SUCCESSFULL_LOG); - - } else { - throw new GenericUncheckedException(new HttpException(methodName + WITH_STATUS + status + " (200 or 202 expected), url= " + url)); - } - - logger.debug(EELFLoggerDelegate.debugLogger, methodName + " received status=" + status); - - return new RestObjectWithRequestInfo<>(HttpMethod.GET, url, restObject, status, rawData); - } catch (RuntimeException e) { - throw warpException ? new ExceptionWithRequestInfo(HttpMethod.GET, url, rawData, status, e) : e; - } - } - - @Override public <T> RestObject<T> GetForObject(String path, Class<T> clazz) { final String methodName = getMethodName(); logger.debug(EELFLoggerDelegate.debugLogger, "start {}->{}({}, {})", getMethodCallerName(), methodName, path, clazz); @@ -211,80 +164,11 @@ public class RestMsoImplementation implements RestInterface { return restObject; } - @Override - public <T> void Delete(T t, Object r, String path, RestObject<T> restObject) { - - String methodName = "Delete"; - String url=""; - Response cres; - - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG); - - try { - MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); - - url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; - loggingService.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url, r); - cres = client.target(url) - .request() - - .accept(APPLICATION_JSON) - .headers(commonHeaders) - //.entity(r) - .build("DELETE", Entity.entity(r, MediaType.APPLICATION_JSON)) - .invoke(); - loggingService.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres); - int status = cres.getStatus(); - restObject.setStatusCode (status); - - if (status == 404) { // resource not found - String msg = "Resource does not exist...: " + cres.getStatus(); - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg); - } else if (status == 200 || status == 204){ - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + "Resource " + url + " deleted"); - } else if (status == 202) { - String msg = "Delete in progress: " + status; - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg); - } - else { - String msg = "Deleting Resource failed: " + status; - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + msg); - } - - try { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - } - catch ( Exception e ) { - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG - + e.getMessage()); - throw e; - } - - } - catch (Exception e) - { - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); - throw e; - } - } - public <T> RestObject<T> PostForObject(Object requestDetails, String path, Class<T> clazz) { logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz); return restCall(HttpMethod.POST, clazz, requestDetails, path); } - public <T> RestObject<T> DeleteForObject(Object requestDetails, String path, Class<T> clazz) { - logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), requestDetails, path, clazz); - return restCall(HttpMethod.DELETE, clazz, requestDetails, path); - } - - @Override - public void Post(String t, Object r, String path, RestObject<String> restObject) { - logger.debug(EELFLoggerDelegate.debugLogger, REST_MSG_TEMPLATE, getMethodCallerName(), getMethodName(), t.getClass(), r, path); - restObject.copyFrom(restCall(HttpMethod.POST, String.class, r, path)); - } - public Invocation.Builder prepareClient(String path, String methodName) { MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); @@ -320,7 +204,9 @@ public class RestMsoImplementation implements RestInterface { final Invocation.Builder restBuilder = client.target(url) .request() .accept(APPLICATION_JSON) - .headers(commonHeaders); + .headers(commonHeaders) + .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true) + ; Invocation restInvocation = payload==null ? restBuilder.build(httpMethod.name()) : @@ -364,56 +250,4 @@ public class RestMsoImplementation implements RestInterface { return restObject; } - @Override - public <T> void Put(T t, org.onap.vid.changeManagement.RequestDetailsWrapper r, String path, RestObject<T> restObject) { - - String methodName = "Put"; - String url=""; - - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + START_LOG); - - try { - - MultivaluedHashMap<String, Object> commonHeaders = initMsoClient(); - - url = systemProperties.getProperty(MsoProperties.MSO_SERVER_URL) + path; - loggingService.logRequest(outgoingRequestsLogger, HttpMethod.PUT, url, r); - // Change the content length - final Response cres = client.target(url) - .request() - .accept(APPLICATION_JSON) - .headers(commonHeaders) - //.header("content-length", 201) - .put(Entity.entity(r, MediaType.APPLICATION_JSON)); - - loggingService.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres); - - try { - t = (T) cres.readEntity(t.getClass()); - restObject.set(t); - } - catch ( Exception e ) { - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + NO_RESPONSE_ENTITY_LOG - + e.getMessage()); - throw e; - } - - int status = cres.getStatus(); - restObject.setStatusCode (status); - - if ( status >= 200 && status <= 299 ) { - logger.info(EELFLoggerDelegate.errorLogger, "<== " + methodName + REST_API_SUCCESSFULL_LOG); - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + REST_API_SUCCESSFULL_LOG); - - } else { - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_STATUS +status+ URL_LOG +url); - } - - } catch (Exception e) - { - logger.debug(EELFLoggerDelegate.debugLogger,"<== " + methodName + WITH_URL_LOG +url+ EXCEPTION_LOG + e.toString()); - throw e; - - } - } } 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 b2ccde93b..82b2fd3d8 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 @@ -20,6 +20,7 @@ */ package org.onap.vid.mso.rest; +import static org.onap.vid.logging.Headers.PARTNER_NAME; import static org.onap.vid.utils.Logging.ONAP_REQUEST_ID_HEADER_KEY; import com.google.common.collect.ImmutableMap; @@ -38,7 +39,6 @@ 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.aai.HttpResponseWithRequestInfo; -import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.changeManagement.MsoRequestDetails; import org.onap.vid.changeManagement.RequestDetailsWrapper; import org.onap.vid.changeManagement.WorkflowRequestDetail; @@ -50,7 +50,6 @@ import org.onap.vid.mso.MsoProperties; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapperInterface; import org.onap.vid.mso.MsoUtil; -import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; import org.onap.vid.utils.Logging; import org.onap.vid.utils.SystemPropertiesWrapper; @@ -60,27 +59,28 @@ import org.springframework.http.HttpMethod; /** * 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"; - public static final String X_ONAP_PARTNER_NAME = "X-ONAP-PartnerName"; final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); private static final String START = " start"; private final SyncRestClient client; private final String baseUrl; + private final SystemPropertiesWrapper systemProperties; private final Map<String, String> commonHeaders; + /** * The logger. */ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MsoRestClientNew.class); - public MsoRestClientNew(SyncRestClient client, String baseUrl, HttpsAuthClient authClient, SystemPropertiesWrapper systemPropertiesWrapper, Logging loggingService) { - super(authClient,systemPropertiesWrapper, loggingService); + public MsoRestClientNew(SyncRestClient client, String baseUrl, SystemPropertiesWrapper systemPropertiesWrapper) { this.client = client; this.baseUrl = baseUrl; + this.systemProperties = systemPropertiesWrapper; this.commonHeaders = initCommonHeaders(); } @@ -482,14 +482,6 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf return client.post(path, getHeaders(), requestDetailsWrapper, responseClass); } - @Override - public <T> HttpResponse<T> post(String endpoint, RequestDetails requestDetails, Class<T> responseClass) { - String path = baseUrl + endpoint; - - return client.post(path, getHeaders(), requestDetails, responseClass); - } - - public HttpResponse<SOWorkflowList> getWorkflowListByModelId(String endpoint){ String path = baseUrl + endpoint; @@ -563,7 +555,7 @@ public class MsoRestClientNew extends RestMsoImplementation implements MsoInterf 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(X_ONAP_PARTNER_NAME, "VID"); + map.put(PARTNER_NAME.getHeaderName(), PARTNER_NAME.getHeaderValue()); return ImmutableMap.copyOf(map); } diff --git a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java b/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java deleted file mode 100644 index 3a0d8fd8e..000000000 --- a/vid-app-common/src/main/java/org/onap/vid/mso/rest/RestInterface.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * VID - * ================================================================================ - * Copyright (C) 2017 - 2019 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.mso.rest; - -import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.mso.RestObject; -import org.onap.vid.mso.RestObjectWithRequestInfo; - -/** - * Created by pickjonathan on 26/06/2017. - */ -public interface RestInterface { - - /** - * Gets the. - * - * @param <T> the generic type - * @param t the t - * @param path the path - * @param restObject the rest object - * @param warpException - * @throws Exception the exception - */ - <T> RestObjectWithRequestInfo<T> Get(T t, String path, RestObject<T> restObject, boolean warpException); - - /** - * Delete. - * - * @param <T> the generic type - * @param t the t - * @param r the r - * @param path the path - * @param restObject the rest object - * @throws Exception the exception - */ - <T> void Delete(T t, Object r, String path, RestObject<T> restObject); - - /** - * Post. - * - * @param t the t - * @param r the r - * @param path the path - * @param restObject the rest object - * @throws Exception the exception - */ - void Post(String t, Object r, String path, RestObject<String> restObject); - - /** - * Put. - * - * @param <T> the generic type - * @param t the t - * @param r the r - * @param path the path - * @param restObject the rest object - * @throws Exception the exception - */ - <T> void Put(T t, RequestDetailsWrapper r, String path, RestObject<T> restObject); - - <T> RestObject<T> GetForObject(String path, Class<T> clazz); - -} diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java index 43edeebe9..03a6c40f3 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerNewTest.java @@ -26,7 +26,7 @@ import javax.servlet.http.HttpServletRequest; import org.junit.Test; import org.onap.vid.mso.MsoBusinessLogicImpl; import org.onap.vid.mso.MsoInterface; -import org.onap.vid.mso.rest.MsoRestClientNew; +import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.RequestDetailsWrapper; import org.onap.vid.services.CloudOwnerServiceImpl; @@ -36,7 +36,7 @@ public class MsoControllerNewTest { private MsoController createTestSubject() { try { - return new MsoController(new MsoBusinessLogicImpl(mock(MsoInterface.class)), mock(MsoRestClientNew.class), + return new MsoController(new MsoBusinessLogicImpl(mock(MsoInterface.class)), mock(RestMsoImplementation.class), new CloudOwnerServiceImpl(null, null)); } catch (Exception e) { return null; diff --git a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java index 5aa6505d4..09f0fd357 100644 --- a/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/controller/MsoControllerTest.java @@ -50,8 +50,8 @@ import org.onap.vid.model.RequestReferencesContainer; import org.onap.vid.mso.MsoBusinessLogic; import org.onap.vid.mso.MsoResponseWrapper; import org.onap.vid.mso.MsoResponseWrapper2; +import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.mso.RestObject; -import org.onap.vid.mso.rest.MsoRestClientNew; import org.onap.vid.mso.rest.Request; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.mso.rest.RequestDetailsWrapper; @@ -73,13 +73,13 @@ public class MsoControllerTest { private MockMvc mockMvc; private MsoBusinessLogic msoBusinessLogic; private CloudOwnerService cloudService; - private MsoRestClientNew msoRestClient; + private RestMsoImplementation msoRestClient; @Before public void setUp() { msoBusinessLogic = mock(MsoBusinessLogic.class); cloudService = mock(CloudOwnerService.class); - msoRestClient = mock(MsoRestClientNew.class); + msoRestClient = mock(RestMsoImplementation.class); MsoController msoController = new MsoController(msoBusinessLogic, msoRestClient, cloudService); mockMvc = MockMvcBuilders.standaloneSetup(msoController).build(); diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java index 558dc269f..83fff4f5d 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/MsoBusinessLogicImplTest.java @@ -1255,7 +1255,7 @@ public class MsoBusinessLogicImplTest extends AbstractTestNGSpringContextTests { UUID workflow_UUID = new UUID(3,30); String path = "/instanceManagement/v1/serviceInstances/"+serviceInstanceId+"/vnfs/"+vnfInstanceId+"/workflows/"+workflow_UUID; - given(msoInterface.invokeWorkflow(eq(request), eq(path), MockitoHamcrest.argThat(allOf(hasEntry("X-RequestorID", "testRequester"),hasEntry("X-ONAP-PartnerName", "VID"))))).willReturn(okResponse); + given(msoInterface.invokeWorkflow(eq(request), eq(path), MockitoHamcrest.argThat(allOf(hasEntry("X-RequestorID", "testRequester"),hasEntry("X-ONAP-PartnerName", "VID.VID"))))).willReturn(okResponse); // when MsoResponseWrapper response = msoBusinessLogic.invokeVnfWorkflow(request, "testRequester", serviceInstanceId, vnfInstanceId, workflow_UUID); diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java index e1b78740a..792435002 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/RestMsoImplementationTest.java @@ -37,13 +37,12 @@ import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; +import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.JerseyInvocation; import org.mockito.InjectMocks; import org.mockito.Mock; import org.onap.vid.aai.util.HttpClientMode; import org.onap.vid.aai.util.HttpsAuthClient; -import org.onap.vid.changeManagement.RequestDetailsWrapper; -import org.onap.vid.exceptions.GenericUncheckedException; import org.onap.vid.mso.rest.RequestDetails; import org.onap.vid.utils.Logging; import org.onap.vid.utils.SystemPropertiesWrapper; @@ -104,46 +103,6 @@ public class RestMsoImplementationTest { assertThat(result).doesNotContainKey("notExistingKey"); } - @Test - public void shouldProperlyGetRestObjectWithRequestInfo() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - - prepareMocks(rawData, HttpStatus.ACCEPTED.value(),""); - - // when - RestObjectWithRequestInfo<HttpRequest> response = restMsoImplementation.Get(httpRequest, path, restObject,false); - - // then - assertThat(response.getRequestedUrl()).contains(path); - assertThat(response.getRawData()).isEqualTo(rawData); - assertThat(response.getHttpCode()).isEqualTo(HttpStatus.ACCEPTED.value()); - assertThat(response.getHttpMethod()).isEqualTo(HttpMethod.GET); - } - - @Test( expectedExceptions = GenericUncheckedException.class) - public void shouldThrowExceptionWhenGetRestObjectWithRequestInfoGetsWrongStatus() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - - prepareMocks("",HttpStatus.BAD_REQUEST.value(),""); - - // when - restMsoImplementation.Get(httpRequest, "", restObject,false); - } - - @Test( expectedExceptions = MsoTestException.class) - public void shouldThrowExceptionWhenGetRestObjectWithRequestInfoGetsWrongParameters() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - - prepareMocks("",HttpStatus.ACCEPTED.value(),""); - when(systemProperties.getProperty(MsoProperties.MSO_SERVER_URL)).thenReturn("SAMPLE_URL"); - when(mockClient.target("SAMPLE_URL")).thenThrow(new MsoTestException("test-target-exception")); - - // when - restMsoImplementation.Get(httpRequest, "", restObject,false); - } @Test() public void shouldProperlyGetRestObjectForObjectWithRequestInfoAndAcceptCode() { @@ -171,79 +130,6 @@ public class RestMsoImplementationTest { assertThat(response.getRaw()).isEqualTo(rawData); } - @Test() - public void shouldProperlyDeleteRestObjectWithStatusHttpAccepted() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - - prepareMocks(rawData,HttpStatus.ACCEPTED.value(),"DELETE"); - - // when - restMsoImplementation.Delete(httpRequest, "testObject", path, restObject); - - // then - assertThat(restObject.getStatusCode()).isEqualTo(HttpStatus.ACCEPTED.value()); - } - - @Test() - public void shouldProperlyDeleteRestObjectWithStatusOK() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - - prepareMocks(rawData,HttpStatus.OK.value(),"DELETE"); - - // when - restMsoImplementation.Delete(httpRequest, "testObject", path, restObject); - - // then - assertThat(restObject.getStatusCode()).isEqualTo(HttpStatus.OK.value()); - } - - @Test() - public void shouldProperlyReturnFromDeleteWithStatusBadRequest() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - - prepareMocks(rawData,HttpStatus.BAD_REQUEST.value(),"DELETE"); - - // when - restMsoImplementation.Delete(httpRequest, "testObject", path, restObject); - - // then - assertThat(restObject.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value()); - } - - @Test() - public void shouldProperlyReturnFromDeleteWithStatusOtherThenAbove() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - prepareMocks(rawData,HttpStatus.NOT_EXTENDED.value(),"DELETE"); - - // when - restMsoImplementation.Delete(httpRequest, "testObject", path, restObject); - - // then - assertThat(restObject.getStatusCode()).isEqualTo(HttpStatus.NOT_EXTENDED.value()); - } - - @Test( expectedExceptions = MsoTestException.class) - public void shouldThrowExceptionWhenCallsDeleteWithWrongParameters() { - // given - when(mockClient.target(any(String.class))).thenThrow(new MsoTestException("testDeleteException")); - - // when - restMsoImplementation.Delete(httpRequest, "testObject", "", null); - } - - @Test( expectedExceptions = NullPointerException.class) - public void shouldThrowExceptionWhenCallsDeleteWithWrongObjectType() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - prepareMocks(rawData,HttpStatus.ACCEPTED.value(),"DELETE"); - - // when - restMsoImplementation.Delete(null, "testObject", path, restObject); - } @Test public void shouldProperlyPostForObject() { @@ -264,43 +150,6 @@ public class RestMsoImplementationTest { } @Test - public void shouldProperlyDeleteForObject() { - // given - RequestDetails requestDetails = new RequestDetails(); - - RestObject<HttpRequest> expectedResponse = new RestObject<>(); - expectedResponse.setStatusCode(HttpStatus.ACCEPTED.value()); - expectedResponse.setRaw(rawData); - - prepareMocks(rawData,HttpStatus.ACCEPTED.value(),"DELETE"); - - // when - RestObject<HttpRequest> response = restMsoImplementation.DeleteForObject(requestDetails, path, HttpRequest.class); - - // then - assertThat(response).isEqualToComparingFieldByField(expectedResponse); - } - - @Test - public void shouldProperlyPost() { - // given - RequestDetails requestDetails = new RequestDetails(); - RestObject<String> response = new RestObject<>(); - - RestObject<String> expectedResponse = new RestObject<>(); - expectedResponse.setStatusCode(HttpStatus.ACCEPTED.value()); - expectedResponse.setRaw(rawData); - - prepareMocks(rawData,HttpStatus.ACCEPTED.value(),"POST"); - - // when - restMsoImplementation.Post(rawData,requestDetails, path, response); - - // then - assertThat(response).isEqualToComparingFieldByField(expectedResponse); - } - - @Test public void shouldProperlyPrepareClient() { // given String method = "POST"; @@ -339,70 +188,6 @@ public class RestMsoImplementationTest { restMsoImplementation.restCall(HttpMethod.GET, String.class, null, "", Optional.empty()); } - @Test - public void shouldProperlyPutRestObjectWithProperParametersAndStatusAccepted() { - // given - String method = "PUT"; - prepareMocks(rawData,HttpStatus.ACCEPTED.value(),method); - - org.onap.vid.changeManagement.RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); - RestObject<String> response = new RestObject<>(); - - RestObject<String> expectedResponse = new RestObject<>(); - expectedResponse.setStatusCode(HttpStatus.ACCEPTED.value()); - expectedResponse.set(rawData); - - // when - restMsoImplementation.Put("testPutBody", requestDetailsWrapper , path, response); - - // then - assertThat(response).isEqualToComparingFieldByField(expectedResponse); - } - - @Test - public void shouldProperlyPutRestObjectWithProperParametersAndStatusMultipleChoices() { - // given - String method = "PUT"; - prepareMocks(rawData,HttpStatus.MULTIPLE_CHOICES.value(),method); - - org.onap.vid.changeManagement.RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); - RestObject<String> response = new RestObject<>(); - - RestObject<String> expectedResponse = new RestObject<>(); - expectedResponse.setStatusCode(HttpStatus.MULTIPLE_CHOICES.value()); - expectedResponse.set(rawData); - - // when - restMsoImplementation.Put("testPutBody", requestDetailsWrapper , path, response); - - // then - assertThat(response).isEqualToComparingFieldByField(expectedResponse); - } - - @Test( expectedExceptions = MsoTestException.class) - public void shouldThrowExceptionWhenCallsPutWithWrongParameters() { - // given - when(mockClient.target(any(String.class))).thenThrow(new MsoTestException("testDeleteException")); - org.onap.vid.changeManagement.RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); - - // when - restMsoImplementation.Put(null, requestDetailsWrapper, "", null); - } - - @Test( expectedExceptions = NullPointerException.class) - public void shouldThrowExceptionWhenCallsPutWithWrongObjectType() { - // given - RestObject<HttpRequest> restObject = new RestObject<>(); - org.onap.vid.changeManagement.RequestDetailsWrapper requestDetailsWrapper = new RequestDetailsWrapper(); - - prepareMocks(rawData,HttpStatus.ACCEPTED.value(),"DELETE"); - - // when - restMsoImplementation.Put(null, requestDetailsWrapper, path, restObject); - } - - - private void prepareMocks(String rawData,int status,String httpMethod) { when(mockClient.target(any(String.class))).thenReturn(webTarget); @@ -411,6 +196,7 @@ public class RestMsoImplementationTest { when(builder.accept(any(String.class))).thenReturn(builder); when(builder.headers(any(MultivaluedMap.class))).thenReturn(builder); + when(builder.property(eq(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION), eq(true))).thenReturn(builder); when(builder.get()).thenReturn(response); when(builder.build( eq(httpMethod), any(Entity.class))).thenReturn(jerseyInvocation); 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 457007500..aaaa324e8 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 @@ -410,7 +410,7 @@ public class MsoRestClientNewTest { String sourceId = ""; String endpoint = ""; final SyncRestClient client = mock(SyncRestClient.class); - MsoRestClientNew testSubject = new MsoRestClientNew(client, "", null, new SystemPropertiesWrapper(), mock(Logging.class)); + MsoRestClientNew testSubject = new MsoRestClientNew(client, "", new SystemPropertiesWrapper()); // setup final HttpResponse<String> response = mock(HttpResponse.class); @@ -474,10 +474,10 @@ public class MsoRestClientNewTest { private MsoRestClientNew msoRestClient() { return new MsoRestClientNew(new SyncRestClient(JOSHWORKS_JACKSON_OBJECT_MAPPER, mock(Logging.class)), - baseUrl(), null, new SystemPropertiesWrapper(), mock(Logging.class)); + baseUrl(), new SystemPropertiesWrapper()); } private MsoRestClientNew createTestSubject() { - return new MsoRestClientNew(null, "", null, new SystemPropertiesWrapper(), mock(Logging.class)); + return new MsoRestClientNew(null, "", new SystemPropertiesWrapper()); } } 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 5486becad..dd05a625e 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 @@ -99,7 +99,7 @@ public class MsoRestClientTest { initMocks(this); when(systemProperties.getProperty(MsoProperties.MSO_PASSWORD)).thenReturn("OBF:1ghz1kfx1j1w1m7w1i271e8q1eas1hzj1m4i1iyy1kch1gdz"); when(systemProperties.getProperty("app_display_name")).thenReturn("vid"); - restClient = new MsoRestClientNew(client,baseUrl,null,systemProperties,loggingService); + restClient = new MsoRestClientNew(client, baseUrl, systemProperties); } @Test @@ -832,7 +832,7 @@ public class MsoRestClientTest { Map<String,String> extraHeaders = new HashMap<>(); extraHeaders.put("X-ONAP-RequestID",requestId.toString()); - extraHeaders.put("X-ONAP-PartnerName","VID"); + extraHeaders.put("X-ONAP-PartnerName","VID.VID"); extraHeaders.put("X-RequestorID","testRequester"); // when 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 index ac82a6e53..123737f4f 100644 --- 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 @@ -32,7 +32,7 @@ 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 static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals; -import static org.onap.vid.mso.rest.MsoRestClientNew.X_ONAP_PARTNER_NAME; +import static org.onap.vid.logging.Headers.PARTNER_NAME; import static org.onap.vid.utils.Logging.ONAP_REQUEST_ID_HEADER_KEY; import com.fasterxml.jackson.databind.ObjectMapper; @@ -235,7 +235,7 @@ class MsoRestClientTestUtil implements AutoCloseable { withHeader(HttpHeaders.ACCEPT), withHeader(HttpHeaders.CONTENT_TYPE), withHeader(MsoRestClientNew.X_FROM_APP_ID), - withHeader(X_ONAP_PARTNER_NAME, "VID"), + withHeader(PARTNER_NAME.getHeaderName(), "VID.VID"), withHeader(SystemProperties.ECOMP_REQUEST_ID), withHeader(ONAP_REQUEST_ID_HEADER_KEY) ); diff --git a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java index ac05ea706..414bcf4ac 100644 --- a/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java +++ b/vid-app-common/src/test/java/org/onap/vid/mso/rest/OutgoingRequestHeadersTest.java @@ -20,16 +20,22 @@ package org.onap.vid.mso.rest; +import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasToString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.matchesPattern; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableList; +import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Consumer; @@ -48,12 +54,18 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.vid.aai.util.AAIRestInterface; +import org.onap.vid.aai.util.HttpsAuthClient; import org.onap.vid.aai.util.ServletRequestHelper; import org.onap.vid.aai.util.SystemPropertyHelper; import org.onap.vid.controller.filter.PromiseRequestIdFilter; +import org.onap.vid.logging.Headers; +import org.onap.vid.mso.MsoProperties; +import org.onap.vid.mso.RestMsoImplementation; import org.onap.vid.testUtils.TestUtils; import org.onap.vid.utils.Logging; +import org.onap.vid.utils.SystemPropertiesWrapper; import org.onap.vid.utils.Unchecked; +import org.springframework.http.HttpMethod; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -67,13 +79,19 @@ public class OutgoingRequestHeadersTest { private static final PromiseRequestIdFilter promiseRequestIdFilter = new PromiseRequestIdFilter(); -// @InjectMocks -// private RestMsoImplementation restMsoImplementation; + @InjectMocks + private RestMsoImplementation restMsoImplementation; @Mock private SystemPropertyHelper systemPropertyHelper; @Mock + private SystemPropertiesWrapper systemPropertiesWrapper; + + @Mock + private HttpsAuthClient httpsAuthClient; + + @Mock private ServletRequestHelper servletRequestHelper; @Mock @@ -89,6 +107,7 @@ public class OutgoingRequestHeadersTest { public void initMocks() { MockitoAnnotations.initMocks(this); when(servletRequestHelper.extractOrGenerateRequestId()).thenAnswer(invocation -> UUID.randomUUID().toString()); + when(systemPropertiesWrapper.getProperty(MsoProperties.MSO_PASSWORD)).thenReturn("OBF:1vub1ua51uh81ugi1u9d1vuz"); } @BeforeMethod @@ -101,42 +120,54 @@ public class OutgoingRequestHeadersTest { (HttpServletRequest) promiseRequestIdFilter.wrapIfNeeded(new MockHttpServletRequest()))); } -// @DataProvider -// public Object[][] msoMethods() { -// return Stream.<ThrowingConsumer<RestMsoImplementation>>of( -// -// client -> client.Get(new Object(), "/any path", new RestObject<>(), false), -// client -> client.GetForObject("/any path", Object.class), -// client -> client.Post("", "some payload", "/any path", new RestObject<>()), -// client -> client.PostForObject("some payload", "/any path", Object.class), -// client -> client.Put(Object.class, new RequestDetailsWrapper(), "/any path", new RestObject<>()) -// -// ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); -// } -// -// @Test(dataProvider = "msoMethods") -// public void mso(Consumer<RestMsoImplementation> f) throws Exception { -// final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); -// -// f.accept(restMsoImplementation); -// -// Invocation.Builder fakeBuilder = mocks.getFakeBuilder(); -// Object requestIdValue = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder); -// assertEquals(requestIdValue, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID")); -// -// assertThat((String) captureHeaderKeyAndReturnItsValue(fakeBuilder, "Authorization"), startsWith("Basic ")); -// assertThat(captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-PartnerName"), equalTo("VID")); -// } -// -// @Test -// public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception { -// -// final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); -// String randomUserName = randomAlphabetic(10); -// -// restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName)); -// assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID")); -// } + @DataProvider + public Object[][] msoMethods() { + return Stream.<ThrowingConsumer<RestMsoImplementation>>of( + client -> client.GetForObject("/any path", Object.class), + client -> client.restCall(HttpMethod.DELETE, Object.class, "some payload", "/any path", Optional.of("userId")), + client -> client.PostForObject("some payload", "/any path", Object.class) + ).map(l -> ImmutableList.of(l).toArray()).collect(Collectors.toList()).toArray(new Object[][]{}); + } + + @Test(dataProvider = "msoMethods") + public void mso(Consumer<RestMsoImplementation> f) throws Exception { + final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); + + f.accept(restMsoImplementation); + + Invocation.Builder fakeBuilder = mocks.getFakeBuilder(); + Object requestIdValue = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder); + assertEquals(requestIdValue, captureHeaderKeyAndReturnItsValue(fakeBuilder, "X-ONAP-RequestID")); + Object invocationId1 = assertRequestHeaderIsUUID(fakeBuilder, "X-InvocationID"); + assertThat((String) captureHeaderKeyAndReturnItsValue(fakeBuilder, "Authorization"), startsWith("Basic ")); + verifyXOnapPartnerNameHeaderWasAdded(fakeBuilder); + + //validate requestId is same in next call but invocationId is different + + //given + final TestUtils.JavaxRsClientMocks mocks2 = setAndGetMocksInsideRestImpl(restMsoImplementation); + + //when + f.accept(restMsoImplementation); + Invocation.Builder fakeBuilder2 = mocks2.getFakeBuilder(); + + //then + Object requestIdValue2 = verifyXEcompRequestIdHeaderWasAdded(fakeBuilder2); + assertEquals(requestIdValue, requestIdValue2); + + Object invocationId2 = assertRequestHeaderIsUUID(fakeBuilder2, "X-InvocationID"); + assertNotEquals(invocationId1, invocationId2); + } + + @Test + public void whenProvideMsoRestCallUserId_builderHasXRequestorIDHeader() throws Exception { + + final TestUtils.JavaxRsClientMocks mocks = setAndGetMocksInsideRestImpl(restMsoImplementation); + String randomUserName = randomAlphabetic(10); + + restMsoImplementation.restCall(HttpMethod.DELETE, String.class, null, "abc", Optional.of(randomUserName)); + assertEquals(randomUserName, captureHeaderKeyAndReturnItsValue(mocks.getFakeBuilder(), "X-RequestorID")); + } @DataProvider public Object[][] aaiMethods() { @@ -157,6 +188,7 @@ public class OutgoingRequestHeadersTest { f.accept(aaiRestInterface); verifyXEcompRequestIdHeaderWasAdded(mocks.getFakeBuilder()); + verifyXOnapPartnerNameHeaderWasAdded(mocks.getFakeBuilder()); } // @Test(dataProvider = "schedulerMethods") @@ -171,12 +203,22 @@ public class OutgoingRequestHeadersTest { private Object verifyXEcompRequestIdHeaderWasAdded(Invocation.Builder fakeBuilder) { final String requestIdHeader = "x-ecomp-requestid"; - final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; - Object requestId = captureHeaderKeyAndReturnItsValue(fakeBuilder, requestIdHeader); + return assertRequestHeaderIsUUID(fakeBuilder, requestIdHeader); + } - assertThat("header '" + requestIdHeader + "' should be a uuid", requestId, + private Object assertRequestHeaderIsUUID(Invocation.Builder fakeBuilder, String headerName) { + Object headerValue = captureHeaderKeyAndReturnItsValue(fakeBuilder, headerName); + final String uuidRegex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; + assertThat("header '" + headerName + "' should be a uuid", headerValue, allOf(instanceOf(String.class), hasToString(matchesPattern(uuidRegex)))); - return requestId; + return headerValue; + } + + private void verifyXOnapPartnerNameHeaderWasAdded(Invocation.Builder fakeBuilder) { + assertThat( + captureHeaderKeyAndReturnItsValue(fakeBuilder, Headers.PARTNER_NAME.getHeaderName()), + is("VID.VID") + ); } private Object captureHeaderKeyAndReturnItsValue(Invocation.Builder fakeBuilder, String headerName) { @@ -187,22 +229,26 @@ public class OutgoingRequestHeadersTest { // The 'verify()' will capture the request id. If no match -- AssertionError will // catch for a second chance -- another 'verify()'. try { - ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class); - Mockito.verify(fakeBuilder) + try { + ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class); + Mockito.verify(fakeBuilder) .header( - Matchers.argThat(s -> equalsIgnoreCase(s, headerName)), - argumentCaptor.capture() + Matchers.argThat(s -> equalsIgnoreCase(s, headerName)), + argumentCaptor.capture() ); - requestId = argumentCaptor.getValue(); + requestId = argumentCaptor.getValue(); - } catch (AssertionError e) { - Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture()); + } catch (AssertionError e) { + Mockito.verify(fakeBuilder).headers(multivaluedMapArgumentCaptor.capture()); - final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue(); - final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName); + final MultivaluedMap<String, Object> headersMap = multivaluedMapArgumentCaptor.getValue(); + final String thisRequestIdHeader = getFromSetCaseInsensitive(headersMap.keySet(), headerName); - assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader)); - requestId = headersMap.getFirst(thisRequestIdHeader); + assertThat(headersMap.keySet(), hasItem(thisRequestIdHeader)); + requestId = headersMap.getFirst(thisRequestIdHeader); + } + } catch (AssertionError e) { + throw new AssertionError("header not captured: " + headerName, e); } return requestId; } |