diff options
Diffstat (limited to 'aai-service/provider/src')
9 files changed, 789 insertions, 1265 deletions
diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIClientRESTExecutor.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIClientRESTExecutor.java index 5e2c8c0a5..8f624e9e5 100755 --- a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIClientRESTExecutor.java +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIClientRESTExecutor.java @@ -3,7 +3,7 @@ * openECOMP : SDN-C * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. + * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,54 +70,54 @@ import com.sun.jersey.client.urlconnection.HTTPSProperties; * The AAIClientRESTExecutor class provides CRUD API for AAI Client service. * @author richtabedzki */ -public class AAIClientRESTExecutor implements AAIExecutorInterface { - - private final String truststorePath; - private final String truststorePassword; - private final String keystorePath; - private final String keystorePassword; - private final Boolean ignoreCertificateHostError; - // authentication credentials - private String userName; - private String userPassword; - private final String applicationId; - - /** - * class Constructor - * @param props - properties to initialize an instance. - */ - public AAIClientRESTExecutor(Properties props) { - super(); - - userName = props.getProperty(AAIService.CLIENT_NAME); - userPassword = props.getProperty(AAIService.CLIENT_PWWD); +public class AAIClientRESTExecutor implements AAIExecutorInterface { + + private final String truststorePath; + private final String truststorePassword; + private final String keystorePath; + private final String keystorePassword; + private final Boolean ignoreCertificateHostError; + // authentication credentials + private String userName; + private String userPassword; + private final String applicationId; + + /** + * class Constructor + * @param props - properties to initialize an instance. + */ + public AAIClientRESTExecutor(Properties props) { + super(); + + userName = props.getProperty(AAIService.CLIENT_NAME); + userPassword = props.getProperty(AAIService.CLIENT_PWWD); if(userName == null || userName.isEmpty()){ - LOG.debug("Basic user name is not set"); + LOG.debug("Basic user name is not set"); } if(userPassword == null || userPassword.isEmpty()) { - LOG.debug("Basic password is not set"); + LOG.debug("Basic password is not set"); } - truststorePath = props.getProperty(AAIService.TRUSTSTORE_PATH); - truststorePassword = props.getProperty(AAIService.TRUSTSTORE_PSSWD); - keystorePath = props.getProperty(AAIService.KEYSTORE_PATH); - keystorePassword = props.getProperty(AAIService.KEYSTORE_PSSWD); -// this.read_timeout = read_timeout; + truststorePath = props.getProperty(AAIService.TRUSTSTORE_PATH); + truststorePassword = props.getProperty(AAIService.TRUSTSTORE_PSSWD); + keystorePath = props.getProperty(AAIService.KEYSTORE_PATH); + keystorePassword = props.getProperty(AAIService.KEYSTORE_PSSWD); +// this.read_timeout = read_timeout; - String tmpApplicationId =props.getProperty(AAIService.APPLICATION_ID); - if(tmpApplicationId == null || tmpApplicationId.isEmpty()) { - tmpApplicationId = "SDNC"; - } - applicationId = tmpApplicationId; + String tmpApplicationId =props.getProperty(AAIService.APPLICATION_ID); + if(tmpApplicationId == null || tmpApplicationId.isEmpty()) { + tmpApplicationId = "SDNC"; + } + applicationId = tmpApplicationId; - String iche = props.getProperty(AAIService.CERTIFICATE_HOST_ERROR); - boolean host_error = false; - if(iche != null && !iche.isEmpty()) { - host_error = Boolean.valueOf(iche); - } + String iche = props.getProperty(AAIService.CERTIFICATE_HOST_ERROR); + boolean host_error = false; + if(iche != null && !iche.isEmpty()) { + host_error = Boolean.valueOf(iche); + } - ignoreCertificateHostError = host_error; + ignoreCertificateHostError = host_error; HttpsURLConnection.setDefaultHostnameVerifier( new HostnameVerifier(){ public boolean verify(String string,SSLSession ssls) { @@ -125,54 +125,54 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { } }); - if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) { - System.setProperty("javax.net.ssl.trustStore", truststorePath); - System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword); - } + if(truststorePath != null && truststorePassword != null && (new File(truststorePath)).exists()) { + System.setProperty("javax.net.ssl.trustStore", truststorePath); + System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword); + } if(keystorePath != null && keystorePassword != null && (new File(keystorePath)).exists()) { - DefaultClientConfig config = new DefaultClientConfig(); - //both jersey and HttpURLConnection can use this - SSLContext ctx = null; - try { - ctx = SSLContext.getInstance("TLS"); - - KeyManagerFactory kmf = null; - try { - String storeType = "PKCS12"; - String def = KeyStore.getDefaultType(); - kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - FileInputStream fin = new FileInputStream(keystorePath); - - String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1); - - if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) { - storeType = "JKS"; - } - KeyStore ks = KeyStore.getInstance(storeType); - - char[] pwd = keystorePassword.toCharArray(); - ks.load(fin, pwd); - kmf.init(ks, pwd); - } catch (Exception ex) { - LOG.error("AAIResource", ex); - } - - ctx.init(kmf.getKeyManagers(), null, null); - config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() { - @Override - public boolean verify( String s, SSLSession sslSession ) { - return ignoreCertificateHostError; - } - }, ctx)); - - CTX = ctx; - LOG.debug("SSLContext created"); - - } catch (KeyManagementException | NoSuchAlgorithmException exc) { - LOG.error("AAIResource", exc); - } + DefaultClientConfig config = new DefaultClientConfig(); + //both jersey and HttpURLConnection can use this + SSLContext ctx = null; + try { + ctx = SSLContext.getInstance("TLS"); + + KeyManagerFactory kmf = null; + try { + String storeType = "PKCS12"; + String def = KeyStore.getDefaultType(); + kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + FileInputStream fin = new FileInputStream(keystorePath); + + String extension = keystorePath.substring(keystorePath.lastIndexOf(".") + 1); + + if(extension != null && !extension.isEmpty() && extension.equalsIgnoreCase("JKS")) { + storeType = "JKS"; + } + KeyStore ks = KeyStore.getInstance(storeType); + + char[] pwd = keystorePassword.toCharArray(); + ks.load(fin, pwd); + kmf.init(ks, pwd); + } catch (Exception ex) { + LOG.error("AAIResource", ex); + } + + ctx.init(kmf.getKeyManagers(), null, null); + config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() { + @Override + public boolean verify( String s, SSLSession sslSession ) { + return ignoreCertificateHostError; + } + }, ctx)); + + CTX = ctx; + LOG.debug("SSLContext created"); + + } catch (KeyManagementException | NoSuchAlgorithmException exc) { + LOG.error("AAIResource", exc); + } } try { @@ -194,68 +194,68 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { methodsField.set(null, methods); } catch (SecurityException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException e) { - e.printStackTrace(); + LOG.warn("Adding PATCH method", e); } LOG.info("AAIResource.ctor initialized."); - } + } - private static final Logger LOG = LoggerFactory.getLogger(AAIService.class); - private final MetricLogger ml = new MetricLogger(); + private static final Logger LOG = LoggerFactory.getLogger(AAIService.class); + private final MetricLogger ml = new MetricLogger(); - private SSLContext CTX; + private SSLContext CTX; - private int connection_timeout = 300000; + private int connection_timeout = 300000; - private int read_timeout = 300000; + private int read_timeout = 300000; - /** - * Returns an String that contains JSON data returned from the AAI Server. - * <p> - * This method always returns immediately, whether or not the - * data exists. - * - * @param request an instance of AAIRequiest representing - * the request made by DirectedGraph node. - * @return the JSON based representation of data instance requested. - * @see String - */ - @Override - public String get(AAIRequest request) throws AAIServiceException { - String response = null; - InputStream inputStream = null; - HttpURLConnection con = null; - URL requestUrl = null; + /** + * Returns an String that contains JSON data returned from the AAI Server. + * <p> + * This method always returns immediately, whether or not the + * data exists. + * + * @param request an instance of AAIRequiest representing + * the request made by DirectedGraph node. + * @return the JSON based representation of data instance requested. + * @see String + */ + @Override + public String get(AAIRequest request) throws AAIServiceException { + String response = null; + InputStream inputStream = null; + HttpURLConnection con = null; + URL requestUrl = null; - StringBuilder errorStringBuilder = new StringBuilder(); + StringBuilder errorStringBuilder = new StringBuilder(); - try { + try { if(request.getRequestObject() != null) { - requestUrl = request.getRequestUrl(HttpMethod.POST, null); - requestUrl = appendDepth(requestUrl, request); - con = getConfiguredConnection(requestUrl, HttpMethod.POST); - String json_text = request.toJSONString(); - LOGwriteDateTrace("data", json_text); - logMetricRequest("POST "+requestUrl.getPath(), json_text, requestUrl.getPath()); - OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream()); - osw.write(json_text); - osw.flush(); + requestUrl = request.getRequestUrl(HttpMethod.POST, null); + requestUrl = appendDepth(requestUrl, request); + con = getConfiguredConnection(requestUrl, HttpMethod.POST); + String json_text = request.toJSONString(); + LOGwriteDateTrace("data", json_text); + logMetricRequest("POST "+requestUrl.getPath(), json_text, requestUrl.getPath()); + OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream()); + osw.write(json_text); + osw.flush(); } else { - requestUrl = request.getRequestUrl(HttpMethod.GET, null); - requestUrl = appendDepth(requestUrl, request); - con = getConfiguredConnection(requestUrl, HttpMethod.GET); - logMetricRequest("GET "+requestUrl.getPath(), "", requestUrl.getPath()); + requestUrl = request.getRequestUrl(HttpMethod.GET, null); + requestUrl = appendDepth(requestUrl, request); + con = getConfiguredConnection(requestUrl, HttpMethod.GET); + logMetricRequest("GET "+requestUrl.getPath(), "", requestUrl.getPath()); } // Check for errors String responseMessage = con.getResponseMessage(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { - inputStream = con.getInputStream(); + inputStream = con.getInputStream(); } else { - inputStream = con.getErrorStream(); + inputStream = con.getErrorStream(); } // Process the response @@ -267,121 +267,121 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { ObjectMapper mapper = AAIService.getObjectMapper(); - if (responseCode == HttpURLConnection.HTTP_OK) { - StringBuilder stringBuilder = new StringBuilder(); - String line = null; - while( ( line = reader.readLine() ) != null ) { - stringBuilder.append( line ); - } - response = stringBuilder.toString(); - try { - Object object = mapper.readValue(response, Object.class); - LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object)); - } catch(Exception exc) { - LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response)); - } + if (responseCode == HttpURLConnection.HTTP_OK) { + StringBuilder stringBuilder = new StringBuilder(); + String line = null; + while( ( line = reader.readLine() ) != null ) { + stringBuilder.append( line ); + } + response = stringBuilder.toString(); + try { + Object object = mapper.readValue(response, Object.class); + LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(object)); + } catch(Exception exc) { + LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, responseMessage, mapper.writeValueAsString(response)); + } } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { - LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist."); - ErrorResponse errorresponse = null; - try { - errorresponse = mapper.readValue(reader, ErrorResponse.class); - } catch(Exception exc) { - errorresponse = new ErrorResponse(); - RequestError requestError = new RequestError(); - ServiceException serviceException = new ServiceException(); - serviceException.setText("Entry does not exist."); - requestError.setServiceException(serviceException); - errorresponse.setRequestError(requestError ); - } - throw new AAIServiceException(responseCode, errorresponse); + LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist."); + ErrorResponse errorresponse = null; + try { + errorresponse = mapper.readValue(reader, ErrorResponse.class); + } catch(Exception exc) { + errorresponse = new ErrorResponse(); + RequestError requestError = new RequestError(); + ServiceException serviceException = new ServiceException(); + serviceException.setText("Entry does not exist."); + requestError.setServiceException(serviceException); + errorresponse.setRequestError(requestError ); + } + throw new AAIServiceException(responseCode, errorresponse); } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) { - StringBuilder stringBuilder = new StringBuilder(); - String line = null; - while( ( line = reader.readLine() ) != null ) { - stringBuilder.append( line ); - } - LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString()); - ServiceException serviceException = new ServiceException(); - serviceException.setMessageId("HTTP_UNAUTHORIZED"); - serviceException.setText(stringBuilder.toString()); - RequestError requestError = new RequestError(); - requestError.setServiceException(serviceException); - ErrorResponse errorresponse = new ErrorResponse(); - errorresponse.setRequestError(requestError); - throw new AAIServiceException(responseCode, errorresponse); + StringBuilder stringBuilder = new StringBuilder(); + String line = null; + while( ( line = reader.readLine() ) != null ) { + stringBuilder.append( line ); + } + LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString()); + ServiceException serviceException = new ServiceException(); + serviceException.setMessageId("HTTP_UNAUTHORIZED"); + serviceException.setText(stringBuilder.toString()); + RequestError requestError = new RequestError(); + requestError.setServiceException(serviceException); + ErrorResponse errorresponse = new ErrorResponse(); + errorresponse.setRequestError(requestError); + throw new AAIServiceException(responseCode, errorresponse); } else { -// StringBuilder errorStringBuilder = new StringBuilder(); - String line = null; - while( ( line = reader.readLine() ) != null ) { - errorStringBuilder.append("\n").append( line ); - } - - ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class); -// ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); - LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); - throw new AAIServiceException(responseCode, errorresponse); +// StringBuilder errorStringBuilder = new StringBuilder(); + String line = null; + while( ( line = reader.readLine() ) != null ) { + errorStringBuilder.append("\n").append( line ); + } + + ErrorResponse errorresponse = mapper.readValue(errorStringBuilder.toString(), ErrorResponse.class); +// ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); + LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); + throw new AAIServiceException(responseCode, errorresponse); } - } catch(AAIServiceException aaiexc) { - throw aaiexc; - } catch (Exception exc) { - LOG.warn(errorStringBuilder.toString(), exc); - throw new AAIServiceException(exc); - } finally { - if(inputStream != null){ - try { - inputStream.close(); - } catch(Exception exc) { - - } - } - } - return response; - } - - /** - * Returns an String that contains JSON data returned from the AAI Server. - * <p> - * This method always returns immediately, whether or not the - * data exists. - * - * @param request an instance of AAIRequiest representing - * the request made by DirectedGraph node. - * @return the JSON based representation of data instance requested. - * @see String - */ - @Override - public String post(AAIRequest request) throws AAIServiceException { - InputStream inputStream = null; - - try { - String resourceVersion = null; - AAIDatum instance = request.getRequestObject(); - - try { - Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion"); - if(getResourceVersionMethod != null){ - try { - Object object = getResourceVersionMethod.invoke(instance); - if(object != null) - resourceVersion = object.toString(); - } catch (InvocationTargetException x) { - Throwable cause = x.getCause(); - } - } - } catch(Exception exc) { - LOG.error("", exc); - } - - URL requestUrl = null; - HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT); - ObjectMapper mapper = AAIService.getObjectMapper(); - String json_text = request.toJSONString(); - - LOGwriteDateTrace("data", json_text); - logMetricRequest("PUT "+requestUrl.getPath(), json_text, requestUrl.getPath()); - - OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream()); + } catch(AAIServiceException aaiexc) { + throw aaiexc; + } catch (Exception exc) { + LOG.warn(errorStringBuilder.toString(), exc); + throw new AAIServiceException(exc); + } finally { + if(inputStream != null){ + try { + inputStream.close(); + } catch(Exception exc) { + + } + } + } + return response; + } + + /** + * Returns an String that contains JSON data returned from the AAI Server. + * <p> + * This method always returns immediately, whether or not the + * data exists. + * + * @param request an instance of AAIRequiest representing + * the request made by DirectedGraph node. + * @return the JSON based representation of data instance requested. + * @see String + */ + @Override + public String post(AAIRequest request) throws AAIServiceException { + InputStream inputStream = null; + + try { + String resourceVersion = null; + AAIDatum instance = request.getRequestObject(); + + try { + Method getResourceVersionMethod = instance.getClass().getMethod("getResourceVersion"); + if(getResourceVersionMethod != null){ + try { + Object object = getResourceVersionMethod.invoke(instance); + if(object != null) + resourceVersion = object.toString(); + } catch (InvocationTargetException x) { + Throwable cause = x.getCause(); + } + } + } catch(Exception exc) { + LOG.error("", exc); + } + + URL requestUrl = null; + HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.PUT, resourceVersion), HttpMethod.PUT); + ObjectMapper mapper = AAIService.getObjectMapper(); + String json_text = request.toJSONString(); + + LOGwriteDateTrace("data", json_text); + logMetricRequest("PUT "+requestUrl.getPath(), json_text, requestUrl.getPath()); + + OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream()); osw.write(json_text); osw.flush(); @@ -389,9 +389,9 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { String responseMessage = con.getResponseMessage(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - inputStream = con.getInputStream(); + inputStream = con.getInputStream(); } else { - inputStream = con.getErrorStream(); + inputStream = con.getErrorStream(); } LOG.debug("HttpURLConnection result:" + responseCode + " : " + responseMessage); @@ -403,58 +403,58 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { reader = new BufferedReader( new InputStreamReader( inputStream ) ); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - StringBuilder stringBuilder = new StringBuilder(); + if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { + StringBuilder stringBuilder = new StringBuilder(); - while( ( line = reader.readLine() ) != null ) { - stringBuilder.append( line ); - } - LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}"); - return stringBuilder.toString(); + while( ( line = reader.readLine() ) != null ) { + stringBuilder.append( line ); + } + LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder.length() > 0) ? stringBuilder.toString() : "{no-data}"); + return stringBuilder.toString(); } else { - ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); - LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); + ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); + LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); - throw new AAIServiceException(responseCode, errorresponse); + throw new AAIServiceException(responseCode, errorresponse); } - } catch(AAIServiceException aaiexc) { - throw aaiexc; - } catch (Exception exc) { - LOG.warn("AAIRequestExecutor.post", exc); - throw new AAIServiceException(exc); - } finally { - try { - if(inputStream != null) - inputStream.close(); - } catch (Exception exc) { - - } - } - } - - /** - * Returns Boolean that contains completion state of the command executed. - * <p> - * This method always returns immediately, whether or not the - * data exists. - * - * @param request an instance of AAIRequiest representing - * @param resourceVersion a resource version of the data instacne to be deleted. - * the request made by DirectedGraph node. - * @return completion state of the command. - * @see String - */ - @Override - public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException { - Boolean response = null; - InputStream inputStream = null; - - if(resourceVersion == null) { - throw new AAIServiceException("resource-version is required for DELETE request"); - } - - try { - URL requestUrl = null; + } catch(AAIServiceException aaiexc) { + throw aaiexc; + } catch (Exception exc) { + LOG.warn("AAIRequestExecutor.post", exc); + throw new AAIServiceException(exc); + } finally { + try { + if(inputStream != null) + inputStream.close(); + } catch (Exception exc) { + + } + } + } + + /** + * Returns Boolean that contains completion state of the command executed. + * <p> + * This method always returns immediately, whether or not the + * data exists. + * + * @param request an instance of AAIRequiest representing + * @param resourceVersion a resource version of the data instacne to be deleted. + * the request made by DirectedGraph node. + * @return completion state of the command. + * @see String + */ + @Override + public Boolean delete(AAIRequest request, String resourceVersion) throws AAIServiceException { + Boolean response = null; + InputStream inputStream = null; + + if(resourceVersion == null) { + throw new AAIServiceException("resource-version is required for DELETE request"); + } + + try { + URL requestUrl = null; HttpURLConnection conn = getConfiguredConnection(requestUrl = request.getRequestUrl(HttpMethod.DELETE, resourceVersion), HttpMethod.DELETE); logMetricRequest("DELETE "+requestUrl.getPath(), "", requestUrl.getPath()); conn.setDoOutput(true); @@ -463,9 +463,9 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { String responseMessage = conn.getResponseMessage(); int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - inputStream = conn.getInputStream(); + inputStream = conn.getInputStream(); } else { - inputStream = conn.getErrorStream(); + inputStream = conn.getErrorStream(); } // Process the response @@ -478,59 +478,59 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { ObjectMapper mapper = AAIService.getObjectMapper(); - if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - StringBuilder stringBuilder = new StringBuilder(); - - while( ( line = reader.readLine() ) != null ) { - stringBuilder.append( line ); - } - LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString()); - response = true; - } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) { - LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist."); - response = false; + if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { + StringBuilder stringBuilder = new StringBuilder(); + + while( ( line = reader.readLine() ) != null ) { + stringBuilder.append( line ); + } + LOGwriteEndingTrace(responseCode, responseMessage, stringBuilder.toString()); + response = true; + } else if(responseCode == HttpURLConnection.HTTP_NOT_FOUND ) { + LOGwriteEndingTrace(responseCode, responseMessage, "Entry does not exist."); + response = false; } else { - ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); - LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); - throw new AAIServiceException(responseCode, errorresponse); + ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); + LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); + throw new AAIServiceException(responseCode, errorresponse); } - } catch(AAIServiceException aaiexc) { - throw aaiexc; - } catch (Exception exc) { - LOG.warn("delete", exc); - throw new AAIServiceException(exc); - } finally { - if(inputStream != null){ - try { - inputStream.close(); - } catch(Exception exc) { - - } - } - } - return response; - } - - /** - * Returns an String that contains JSON data returned from the AAI Server. - * <p> - * This method always returns immediately, whether or not the - * data exists. - * - * @param request an instance of AAIRequiest representing - * the request made by DirectedGraph node. - * @param clas an definition of the class for which data will be returned - * @return the instance of the class with data. - * @see String - */ - @Override - public Object query(AAIRequest request, Class clas) throws AAIServiceException { - Object response = null; - InputStream inputStream = null; - HttpURLConnection con = null; - URL requestUrl = null; - - try { + } catch(AAIServiceException aaiexc) { + throw aaiexc; + } catch (Exception exc) { + LOG.warn("delete", exc); + throw new AAIServiceException(exc); + } finally { + if(inputStream != null){ + try { + inputStream.close(); + } catch(Exception exc) { + + } + } + } + return response; + } + + /** + * Returns an String that contains JSON data returned from the AAI Server. + * <p> + * This method always returns immediately, whether or not the + * data exists. + * + * @param request an instance of AAIRequiest representing + * the request made by DirectedGraph node. + * @param clas an definition of the class for which data will be returned + * @return the instance of the class with data. + * @see String + */ + @Override + public Object query(AAIRequest request, Class clas) throws AAIServiceException { + Object response = null; + InputStream inputStream = null; + HttpURLConnection con = null; + URL requestUrl = null; + + try { con = getConfiguredConnection(requestUrl = request.getRequestQueryUrl(HttpMethod.GET), HttpMethod.GET); logMetricRequest("GET "+requestUrl.getPath(), "", requestUrl.getPath()); @@ -538,66 +538,66 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { String responseMessage = con.getResponseMessage(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { - inputStream = con.getInputStream(); + inputStream = con.getInputStream(); } else { - inputStream = con.getErrorStream(); + inputStream = con.getErrorStream(); } logMetricResponse(responseCode, responseMessage); ObjectMapper mapper = AAIService.getObjectMapper(); - if (responseCode == HttpURLConnection.HTTP_OK) { - // Process the response - BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) ); - response = mapper.readValue(reader, clas); - LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response)); + if (responseCode == HttpURLConnection.HTTP_OK) { + // Process the response + BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) ); + response = mapper.readValue(reader, clas); + LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response)); } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) { - LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist."); - return response; - } else { - BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) ); - ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); - LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse)); - throw new AAIServiceException(responseCode, errorresponse); + LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist."); + return response; + } else { + BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream ) ); + ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); + LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse)); + throw new AAIServiceException(responseCode, errorresponse); } - } catch(AAIServiceException aaiexc) { - throw aaiexc; - } catch (Exception exc) { - LOG.warn("GET", exc); - throw new AAIServiceException(exc); - } finally { - if(inputStream != null){ - try { - inputStream.close(); - } catch(Exception exc) { - - } - } - con = null; - } - return response; - } - - @Override - public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException { - InputStream inputStream = null; - - try { - AAIDatum instance = request.getRequestObject(); - if(instance instanceof ResourceVersion) { - resourceVersion = ((ResourceVersion)instance).getResourceVersion(); - } - - URL requestUrl = null; - HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH"); - ObjectMapper mapper = AAIService.getObjectMapper(); - String json_text = request.toJSONString(); - - LOGwriteDateTrace("data", json_text); - logMetricRequest("PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath()); - - OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream()); + } catch(AAIServiceException aaiexc) { + throw aaiexc; + } catch (Exception exc) { + LOG.warn("GET", exc); + throw new AAIServiceException(exc); + } finally { + if(inputStream != null){ + try { + inputStream.close(); + } catch(Exception exc) { + + } + } + con = null; + } + return response; + } + + @Override + public Boolean patch(AAIRequest request, String resourceVersion) throws AAIServiceException { + InputStream inputStream = null; + + try { + AAIDatum instance = request.getRequestObject(); + if(instance instanceof ResourceVersion) { + resourceVersion = ((ResourceVersion)instance).getResourceVersion(); + } + + URL requestUrl = null; + HttpURLConnection con = getConfiguredConnection(requestUrl = request.getRequestUrl("PATCH", resourceVersion), "PATCH"); + ObjectMapper mapper = AAIService.getObjectMapper(); + String json_text = request.toJSONString(); + + LOGwriteDateTrace("data", json_text); + logMetricRequest("PATCH "+requestUrl.getPath(), json_text, requestUrl.getPath()); + + OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream()); osw.write(json_text); osw.flush(); @@ -605,9 +605,9 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { String responseMessage = con.getResponseMessage(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - inputStream = con.getInputStream(); + inputStream = con.getInputStream(); } else { - inputStream = con.getErrorStream(); + inputStream = con.getErrorStream(); } LOG.info("HttpURLConnection result: " + responseCode + " : " + responseMessage); @@ -619,133 +619,133 @@ public class AAIClientRESTExecutor implements AAIExecutorInterface { reader = new BufferedReader( new InputStreamReader( inputStream ) ); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { - StringBuilder stringBuilder = new StringBuilder(); + if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_NO_CONTENT) { + StringBuilder stringBuilder = new StringBuilder(); - while( ( line = reader.readLine() ) != null ) { - stringBuilder.append( line ); - } - LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}"); - return true; + while( ( line = reader.readLine() ) != null ) { + stringBuilder.append( line ); + } + LOGwriteEndingTrace(responseCode, responseMessage, (stringBuilder != null) ? stringBuilder.toString() : "{no-data}"); + return true; } else { - StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder = new StringBuilder(); + + while( ( line = reader.readLine() ) != null ) { + stringBuilder.append("\n").append( line ); + } + LOG.info(stringBuilder.toString()); + - while( ( line = reader.readLine() ) != null ) { - stringBuilder.append("\n").append( line ); - } - LOG.info(stringBuilder.toString()); + ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); + LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); + throw new AAIServiceException(responseCode, errorresponse); + } + } catch(AAIServiceException aaiexc) { + throw aaiexc; + } catch (Exception exc) { + LOG.warn("AAIRequestExecutor.patch", exc); + throw new AAIServiceException(exc); + } finally { + try { + if(inputStream != null) + inputStream.close(); + } catch (Exception exc) { + + } + } + } + + /** + * + * @param httpReqUrl + * @param method + * @return + * @throws Exception + */ + protected HttpURLConnection getConfiguredConnection(URL httpReqUrl, String method) throws Exception { + HttpURLConnection con = (HttpURLConnection) httpReqUrl.openConnection(); + + // Set up the connection properties + con.setRequestProperty("Connection", "close"); + con.setDoInput(true); + con.setDoOutput(true); + con.setUseCaches(false); + con.setConnectTimeout(connection_timeout); + con.setReadTimeout(read_timeout); + con.setRequestMethod(method); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("Transfer-Encoding","chunked"); + con.setRequestProperty("Content-Type", + "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json"); + con.setRequestProperty("X-FromAppId", applicationId); + con.setRequestProperty("X-TransactionId", TransactionIdTracker.getNextTransactionId()); + String mlId = ml.getRequestID(); + if (mlId != null && !mlId.isEmpty()) { + LOG.debug(String.format("MetricLogger requestId = %s", mlId)); + con.setRequestProperty(MetricLogger.REQUEST_ID, mlId); + } else { + LOG.debug("MetricLogger requestId is null"); + } - ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class); - LOGwriteEndingTrace(responseCode, responseMessage, mapper.writeValueAsString(errorresponse)); + if (userName != null && !userName.isEmpty() && userPassword != null && !userPassword.isEmpty()) { + String basicAuth = "Basic " + new String(Base64.encodeBase64((userName + ":" + userPassword).getBytes())); + con.setRequestProperty("Authorization", basicAuth); + } - throw new AAIServiceException(responseCode, errorresponse); + if (con instanceof HttpsURLConnection && CTX != null) { + SSLSocketFactory sockFact = CTX.getSocketFactory(); + HttpsURLConnection.class.cast(con).setSSLSocketFactory(sockFact); + } + return con; + } + + private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException { + + String depth = request.requestProperties.getProperty("depth", "1"); + String path = requestUrl.toString(); + if(path.contains("?depth=") || path.contains("&depth=")) { + return requestUrl; + } else { + if(path.contains("?")) { + path = String.format("%s&depth=%s", path, depth); + } else { + path = String.format("%s?depth=%s", path, depth); } - } catch(AAIServiceException aaiexc) { - throw aaiexc; - } catch (Exception exc) { - LOG.warn("AAIRequestExecutor.patch", exc); - throw new AAIServiceException(exc); - } finally { - try { - if(inputStream != null) - inputStream.close(); - } catch (Exception exc) { - - } - } - } - - /** - * - * @param httpReqUrl - * @param method - * @return - * @throws Exception - */ - protected HttpURLConnection getConfiguredConnection(URL httpReqUrl, String method) throws Exception { - HttpURLConnection con = (HttpURLConnection) httpReqUrl.openConnection(); - - // Set up the connection properties - con.setRequestProperty("Connection", "close"); - con.setDoInput(true); - con.setDoOutput(true); - con.setUseCaches(false); - con.setConnectTimeout(connection_timeout); - con.setReadTimeout(read_timeout); - con.setRequestMethod(method); - con.setRequestProperty("Accept", "application/json"); - con.setRequestProperty("Transfer-Encoding","chunked"); - con.setRequestProperty("Content-Type", - "PATCH".equalsIgnoreCase(method) ? "application/merge-patch+json" : "application/json"); - con.setRequestProperty("X-FromAppId", applicationId); - con.setRequestProperty("X-TransactionId", TransactionIdTracker.getNextTransactionId()); - String mlId = ml.getRequestID(); - if (mlId != null && !mlId.isEmpty()) { - LOG.debug(String.format("MetricLogger requestId = %s", mlId)); - con.setRequestProperty(MetricLogger.REQUEST_ID, mlId); - } else { - LOG.debug("MetricLogger requestId is null"); - } - - if (userName != null && !userName.isEmpty() && userPassword != null && !userPassword.isEmpty()) { - String basicAuth = "Basic " + new String(Base64.encodeBase64((userName + ":" + userPassword).getBytes())); - con.setRequestProperty("Authorization", basicAuth); - } - - if (con instanceof HttpsURLConnection && CTX != null) { - SSLSocketFactory sockFact = CTX.getSocketFactory(); - HttpsURLConnection.class.cast(con).setSSLSocketFactory(sockFact); - } - return con; - } - - private URL appendDepth(URL requestUrl, AAIRequest request) throws MalformedURLException { - - String depth = request.requestProperties.getProperty("depth", "1"); - String path = requestUrl.toString(); - if(path.contains("?depth=") || path.contains("&depth=")) { - return requestUrl; - } else { - if(path.contains("?")) { - path = String.format("%s&depth=%s", path, depth); - } else { - path = String.format("%s?depth=%s", path, depth); - } - return new URL(path); - } - } - - public void logMetricRequest(String targetServiceName, String msg, String path){ - String svcInstanceId = ""; - String svcName = null; - String partnerName = null; - String targetEntity = "A&AI"; - String targetVirtualEntity = null; - - targetServiceName = ""; - - ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg); - } - - public void logMetricResponse(int responseCode, String responseDescription){ - ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription); - } - - protected void LOGwriteFirstTrace(String method, String url) { - String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis()); - LOG.info("A&AI transaction :"); - LOG.info("Request Time : " + time + ", Method : " + method); - LOG.info("Request URL : "+ url); - } - - protected void LOGwriteDateTrace(String name, String data) { - LOG.info("Input - " + name + " : " + data); - } - - protected void LOGwriteEndingTrace(int response_code, String comment, String data) { - LOG.info("Response code : " + response_code +", " + comment); - LOG.info(String.format("Response data : %s", data)); - } + return new URL(path); + } + } + + public void logMetricRequest(String targetServiceName, String msg, String path){ + String svcInstanceId = ""; + String svcName = null; + String partnerName = null; + String targetEntity = "A&AI"; + String targetVirtualEntity = null; + + targetServiceName = ""; + + ml.logRequest(svcInstanceId, svcName, partnerName, targetEntity, targetServiceName, targetVirtualEntity, msg); + } + + public void logMetricResponse(int responseCode, String responseDescription){ + ml.logResponse(responseCode < 400 ? "SUCCESS" : "FAILURE", Integer.toString(responseCode), responseDescription); + } + + protected void LOGwriteFirstTrace(String method, String url) { + String time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(System.currentTimeMillis()); + LOG.info("A&AI transaction :"); + LOG.info("Request Time : " + time + ", Method : " + method); + LOG.info("Request URL : "+ url); + } + + protected void LOGwriteDateTrace(String name, String data) { + LOG.info("Input - " + name + " : " + data); + } + + protected void LOGwriteEndingTrace(int response_code, String comment, String data) { + LOG.info("Response code : " + response_code +", " + comment); + LOG.info(String.format("Response data : %s", data)); + } } diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIRequest.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIRequest.java index f26b71de9..21f8859d5 100755 --- a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIRequest.java +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIRequest.java @@ -174,7 +174,7 @@ public abstract class AAIRequest { try { URL url = null; - Bundle bundle = FrameworkUtil.getBundle(AAIServiceActivator.class); + Bundle bundle = FrameworkUtil.getBundle(AAIService.class); if(bundle != null) { BundleContext ctx = bundle.getBundleContext(); if(ctx == null) diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java index c4604a4a1..c8c5b92df 100755 --- a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIService.java @@ -26,6 +26,7 @@ import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; @@ -152,11 +153,25 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe private AAIExecutorInterface executor; - public void setExecutor(AAIExecutorInterface executor) { - this.executor = executor; - } + public AAIService(final UtilsProvider configuration) { + this(configuration.getProperties()); + } + + public AAIService(final URL url) { + this(getProperties(url)); + } + + private static Properties getProperties(URL url) { + Properties properties = new Properties(); + try { + properties.load(url.openStream()); + } catch (IOException exc) { + LOG.error("getProperties", exc); + } + return properties; + } - public AAIService(URL propURL) { + public AAIService(Properties props) { LOG.info("Entered AAIService.ctor"); String runtime = System.getProperty("aaiclient.runtime"); @@ -166,9 +181,7 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe runtimeOSGI = false; } - Properties props = null; try { - props = initialize(propURL); AAIRequest.setProperties(props, this); } catch(Exception exc){ @@ -198,7 +211,7 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe String tmpApplicationId = props.getProperty(APPLICATION_ID); if(tmpApplicationId == null || tmpApplicationId.isEmpty()) { - tmpApplicationId = "SDNC"; + tmpApplicationId = "SDNC"; } this.applicationId = tmpApplicationId; @@ -329,6 +342,10 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe } + public void setExecutor(AAIExecutorInterface executor) { + this.executor = executor; + } + public void cleanUp() { } @@ -1373,7 +1390,7 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe String normResource = resource.split(":")[0]; switch(normResource){ - case "custom-query": + case "custom-query": case "formatted-query": case "generic-query": case "named-query": @@ -1402,7 +1419,7 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe String normResource = resource.split(":")[0]; switch(normResource){ - case "custom-query": + case "custom-query": case "formatted-query": case "generic-query": case "named-query": @@ -1431,7 +1448,7 @@ public class AAIService extends AAIDeclarations implements AAIClient, SvcLogicRe String normResource = resource.split(":")[0]; switch(normResource){ - case "custom-query": + case "custom-query": case "formatted-query": case "generic-query": case "named-query": diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceActivator.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceActivator.java deleted file mode 100755 index fab0ee707..000000000 --- a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceActivator.java +++ /dev/null @@ -1,239 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.sli.adaptors.aai; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import org.onap.ccsdk.sli.core.sli.ConfigurationException; -import org.osgi.framework.BundleActivator; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceRegistration; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class AAIServiceActivator implements BundleActivator { - - private static final String DEFAULT_CONFIG_FILE_NAME = "aaiclient.config"; - private static final String DEFAULT_PROPERTY_FILE_NAME = "aaiclient.properties"; - private static final String DEFAULT_KEYWORD = "default"; - - private static final String SDNC_CONFIG_DIR = "SDNC_CONFIG_DIR"; - - private static final String BVC_PROPERTY_FILE = "/opt/bvc/controller/configuration/aaiclient.properties"; - private static final String DEFAULT_SDNC_PROPERTY_FILE = "/opt/sdnc/data/properties/aaiclient.properties"; - - private Set<ServiceRegistration> registrationSet = new HashSet<ServiceRegistration>(); - - private static final Logger LOG = LoggerFactory.getLogger(AAIServiceActivator.class); - - @Override - public void start(BundleContext ctx) throws Exception { - - System.setProperty("aaiclient.runtime", "OSGI"); - - String sdnConfigDirectory = System.getenv(SDNC_CONFIG_DIR); - - // check SDNC CONFIG DIR system property - if(sdnConfigDirectory == null ) { - LOG.error("System property SDNC_CONFIG_DIR is not defined."); - LOG.info("Defaulting SDNC_CONFIG_DIR to '/opt/sdnc/data/properties/'"); - sdnConfigDirectory = "/opt/sdnc/data/properties/"; - } - - LOG.debug("Configuration directory used : " + sdnConfigDirectory); - - // check existance of properties directory - File configDirectory = new File(sdnConfigDirectory); - if(!configDirectory.exists() || !configDirectory.isDirectory()){ - LOG.error("System property SDNC_CONFIG_DIR = '" + sdnConfigDirectory + "' does not point to a valid directory. AAIService will not be initialized."); - return; - } - - Properties properties = new Properties(); - InputStream input = null; - - // find aaiclient config file - File[] files = findFiles(configDirectory, DEFAULT_CONFIG_FILE_NAME); - - // read the aai config data - if(files != null && files.length > 0) { - LOG.debug("AAIService config file exists and it is named :" + files[0].getAbsolutePath() ); - try { - input = new FileInputStream(files[0]); - properties.load(input); - LOG.debug("Loaded AAI Client properties from " + files[0].getAbsolutePath()); - } catch (IOException exc) { - LOG.warn("Problem loading AAI Client properties from " + files[0].getAbsolutePath(), exc); - } finally { - if(input != null ) { - try { - input.close(); - } catch(Exception exc) { - LOG.error("Failed to close InputStream", exc); - } - } - int size = properties.keySet().size() ; - if(size == 0) { - LOG.debug(files[0].getAbsolutePath() + " contained no entries. Adding the default entry"); - properties.put(DEFAULT_KEYWORD, DEFAULT_PROPERTY_FILE_NAME); - } - } - } else { - LOG.debug("No configuration entries were found. Adding the default entry"); - properties.put(DEFAULT_KEYWORD, DEFAULT_PROPERTY_FILE_NAME); - } - - Set<String> entrySet = properties. stringPropertyNames(); - String value = null; - - // initialize AAI Service for each aai client property files - for(String entry : entrySet) { - value = properties.getProperty(entry); - if(value != null && !value.isEmpty()) { - - final String fileName = value; - - File[] propertyFileList = findFiles(configDirectory, fileName); - - for(File propertiesFile : propertyFileList) { - LOG.info(propertiesFile.getName()); - // Advertise AAI resource adaptor - AAIClient impl = null; - switch(entry) { - case DEFAULT_KEYWORD: - impl = new AAIService(propertiesFile.toURI().toURL()); - break; - case "trinity": - impl = new AAITrinityService(propertiesFile.toURI().toURL()); - break; - default: - LOG.error("Invalid configuration keyword '"+entry+"' detected in aaiclient.config. Aborting initialization"); - continue; - } - String regName = impl.getClass().getName(); - - LOG.debug("Registering AAIService service "+regName); - ServiceRegistration registration = ctx.registerService(regName, impl, null); - registrationSet.add(registration); - - } - } - } - } - -// @Override - @Deprecated - public void start1(BundleContext ctx) throws Exception { - - String sdnConfigDirectory = System.getenv(SDNC_CONFIG_DIR); - String propertiesPath = null; - - if (sdnConfigDirectory == null || sdnConfigDirectory.isEmpty()) { - String filename = DEFAULT_SDNC_PROPERTY_FILE; - File file = new File(filename); - if(file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - filename = BVC_PROPERTY_FILE; - file = new File(filename); - if(file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - throw new ConfigurationException("Cannot find config file - "+filename+" and "+SDNC_CONFIG_DIR+" is unset"); - } - } - } else { - propertiesPath = sdnConfigDirectory + "/aaiclient.properties"; - LOG.info("Environment variable " + SDNC_CONFIG_DIR + " set, - calculated path " + propertiesPath); - } - - File propFile = new File(propertiesPath); - if(!propFile.exists()) { - String filename = DEFAULT_SDNC_PROPERTY_FILE; - File file = new File(filename); - if(file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - filename = BVC_PROPERTY_FILE; - file = new File(filename); - if(file.exists()) { - propertiesPath = filename; - LOG.info("Using property file (1): " + propertiesPath); - } else { - LOG.error("AnAI Service Property file " + propertiesPath + "does not exist."); - throw new ConfigurationException("Cannot find config file - "+propertiesPath+" and " + SDNC_CONFIG_DIR + " is unset."); - } - } - } - - // Advertise AAI resource adaptor - AAIClient impl = new AAIService(propFile.toURI().toURL()); - String regName = impl.getClass().getName(); - - LOG.debug("Registering AAIService service "+regName); - ServiceRegistration registration = ctx.registerService(regName, impl, null); - registrationSet.add(registration); - } - - @Override - public void stop(BundleContext ctx) throws Exception { - - Set<ServiceRegistration> localRegistrationSet = new HashSet<ServiceRegistration>(); - localRegistrationSet.addAll(registrationSet); - - for(ServiceRegistration registration : localRegistrationSet) { - if (registration != null) { - try { - AAIService aaiService = (AAIService)ctx.getService(registration.getReference()); - registration.unregister(); - registrationSet.remove(registration); - if(aaiService != null) { - aaiService.cleanUp(); - } - } catch(Exception exc) { - if(LOG.isDebugEnabled()) - LOG.debug(exc.getMessage()); - } - } - } - } - - private File[] findFiles(File configDirectory, final String filter) { - File[] files = configDirectory.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.equalsIgnoreCase(filter); - } - }); - - return files; - } -} diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceProvider.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceProvider.java new file mode 100755 index 000000000..3450ff747 --- /dev/null +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAIServiceProvider.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * openECOMP : SDN-C + * ================================================================================ + * Copyright (C) 2017 - 2018 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.ccsdk.sli.adaptors.aai; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Optional; +import java.util.Properties; +import java.util.Vector; + +import org.onap.ccsdk.sli.core.utils.JREFileResolver; +import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver; +import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver; +import org.onap.ccsdk.sli.core.utils.common.BundleContextFileResolver; +import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver; +import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Responsible for determining the properties file to use and instantiating the <code>DBResourceManager</code> + * Service. The priority for properties file resolution is as follows: + * + * <ol> + * <li>A directory identified by the system environment variable <code>SDNC_CONFIG_DIR</code></li> + * <li>The default directory <code>DEFAULT_DBLIB_PROP_DIR</code></li> + * <li>A directory identified by the JRE argument <code>dblib.properties</code></li> + * <li>A <code>dblib.properties</code> file located in the karaf root directory</li> + * </ol> + */ +public class AAIServiceProvider implements UtilsProvider { + + private static final Logger LOG = LoggerFactory.getLogger(AAIServiceProvider.class); + + /** + * The name of the properties file for database configuration + */ + private static final String AAISEERVICE_PROP_FILE_NAME = "aaiclient.properties"; + + /** + * A prioritized list of strategies for resolving dblib properties files. + */ + private Vector<PropertiesFileResolver> dblibPropertiesFileResolvers = new Vector(); + + /** + * The configuration properties for the db connection. + */ + private Properties properties; + + /** + * Set up the prioritized list of strategies for resolving dblib properties files. + */ + public AAIServiceProvider() { + dblibPropertiesFileResolvers.add(new JREFileResolver( + "Using property file (1) from JRE argument", AAIServiceProvider.class + )); + dblibPropertiesFileResolvers.add(new BundleContextFileResolver( + "Using property file (1) from JRE argument", AAIServiceProvider.class + )); + dblibPropertiesFileResolvers.add(new SdncConfigEnvVarFileResolver( + "Using property file (2) from environment variable" + )); + dblibPropertiesFileResolvers.add(new KarafRootFileResolver( + "Using property file (4) from karaf root", this + )); + dblibPropertiesFileResolvers.add(new CoreDefaultFileResolver( + "Using property file (3) from default directory" + )); + + // determines properties file as according to the priority described in the class header comment + final File propertiesFile = determinePropertiesFile(); + if (propertiesFile != null) { + try(FileInputStream fileInputStream = new FileInputStream(propertiesFile)) { + properties = new Properties(); + properties.load(fileInputStream); + } catch (final IOException e) { + LOG.error("Failed to load properties for file: {}", propertiesFile.toString(), + new AAIServiceException("Failed to load properties for file: " + + propertiesFile.toString(), e)); + } + } + } + + /** + * Extract db config properties. + * + * @return the db config properties + */ + public Properties getProperties() { + return properties; + } + + /** + * Reports the method chosen for properties resolution to the <code>Logger</code>. + * + * @param message Some user friendly message + * @param fileOptional The file location of the chosen properties file + * @return the file location of the chosen properties file + */ + private static File reportSuccess(final String message, final Optional<File> fileOptional) { + if(fileOptional.isPresent()) { + final File file = fileOptional.get(); + LOG.info("{} {}", message, file.getPath()); + return file; + } + return null; + } + + /** + * Reports fatal errors. This is the case in which no properties file could be found. + * + * @param message An appropriate fatal error message + * @param dblibConfigurationException An exception describing what went wrong during resolution + */ + private static void reportFailure(final String message, + final AAIServiceException dblibConfigurationException) { + + LOG.error("{}", message, dblibConfigurationException); + } + + /** + * Determines the dblib properties file to use based on the following priority: + * <ol> + * <li>A directory identified by the system environment variable <code>SDNC_CONFIG_DIR</code></li> + * <li>The default directory <code>DEFAULT_DBLIB_PROP_DIR</code></li> + * <li>A directory identified by the JRE argument <code>dblib.properties</code></li> + * <li>A <code>dblib.properties</code> file located in the karaf root directory</li> + * </ol> + */ + File determinePropertiesFile() { + + for (final PropertiesFileResolver dblibPropertiesFileResolver : dblibPropertiesFileResolvers) { + final Optional<File> fileOptional = dblibPropertiesFileResolver.resolveFile(AAISEERVICE_PROP_FILE_NAME); + if (fileOptional.isPresent()) { + return reportSuccess(dblibPropertiesFileResolver.getSuccessfulResolutionMessage(), fileOptional); + } + } + + reportFailure("Missing configuration properties resource(3)", + new AAIServiceException("Missing configuration properties resource(3): " + + AAISEERVICE_PROP_FILE_NAME)); + return null; + } +} diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAITrinityService.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAITrinityService.java index 8b273df73..6c627ff6a 100644 --- a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAITrinityService.java +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/AAITrinityService.java @@ -3,14 +3,14 @@ * openECOMP : SDN-C * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. + * 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. @@ -21,18 +21,16 @@ package org.onap.ccsdk.sli.adaptors.aai; -import java.net.URL; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AAITrinityService extends AAIService { - - private static final Logger LOG = LoggerFactory.getLogger(AAITrinityService.class); - public AAITrinityService(URL propURL) { - super(propURL); - LOG.info("Entered AAITrinityService.ctor"); - } + private static final Logger LOG = LoggerFactory.getLogger(AAITrinityService.class); + + public AAITrinityService(UtilsProvider configuration) { + super(configuration); + LOG.info("Entered AAITrinityService.ctor"); + } } diff --git a/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/UtilsProvider.java b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/UtilsProvider.java new file mode 100755 index 000000000..c89e35b2c --- /dev/null +++ b/aai-service/provider/src/main/java/org/onap/ccsdk/sli/adaptors/aai/UtilsProvider.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * onap + * ================================================================================ + * Copyright (C) 2016 - 2017 ONAP + * ================================================================================ + * 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.ccsdk.sli.adaptors.aai; + +import java.util.Properties; + +/** + * @author Rich Tabedzki + * + */ +public interface UtilsProvider { + /** + * Extract configuration properties. + * + * @return the configuration properties + */ + Properties getProperties(); +} diff --git a/aai-service/provider/src/main/resources/org/opendaylight/blueprint/aaiservice-blueprint.xml b/aai-service/provider/src/main/resources/org/opendaylight/blueprint/aaiservice-blueprint.xml new file mode 100755 index 000000000..970936610 --- /dev/null +++ b/aai-service/provider/src/main/resources/org/opendaylight/blueprint/aaiservice-blueprint.xml @@ -0,0 +1,39 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + ============LICENSE_START======================================================= + openECOMP : SDN-C + ================================================================================ + Copyright (C) 2017 - 2018 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========================================================= + --> + +<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0" + xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0" + odl:use-default-for-reference-types="true"> + + <bean id="provider" class="org.onap.ccsdk.sli.adaptors.aai.AAIServiceProvider" /> + + <bean id="aaiService" class="org.onap.ccsdk.sli.adaptors.aai.AAIService"> + <argument ref="provider" /> + </bean> + <service ref="aaiService"> + <interfaces> + <value>org.onap.ccsdk.sli.adaptors.aai.AAIService</value> + <value>org.onap.ccsdk.sli.adaptors.aai.AAIClient</value> + </interfaces> + </service> + +</blueprint> diff --git a/aai-service/provider/src/test/java/org/onap/ccsdk/sli/adaptors/aai/r1607/R1607AutoGeneratedTest.java b/aai-service/provider/src/test/java/org/onap/ccsdk/sli/adaptors/aai/r1607/R1607AutoGeneratedTest.java deleted file mode 100755 index e0f201230..000000000 --- a/aai-service/provider/src/test/java/org/onap/ccsdk/sli/adaptors/aai/r1607/R1607AutoGeneratedTest.java +++ /dev/null @@ -1,491 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * openECOMP : SDN-C - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights - * reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.ccsdk.sli.adaptors.aai.r1607; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.xml.bind.SchemaOutputResolver; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.transform.Result; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.StringUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; -import org.onap.ccsdk.sli.adaptors.aai.AAIClient; -import org.onap.ccsdk.sli.adaptors.aai.AAIDeclarations; -import org.onap.ccsdk.sli.adaptors.aai.AAIRequest; -import org.onap.ccsdk.sli.adaptors.aai.AAIService; -import org.onap.ccsdk.sli.adaptors.aai.data.AAIDatum; -import org.openecomp.aai.inventory.v11.GenericVnf; -import org.openecomp.aai.inventory.v11.InventoryResponseItems; -import org.onap.ccsdk.sli.core.sli.SvcLogicContext; -import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.databind.ObjectMapper; - - - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class R1607AutoGeneratedTest { - - private static final Logger LOG = LoggerFactory.getLogger(R1607AutoGeneratedTest.class); - - protected static AAIClient client; - - protected Map<String, String> cache = new HashMap<String, String>(); - - @BeforeClass - public static void setUp() throws Exception { -// super.setUp(); - URL url = AAIService.class.getResource(AAIService.AAICLIENT_PROPERTIES); -// client = new AAIService(url); - LOG.info("\nTaicAAIResourceTest.setUp\n"); - } - - @AfterClass - public static void tearDown() throws Exception { -// super.tearDown(); - client = null; - LOG.info("----------------------- AAIResourceTest.tearDown -----------------------"); - } - - -// @Test - public void test01AutoGeneratedRequest() { - - String[] requestDefinition = { - "query|generic-vnf|generic-vnf.vnf-id:assign:value:bnfm0001v-1147" - }; - - for(String line : requestDefinition){ - // parse request line resource | key structure - String[] segments = line.split("\\|"); - String action = segments[0]; - String resource = segments[1]; - String[] tmpKeys = segments[2].split("&"); - - - String localId = null; - - List<String> keys = new ArrayList<String>(); - String keyLine = null; - - for(String instruction : tmpKeys) { - String[] parts = instruction.split(":"); - String identifier = parts[0]; - String method = parts[2]; - - if(identifier.startsWith(resource)) { - localId = identifier; - } else if(identifier.startsWith("l-interface") && "l2-bridge-bgf".equals(resource)) { - localId = identifier; - } else if(identifier.startsWith("l-interface") && "l2-bridge-sbg".equals(resource)) { - localId = identifier; - } - - switch(parts[1]) { - case "assign": - String postProcesss = parts[3]; - keyLine = processAssign(identifier, method, postProcesss); - if(keyLine != null && !keyLine.trim().isEmpty()) { - keys.add(keyLine); - } - break; - case "cached": - keyLine = processCached(identifier, method); - if(keyLine != null && !keyLine.trim().isEmpty()) { - keys.add(keyLine); - } - break; - } - - } - - switch(action){ - case "save": - List<String> x = Arrays.asList(localId.split("\\.")); - - testAutoGeneratedSaveRequest(resource, keys, x.get(x.size() - 1), cache.get(localId)); - break; - case "query": - test03AutoGeneratedQueryRequest(resource, keys); - break; - case "delete": - test03AutoGeneratedDeleteRequest(resource, keys); - break; - } - } - - LOG.info("done"); - } - - - public void testAutoGeneratedSaveRequest(String resource, List<String> requestKeys, String identifier, String idValue) { - LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); - - try - { - Map<String, String> nameValues = keyToHashMap(StringUtils.join(requestKeys, " AND "), new SvcLogicContext()); - AAIRequest request = AAIRequest.createRequest(resource, nameValues); - Class<AAIDatum> resourceClass = (Class<AAIDatum>) (request==null ? GenericVnf.class : request.getModelClass()); - - Map<String, String> data = new HashMap<String, String>(); - - for(Field field : resourceClass.getDeclaredFields()) { - String type = field.getType().getName(); - if(type.startsWith("java.lang.")){ - Annotation[] fieldAnnotations = field.getAnnotations(); - for(int i = 0; i < fieldAnnotations.length; i++) { - Annotation a = fieldAnnotations[i]; - if(a instanceof JsonProperty){ - JsonProperty pa = (JsonProperty)a; - String name = pa.value(); - String value; - switch(type) { - case "java.lang.Integer": - case "java.lang.Long": - value = RandomStringUtils.random(6, false, true); - break; - case "java.lang.Boolean": - value = "false"; - break; - default: - if(name.equals(identifier)) { - value = idValue; - } else { - value = RandomStringUtils.random(10, true, false); - } - } - data.put(name, value); - } else - if(a instanceof javax.xml.bind.annotation.XmlElement) { - XmlElement xe = (XmlElement)a; - String name = xe.name(); - if("link-type".equals(name)){ - data.put(name, "roadmTail"); - continue; - } - if("operational-status".equals(name)){ - data.put(name, "available"); - continue; - } - String value; - switch(type) { - case "java.lang.Integer": - case "java.lang.Long": - value = RandomStringUtils.random(6, false, true); - break; - case "java.lang.Boolean": - value = "false"; - break; - default: - if(name.equals(identifier)) { - value = idValue; - } else { - value = RandomStringUtils.random(10, true, false); - } - } - data.put(name, value); - } - } - } - } - - SvcLogicContext ctx = new SvcLogicContext(); - - data.remove("resource-version"); - - QueryStatus resp = null; - - //(String resource, boolean force, boolean localOnly, String key, Map<String, String> parms, String prefix, SvcLogicContext ctx) - resp = client.save(resource, false, false, StringUtils.join(requestKeys, " AND "), data, "aaidata", ctx); - } - catch (Throwable e) - { - LOG.error("Caught exception", e); - fail("Caught exception"); - } - } - - public void test03AutoGeneratedQueryRequest(String resource, List<String> requestKeys) { - LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); - - SvcLogicContext ctx = new SvcLogicContext(); - try - { - - QueryStatus response = null; - - response = client.query(resource, false, null, StringUtils.join(requestKeys, " AND "), "aaiTest", null, ctx); - } - catch (Throwable e) - { - LOG.error("Caught exception", e); - fail("Caught exception"); - } - } - - - public void test03AutoGeneratedDeleteRequest(String resource, List<String> requestKeys) { - LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); - - try - { - SvcLogicContext ctx = new SvcLogicContext(); - - QueryStatus response = null; - - response = client.delete(resource, StringUtils.join(requestKeys, " AND "), ctx); - } - catch (Throwable e) - { - LOG.error("Caught exception", e); - fail("Caught exception"); - } - } - - static ArrayList<Method> findSetters(Class<?> c) { - ArrayList<Method> list = new ArrayList<Method>(); - Method[] methods = c.getDeclaredMethods(); - for (Method method : methods) - if (isGetter(method)) - list.add(method); - return list; - } - - - public static boolean isGetter(Method method) { - if (Modifier.isPublic(method.getModifiers()) && - method.getParameterTypes().length == 0) { - if (method.getName().matches("^get[A-Z].*") && - !method.getReturnType().equals(void.class)) - return true; - if (method.getName().matches("^is[A-Z].*") && - method.getReturnType().equals(boolean.class)) - return true; - } - return false; - } - - public static boolean isSetter(Method method) { - return Modifier.isPublic(method.getModifiers()) && - method.getReturnType().equals(void.class) && - method.getParameterTypes().length == 1 && - method.getName().matches("^set[A-Z].*"); - } - - private String processAssign(String identifier, String method, String postProcess) { - String value = null; - if("uuid".equals(method)) { - value = UUID.randomUUID().toString(); - } - - if("cache".equals(postProcess)) { - cache.put(identifier, value); - } - - if("value".equals(method)) { - cache.put(identifier, postProcess); - value = postProcess; - } - - String key = String.format("%s = '%s'", identifier, value); - return key; - } - - private String processCached(String identifier, String method) { - String value = cache.get(identifier); - - String key = String.format("%s = '%s'", identifier, value); - return key; - } - - protected HashMap<String,String> keyToHashMap(String key, SvcLogicContext ctx) { - if (key == null) { - return (null); - } - - LOG.debug("Converting key [" + key + "] to where clause"); - - if (key.startsWith("'") && key.endsWith("'")) { - key = key.substring(1, key.length() - 1); - - LOG.debug("Stripped outer single quotes - key is now [" + key + "]"); - } - - String[] keyTerms = key.split("\\s+"); - - StringBuffer whereBuff = new StringBuffer(); - String term1 = null; - String op = null; - String term2 = null; - HashMap<String, String> results = new HashMap<String, String>(); - - for (int i = 0; i < keyTerms.length; i++) { - if (term1 == null) { - if ("and".equalsIgnoreCase(keyTerms[i]) - || "or".equalsIgnoreCase(keyTerms[i])) { - // Skip over ADD/OR - } else { - term1 = resolveTerm(keyTerms[i], ctx); - } - } else if (op == null) { - if ("==".equals(keyTerms[i])) { - op = "="; - } else { - op = keyTerms[i]; - } - } else { - term2 = resolveTerm(keyTerms[i], ctx); - term2 = term2.trim().replace("'", "").replace("$", "").replace("'", ""); - results.put(term1, term2); - - term1 = null; - op = null; - term2 = null; - } - } - - return (results); - } - - private String resolveTerm(String term, SvcLogicContext ctx) { - if (term == null) { - return (null); - } - - LOG.debug("resolveTerm: term is " + term); - - if (term.startsWith("$") && (ctx != null)) { - // Resolve any index variables. - - return ("'" + resolveCtxVariable(term.substring(1), ctx) + "'"); - } else if (term.startsWith("'") || term.startsWith("\"")) { - return (term); - } else { - return (term.replaceAll("-", "_")); - - } - - } - - private String resolveCtxVariable(String ctxVarName, SvcLogicContext ctx) { - - if (ctxVarName.indexOf('[') == -1) { - // Ctx variable contains no arrays - return (ctx.getAttribute(ctxVarName)); - } - - // Resolve any array references - StringBuffer sbuff = new StringBuffer(); - String[] ctxVarParts = ctxVarName.split("\\["); - sbuff.append(ctxVarParts[0]); - for (int i = 1; i < ctxVarParts.length; i++) { - if (ctxVarParts[i].startsWith("$")) { - int endBracketLoc = ctxVarParts[i].indexOf("]"); - if (endBracketLoc == -1) { - // Missing end bracket ... give up parsing - LOG.warn("Variable reference " + ctxVarName - + " seems to be missing a ']'"); - return (ctx.getAttribute(ctxVarName)); - } - - String idxVarName = ctxVarParts[i].substring(1, endBracketLoc); - String remainder = ctxVarParts[i].substring(endBracketLoc); - - sbuff.append("["); - sbuff.append(ctx.getAttribute(idxVarName)); - sbuff.append(remainder); - - } else { - // Index is not a variable reference - sbuff.append("["); - sbuff.append(ctxVarParts[i]); - } - } - - return (ctx.getAttribute(sbuff.toString())); - } - -// @Test - public void test04VceDataPost() { - LOG.info("----------------------- Test: " + new Object(){}.getClass().getEnclosingMethod().getName() + " -----------------------"); - - try - { - URL resource = this.getClass().getResource("/json/tails4.json"); - - LOG.info("Resource is " + resource.getFile()); - File requestFile = new File(resource.getFile()); - if(!requestFile.exists()) { - fail("Test file does not exist"); - } - SvcLogicContext ctx = new SvcLogicContext(); - ObjectMapper mapper = AAIService.getObjectMapper(); - InventoryResponseItems request = mapper.readValue(requestFile, InventoryResponseItems.class); - Map<String, Object> subnetsList = mapper.convertValue(request, Map.class); - AAIDeclarations.class.cast(client).writeMap(subnetsList, "aaiTmp", ctx); - assertNotNull(request); - - } - catch (Exception e) - { - LOG.error("Caught exception", e); - fail("Caught exception"); - } - } - - - static class MySchemaOutputResolver extends SchemaOutputResolver { - - public Result createOutput(String namespaceURI, String suggestedFileName) throws IOException { - File file = new File(suggestedFileName); - StreamResult result = new StreamResult(file); - result.setSystemId(file.getAbsolutePath()); - return result; - } - - } -} |