diff options
author | 2018-07-10 14:20:54 +0300 | |
---|---|---|
committer | 2018-07-10 14:20:54 +0300 | |
commit | c72d565bb58226b20625b2bce5f0019046bee649 (patch) | |
tree | 8658e49595705b02e47ddc14afa20d6bb7123547 /vid-app-common/src/main/java/org/onap/vid/aai/util | |
parent | ef8a6b47847012fd59ea20da21d8d3d7c4a301ed (diff) |
Merge 1806 code of vid-common
Change-Id: I75d52abed4a24dfe3827d79edc4a2938726aa87a
Issue-ID: VID-208
Signed-off-by: Sonsino, Ofir (os0695) <os0695@intl.att.com>
Diffstat (limited to 'vid-app-common/src/main/java/org/onap/vid/aai/util')
7 files changed, 320 insertions, 259 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 226850d2..ac38b505 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 @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -20,28 +20,31 @@ package org.onap.vid.aai.util; +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.eclipse.jetty.util.security.Password; +import org.onap.vid.aai.ExceptionWithRequestInfo; +import org.onap.vid.aai.ResponseWithRequestInfo; +import org.onap.vid.utils.Logging; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpMethod; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; -import java.security.KeyManagementException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Date; import java.util.UUID; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; - -import com.att.eelf.configuration.EELFLogger; -import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.onap.portalsdk.core.util.SystemProperties; -import org.eclipse.jetty.util.security.Password; -import org.onap.vid.utils.Logging; -import org.springframework.http.HttpMethod; -import static org.onap.vid.utils.Logging.getHttpServletRequest; -import static org.onap.vid.utils.Logging.requestIdHeaderKey; +import static org.apache.commons.lang3.ObjectUtils.defaultIfNull; +import static org.onap.vid.utils.Logging.REQUEST_ID_HEADER_KEY; /** @@ -49,43 +52,32 @@ import static org.onap.vid.utils.Logging.requestIdHeaderKey; */ public class AAIRestInterface { + public static final String WITH_STATUS = " with status="; /** The logger. */ - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class); + protected EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AAIRestInterface.class); - final private EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai"); + protected final EELFLogger outgoingRequestsLogger = Logging.getRequestsLogger("aai"); /** The Constant dateFormat. */ - final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); + protected final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS"); /** The client. */ - private static Client client = null; + private Client client = null; /** The rest srvr base URL. */ private String restSrvrBaseURL; - /** The certificate path. */ - public String certificatePath = ""; + @Autowired + protected HttpsAuthClient httpsAuthClientFactory; private String START_STRING = " start"; - - private String TRANSACTION_ID_HEADER = "X-TransactionId"; - private String FROM_APP_ID_HEADER = "X-FromAppId"; + protected String TRANSACTION_ID_HEADER = "X-TransactionId"; + protected String FROM_APP_ID_HEADER = "X-FromAppId"; private String SUCCESSFUL_API_MESSAGE=" REST api POST was successful!"; - private String URL_DECLERATION = ", url="; - - - - + protected String URL_DECLARATION = ", url="; - - /** - * Instantiates a new AAI rest interface. - * - * @param certPath the cert path - */ - public AAIRestInterface(String certPath) - { - certificatePath = certPath; + public AAIRestInterface(HttpsAuthClient httpsAuthClientFactory) { + this.httpsAuthClientFactory = httpsAuthClientFactory; } /** @@ -99,27 +91,28 @@ public class AAIRestInterface { return URLEncoder.encode(nodeKey, "UTF-8").replaceAll("\\+", "%20"); } - /** - * Inits the rest client. - */ - private void initRestClient() - { - String methodName = "initRestClient"; + private void initRestClient() { + initRestClient(false); + } + + private void initRestClient(boolean propagateExceptions) + { if (client == null) { try { - client = HttpsAuthClient.getClient(certificatePath); - } - catch (KeyManagementException e){ - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== KeyManagementException in " + methodName + e.toString()); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== KeyManagementException in " + methodName + e.toString()); + client = httpsAuthClientFactory.getClient(HttpClientMode.WITHOUT_KEYSTORE); } catch (Exception e) { logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB in initRestClient" + e.toString()); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== Exception in REST call to DB : " + e.toString()); + if (propagateExceptions) { + ExceptionUtils.rethrow(e); + } } } } + + /** * Sets the rest srvr base URL. * @@ -155,70 +148,82 @@ public class AAIRestInterface { * @param requestUri the request uri * @param xml the xml * @return the string - * @throws UnsupportedEncodingException */ - public Response RestGet(String fromAppId, String transId, String requestUri, boolean xml) throws UnsupportedEncodingException { - String methodName = "RestGet"; - - String responseType = MediaType.APPLICATION_JSON; - if (xml) - responseType = MediaType.APPLICATION_XML; - initRestClient(); + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml) { + return RestGet(fromAppId, transId, requestUri, xml, false); + } - String clientCert = SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT); + public ResponseWithRequestInfo RestGet(String fromAppId, String transId, String requestUri, boolean xml, boolean propagateExceptions) { + String url = null; + try { + String methodName = "RestGet"; + url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + requestUri; - boolean useClientCert = false; - if (clientCert != null && - SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT).equalsIgnoreCase("true")) { - useClientCert = true; - } - String url = ""; - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); + String responseType = MediaType.APPLICATION_JSON; + if (xml) + responseType = MediaType.APPLICATION_XML; - url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + requestUri; + initRestClient(propagateExceptions); + String clientCert = SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT); - logger.debug(dateFormat.format(new Date()) + "<== " + url + " for the get REST API"); - Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); + boolean useClientCert = false; + if (clientCert != null && + SystemProperties.getProperty(AAIProperties.AAI_USE_CLIENT_CERT).equalsIgnoreCase("true")) { + useClientCert = true; + } - final Response cres; - if (useClientCert == true) { - cres = client.target(url) - .request() - .accept(responseType) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId) - .header("Content-Type", MediaType.APPLICATION_JSON) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(); - } else { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + url + " for the get REST API"); + + Logging.logRequest(outgoingRequestsLogger, HttpMethod.GET, url); + + final Response cres; + if (useClientCert == true) { + cres = client.target(url) + .request() + .accept(responseType) + .header(TRANSACTION_ID_HEADER, transId) + .header(FROM_APP_ID_HEADER, fromAppId) + .header("Content-Type", MediaType.APPLICATION_JSON) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) + .get(); + } else { - String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME); - String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X)); - String encodeThis = vidUsername + ":" + vidPassword; + String vidUsername = SystemProperties.getProperty(AAIProperties.AAI_VID_USERNAME); + String vidPassword = Password.deobfuscate(SystemProperties.getProperty(AAIProperties.AAI_VID_PASSWD_X)); + String encodeThis = vidUsername + ":" + vidPassword; + + cres = client.target(url) + .request() + .accept(responseType) + .header(TRANSACTION_ID_HEADER, transId) + .header(FROM_APP_ID_HEADER, fromAppId) + .header("Content-Type", "application/json") + .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) + .get(); + } + Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); - cres = client.target(url) - .request() - .accept(responseType) - .header(TRANSACTION_ID_HEADER, transId) - .header(FROM_APP_ID_HEADER, fromAppId) - .header("Content-Type", "application/json") - .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - .get(); - } - Logging.logResponse(outgoingRequestsLogger, HttpMethod.GET, url, cres); -// String r = cres.readEntity(String.class); - if (cres.getStatus() == 200) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); - } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+URL_DECLERATION+url); + if (cres.getStatus() == 200) { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + SUCCESSFUL_API_MESSAGE); + } else { + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS + cres.getStatus() + URL_DECLARATION + url); + } + return new ResponseWithRequestInfo(cres, url, HttpMethod.GET); + } catch (Exception e) { + // no need to ask if "propagateExceptions" because any exception + // at this point should have already obey to the + // "propagateExceptions" flag + throw new ExceptionWithRequestInfo(HttpMethod.GET, defaultIfNull(url, requestUri), e); } - return cres; -// logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" resp=" + r ); -// return r; + } + + protected String extractOrGenerateRequestId() { + return Logging.extractOrGenerateRequestId(); } @@ -237,7 +242,6 @@ public class AAIRestInterface { logger.debug(dateFormat.format(new Date()) + "<== " + methodName + START_STRING); initRestClient(); - String request = "{}"; url = SystemProperties.getProperty(AAIProperties.AAI_SERVER_URL) + path; Logging.logRequest(outgoingRequestsLogger, HttpMethod.DELETE, url); final Response cres = client.target(url) @@ -245,8 +249,7 @@ public class AAIRestInterface { .accept(MediaType.APPLICATION_JSON) .header(TRANSACTION_ID_HEADER, transId) .header(FROM_APP_ID_HEADER, sourceID) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) - //.entity(request) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) .delete(); Logging.logResponse(outgoingRequestsLogger, HttpMethod.DELETE, url, cres); if (cres.getStatus() == 404) { // resource not found @@ -271,16 +274,15 @@ public class AAIRestInterface { * Rest put. * * @param fromAppId the from app id - * @param transId the trans id * @param path the path * @param payload the payload * @param xml the xml * @return the string */ - public Response RestPut(String fromAppId, String transId, String path, String payload, boolean xml) { + public Response RestPut(String fromAppId, String path, String payload, boolean xml) { String methodName = "RestPut"; String url=""; - transId = UUID.randomUUID().toString(); + String transId = UUID.randomUUID().toString(); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); try { @@ -303,19 +305,19 @@ public class AAIRestInterface { .header(TRANSACTION_ID_HEADER, transId) .header(FROM_APP_ID_HEADER, fromAppId) .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) .put(Entity.entity(payload, MediaType.APPLICATION_JSON)); Logging.logResponse(outgoingRequestsLogger, HttpMethod.PUT, url, cres); if (cres.getStatus() == 200 && cres.getStatus() <= 299) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName +" with status="+cres.getStatus()+URL_DECLERATION+url); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +cres.getStatus()+ URL_DECLARATION +url); } return cres; } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION+url+ ", Exception: " + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION +url+ ", Exception: " + e.toString()); } return null; } @@ -326,16 +328,15 @@ public class AAIRestInterface { * Rest post. * * @param fromAppId the from app id - * @param transId the trans id * @param path the path * @param payload the payload * @param xml the xml * @return the string */ - public Response RestPost(String fromAppId, String transId, String path, String payload, boolean xml) { + public Response RestPost(String fromAppId, String path, String payload, boolean xml) { String methodName = "RestPost"; String url=""; - transId = UUID.randomUUID().toString(); + String transId = UUID.randomUUID().toString(); logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + START_STRING); try { @@ -358,19 +359,19 @@ public class AAIRestInterface { .header(TRANSACTION_ID_HEADER, transId) .header(FROM_APP_ID_HEADER, fromAppId) .header("Authorization", "Basic " + Base64.getEncoder().encodeToString(encodeThis.getBytes("utf-8"))) - .header(requestIdHeaderKey, getHttpServletRequest().getHeader(requestIdHeaderKey)) + .header(REQUEST_ID_HEADER_KEY, extractOrGenerateRequestId()) .post(Entity.entity(payload, MediaType.APPLICATION_JSON)); Logging.logResponse(outgoingRequestsLogger, HttpMethod.POST, url, cres); if (cres.getStatus() == 200 && cres.getStatus() <= 299) { - logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION); + logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION); } else { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " with status="+cres.getStatus()+URL_DECLERATION+url); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + WITH_STATUS +cres.getStatus()+ URL_DECLARATION +url); } return cres; } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLERATION+url+ ", Exception: " + e.toString()); + logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + URL_DECLARATION +url+ ", Exception: " + e.toString()); } return null; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java index 996341a9..375f0b2d 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/CustomJacksonJaxBJsonProvider.java @@ -21,8 +21,6 @@ package org.onap.vid.aai.util; -import javax.ws.rs.ext.Provider; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; @@ -30,6 +28,8 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule; +import javax.ws.rs.ext.Provider; + /** * The Class CustomJacksonJaxBJsonProvider. */ diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpClientMode.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpClientMode.java new file mode 100644 index 00000000..e1992826 --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpClientMode.java @@ -0,0 +1,9 @@ +package org.onap.vid.aai.util; + +public enum HttpClientMode { + + WITH_KEYSTORE, + WITHOUT_KEYSTORE(), + UNSECURE, + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java index 3bc8e4a3..f1eafe42 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsAuthClient.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,120 +21,151 @@ package org.onap.vid.aai.util; -import java.io.FileInputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; - import org.eclipse.jetty.util.security.Password; import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.HttpUrlConnectorProvider; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; + +import javax.net.ssl.*; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + /** * The Class HttpsAuthClient. */ -public class HttpsAuthClient{ - /** The logger. */ - static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsAuthClient.class); - - /** - * Gets the client. - * - * @param certFilePath the cert file path - * @return the client - * @throws KeyManagementException the key management exception - */ - public static Client getClient(String certFilePath) throws KeyManagementException { - - ClientConfig config = new ClientConfig(); - //config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - //config.getClasses().add(org.onap.aai.util.CustomJacksonJaxBJsonProvider.class); - - try { - - config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, Boolean.TRUE ); - - config.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround()); - String truststore_path = certFilePath + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_FILENAME); - String truststore_password = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_PASSWD_X); - String decrypted_truststore_password = Password.deobfuscate(truststore_password); - - boolean useClientCert = false; - - String keystore_path = certFilePath + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_FILENAME); - String keystore_password = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_PASSWD_X); - String decrypted_keystore_password = Password.deobfuscate(keystore_password); - - String clientCert = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_USE_CLIENT_CERT); - - if (clientCert != null && - SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_USE_CLIENT_CERT).equalsIgnoreCase("true")) { - useClientCert = true; - } - - System.setProperty("javax.net.ssl.trustStore", truststore_path); - System.setProperty("javax.net.ssl.trustStorePassword", decrypted_truststore_password); - HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ - public boolean verify(String string,SSLSession ssls) { - return true; - } - }); - - final SSLContext ctx = SSLContext.getInstance("TLS"); - - KeyManagerFactory kmf = null; - if (useClientCert) { - - try { - kmf = KeyManagerFactory.getInstance("SunX509"); - FileInputStream fin = new FileInputStream(keystore_path); - KeyStore ks = KeyStore.getInstance("PKCS12"); - char[] pwd = decrypted_keystore_password.toCharArray(); - ks.load(fin, pwd); - kmf.init(ks, pwd); - } catch (Exception e) { - //System.out.println("Error setting up kmf: exiting"); - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up kmf: exiting"); - e.printStackTrace(); - return null; - } - ctx.init(kmf.getKeyManagers(), null, null); - - return ClientBuilder.newBuilder() - .sslContext(ctx) - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return true; - } - }).withConfig(config) - .build() - .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); - } else { - return ClientBuilder.newBuilder() - .hostnameVerifier(new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return true; - } - }).withConfig(config) - .build() - .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); - } - } catch (Exception e) { - logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config: exiting"); - //System.out.println("Error setting up config: exiting"); - e.printStackTrace(); - System.exit(1); - return null; - } - } -} +public class HttpsAuthClient { + + + public HttpsAuthClient(String certFilePath) { + this.certFilePath = certFilePath; + } + + private final String certFilePath; + + /** The logger. */ + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsAuthClient.class); + + /** + * Gets the client. + * + * @return the client + * @throws KeyManagementException the key management exception + */ + public Client getClient(HttpClientMode mode) throws GeneralSecurityException, IOException { + ClientConfig config = new ClientConfig(); + SSLContext ctx; + + try { + String truststorePath = getCertificatesPath() + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_FILENAME); + String truststorePassword = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_TRUSTSTORE_PASSWD_X); + String decryptedTruststorePassword = Password.deobfuscate(truststorePassword); + + System.setProperty("javax.net.ssl.trustStore", truststorePath); + System.setProperty("javax.net.ssl.trustStorePassword", decryptedTruststorePassword); + + HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { + public boolean verify(String string, SSLSession ssls) { + return true; + } + }); + ctx = SSLContext.getInstance("TLSv1.2"); + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = getTrustManager(mode); + + switch (mode) { + case WITH_KEYSTORE: + String aaiKeystorePath = getCertificatesPath() + org.onap.vid.aai.util.AAIProperties.FILESEPARTOR + SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_FILENAME); + String aaiKeystorePassword = SystemProperties.getProperty(org.onap.vid.aai.util.AAIProperties.AAI_KEYSTORE_PASSWD_X); + config.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, Boolean.TRUE); + config.connectorProvider(new HttpUrlConnectorProvider().useSetMethodWorkaround()); + KeyManagerFactory kmf = getKeyManagerFactory(aaiKeystorePath, aaiKeystorePassword); + keyManagers = kmf.getKeyManagers(); + break; + + case WITHOUT_KEYSTORE: + config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + break; + + default: + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config. HttpClientMode is " + mode); + } + + ctx.init(keyManagers, trustManagers, null); + return ClientBuilder.newBuilder() + .sslContext(ctx) + .hostnameVerifier(new HostnameVerifier() { + @Override + public boolean verify(String s, SSLSession sslSession) { + return true; + } + }).withConfig(config) + .build() + .register(org.onap.vid.aai.util.CustomJacksonJaxBJsonProvider.class); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up config", e); + throw e; + } + + } + + /** + * @param aaiKeystorePath + * @param aaiKeystorePassword - in OBF format + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws IOException + * @throws CertificateException + * @throws UnrecoverableKeyException + */ + private KeyManagerFactory getKeyManagerFactory(String aaiKeystorePath, String aaiKeystorePassword) throws IOException, GeneralSecurityException { + String aaiDecryptedKeystorePassword = Password.deobfuscate(aaiKeystorePassword); + KeyManagerFactory kmf = null; + try (FileInputStream fin = new FileInputStream(aaiKeystorePath)) { + kmf = KeyManagerFactory.getInstance("SunX509"); + KeyStore ks = KeyStore.getInstance("PKCS12"); + char[] pwd = aaiDecryptedKeystorePassword.toCharArray(); + ks.load(fin, pwd); + kmf.init(ks, pwd); + } catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up kmf"); + logger.error(EELFLoggerDelegate.errorLogger, "Error setting up kmf (keystore path: {}, obfuascated keystore password: {})", aaiKeystorePath, aaiKeystorePassword, e); + throw e; + } + return kmf; + } + + private String getCertificatesPath() { + return certFilePath; + } + + private TrustManager[] getTrustManager(HttpClientMode httpClientMode) { + //Creating a trustManager that will accept all certificates. + //TODO - remove this one the POMBA certificate is added to the tomcat_keystore file + TrustManager[] trustAllCerts = null; + if (httpClientMode == HttpClientMode.UNSECURE) { + + trustAllCerts = new TrustManager[]{new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + }}; + } + return trustAllCerts; + } + + +} diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java index 10022219..d1f1cfc8 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/HttpsComponentsClient.java @@ -20,25 +20,29 @@ package org.onap.vid.aai.util; -import java.io.FileInputStream; -import java.security.KeyManagementException; -import java.security.KeyStore; - -import javax.net.ssl.SSLContext; - +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClients; import org.eclipse.jetty.util.security.Password; +import org.onap.vid.exceptions.GenericUncheckedException; +import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.util.SystemProperties; +import javax.net.ssl.SSLContext; +import java.io.FileInputStream; +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStore; + /** * The Class HttpsComponentsClient. */ public class HttpsComponentsClient{ - + + static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(HttpsComponentsClient.class); + /** * Gets the client. * @@ -46,10 +50,10 @@ public class HttpsComponentsClient{ * @return the client * @throws KeyManagementException the key management exception */ - public static CloseableHttpClient getClient(String certFilePath) throws Exception { + public static CloseableHttpClient getClient(String certFilePath) { CloseableHttpClient httpclient = null; try { - + String truststore_path = certFilePath + AAIProperties.FILESEPARTOR + SystemProperties.getProperty(AAIProperties.AAI_TRUSTSTORE_FILENAME); String truststore_password = SystemProperties.getProperty(AAIProperties.AAI_TRUSTSTORE_PASSWD_X); String decrypted_truststore_password = Password.deobfuscate(truststore_password); @@ -60,17 +64,31 @@ public class HttpsComponentsClient{ SSLContextBuilder sslContextB = new SSLContextBuilder(); KeyStore ks = KeyStore.getInstance("PKCS12"); - FileInputStream fin = new FileInputStream(keystore_path); char[] pwd = decrypted_keystore_password.toCharArray(); - ks.load(fin, pwd); - + + try(FileInputStream fin = new FileInputStream(keystore_path)) { + ks.load(fin, pwd); + } + catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up keystore"); + logger.error(EELFLoggerDelegate.errorLogger, "Error loading keystore materials: (keystore path: {}, obfuascated keystore password: {})", keystore_path, keystore_password); + throw new GenericUncheckedException(e); + } + sslContextB.loadKeyMaterial(ks, pwd); KeyStore ts = KeyStore.getInstance("JKS"); - FileInputStream fin1 = new FileInputStream(truststore_path); char[] pwd1 = decrypted_truststore_password.toCharArray(); - ts.load(fin1, pwd1); - + + try(FileInputStream fin1 = new FileInputStream(truststore_path)) { + ts.load(fin1, pwd1); + } + catch (Exception e) { + logger.debug(EELFLoggerDelegate.debugLogger, "Error setting up truststore"); + logger.error(EELFLoggerDelegate.errorLogger, "Error loading truststore materials: (truststore path: {}, obfuascated truststore password: {})", truststore_path, truststore_password); + throw new GenericUncheckedException(e); + } + sslContextB.loadTrustMaterial(ts); sslContextB.loadKeyMaterial(ks, pwd); sslContextB.useTLS(); @@ -88,8 +106,8 @@ public class HttpsComponentsClient{ .build(); - } catch (Exception e) { - throw e; + } catch (GeneralSecurityException e) { + throw new GenericUncheckedException(e); } return httpclient; } diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java index 8a3ba88f..cfc56d18 100644 --- a/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/JettyObfuscationConversionCommandLineUtil.java @@ -21,11 +21,7 @@ package org.onap.vid.aai.util; -import org.apache.commons.cli.BasicParser; -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; +import org.apache.commons.cli.*; import org.eclipse.jetty.util.security.Password; @@ -70,7 +66,7 @@ public class JettyObfuscationConversionCommandLineUtil { * Usage. */ private static void usage(){ - System.out.println("usage:");; + System.out.println("usage:"); System.out.println("-e [string] to obfuscate"); System.out.println("-d [string] to deobfuscate"); System.out.println("-h help"); diff --git a/vid-app-common/src/main/java/org/onap/vid/aai/util/VidObjectMapperType.java b/vid-app-common/src/main/java/org/onap/vid/aai/util/VidObjectMapperType.java new file mode 100644 index 00000000..931987ae --- /dev/null +++ b/vid-app-common/src/main/java/org/onap/vid/aai/util/VidObjectMapperType.java @@ -0,0 +1,6 @@ +package org.onap.vid.aai.util; + +public enum VidObjectMapperType { + CODEHAUS, + FASTERXML +}
\ No newline at end of file |