diff options
author | Venkata Harish K Kajur <vk250x@att.com> | 2018-01-30 13:52:34 -0500 |
---|---|---|
committer | Venkata Harish K Kajur <vk250x@att.com> | 2018-02-28 11:36:08 -0500 |
commit | 4f13d6cc64eed0ef75a31ec5f490853267447ab1 (patch) | |
tree | cb7066e12fc39038cc99b74bbeba879c9eb6ca8c /aai-resources/src/test | |
parent | 73539cae6d24e352b84a6411e523da734fbc19e2 (diff) |
Turn ajsc 2 to using ajsc 6 spring boot
Issue-ID: AAI-800
Change-Id: Id174ec5088ddea57f18e605d004c417bee8fbf33
Signed-off-by: Venkata Harish K Kajur <vk250x@att.com>
Diffstat (limited to 'aai-resources/src/test')
20 files changed, 949 insertions, 1089 deletions
diff --git a/aai-resources/src/test/java/org/onap/aai/AAISetup.java b/aai-resources/src/test/java/org/onap/aai/AAISetup.java index 05864fd..d3b5abe 100644 --- a/aai-resources/src/test/java/org/onap/aai/AAISetup.java +++ b/aai-resources/src/test/java/org/onap/aai/AAISetup.java @@ -35,9 +35,9 @@ public abstract class AAISetup { @BeforeClass public static void setupBundleconfig() throws Exception { - System.setProperty("AJSC_HOME", "."); - System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); - QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "bundleconfig-local/etc/oxm/"); + System.setProperty("AJSC_HOME", "./"); + System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/"); +// QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "bundleconfig-local/etc/oxm/"); } public String getPayload(String filename) throws IOException { diff --git a/aai-resources/src/test/java/org/onap/aai/ResourcesTestConfiguration.java b/aai-resources/src/test/java/org/onap/aai/ResourcesTestConfiguration.java new file mode 100644 index 0000000..f2745c0 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/ResourcesTestConfiguration.java @@ -0,0 +1,125 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.http.client.HttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.ssl.SSLContextBuilder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpStatus; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.util.ResourceUtils; +import org.springframework.web.client.ResponseErrorHandler; +import org.springframework.web.client.RestTemplate; + +import javax.net.ssl.SSLContext; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.KeyStore; + +@TestConfiguration +public class ResourcesTestConfiguration { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ResourcesTestConfiguration.class); + + @Autowired + private Environment env; + + /** + * Create a RestTemplate bean, using the RestTemplateBuilder provided + * by the auto-configuration. + */ + @Bean + RestTemplate restTemplate(RestTemplateBuilder builder) throws Exception { + + char[] trustStorePassword = env.getProperty("server.ssl.trust-store-password").toCharArray(); + char[] keyStorePassword = env.getProperty("server.ssl.key-store-password").toCharArray(); + + String keyStore = env.getProperty("server.ssl.key-store"); + String trustStore = env.getProperty("server.ssl.trust-store"); + + SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); + + if(env.acceptsProfiles("two-way-ssl")){ + sslContextBuilder = sslContextBuilder.loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword); + } + + SSLContext sslContext = sslContextBuilder + .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword) + .build(); + + HttpClient client = HttpClients.custom() + .setSSLContext(sslContext) + .setSSLHostnameVerifier((s, sslSession) -> true) + .build(); + + RestTemplate restTemplate = builder + .requestFactory(new HttpComponentsClientHttpRequestFactory(client)) + .build(); + + restTemplate.setErrorHandler(new ResponseErrorHandler() { + @Override + public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException { + if (clientHttpResponse.getStatusCode() != HttpStatus.OK) { + + logger.debug("Status code: " + clientHttpResponse.getStatusCode()); + + if (clientHttpResponse.getStatusCode() == HttpStatus.FORBIDDEN) { + logger.debug("Call returned a error 403 forbidden resposne "); + return true; + } + + if(clientHttpResponse.getRawStatusCode() % 100 == 5){ + logger.debug("Call returned a error " + clientHttpResponse.getStatusText()); + return true; + } + } + + return false; + } + + @Override + public void handleError(ClientHttpResponse clientHttpResponse) throws IOException { + } + }); + + return restTemplate; + } + + private KeyStore loadPfx(String file, char[] password) throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + File key = ResourceUtils.getFile(file); + try (InputStream in = new FileInputStream(key)) { + keyStore.load(in, password); + } + return keyStore; + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/dbgen/DupeToolTest.java b/aai-resources/src/test/java/org/onap/aai/dbgen/DupeToolTest.java new file mode 100644 index 0000000..3da335b --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/dbgen/DupeToolTest.java @@ -0,0 +1,150 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbgen; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.thinkaurelius.titan.core.TitanTransaction; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.serialization.db.EdgeRules; + +import static org.junit.Assert.*; + + +public class DupeToolTest extends AAISetup { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(DupeToolTest.class); + + private DupeTool dupeTool; + + @Before + public void setup(){ + dupeTool = new DupeTool(); + dupeTool.SHOULD_EXIT_VM = false; + createGraph(); + } + + private void createGraph() { + TitanTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + + EdgeRules edgeRules = EdgeRules.getInstance(); + + boolean success = true; + + try { + + GraphTraversalSource g = transaction.traversal(); + + Vertex cloudRegionVertex = g.addV() + .property("aai-node-type", "cloud-region") + .property("cloud-owner", "test-owner") + .property("cloud-region-id", "test-region") + .property("source-of-truth", "JUNIT") + .next(); + + Vertex tenantVertex = g.addV() + .property("aai-node-type", "tenant") + .property("tenant-id", "test-tenant") + .property("source-of-truth", "JUNIT") + .next(); + + Vertex pserverVertex = g.addV() + .property("aai-node-type", "pserver") + .property("hostname", "test-pserver") + .property("in-maint", false) + .property("source-of-truth", "JUNIT") + .next(); + + for(int i = 0; i < 100; ++i){ + g.addV() + .property("aai-node-type", "pserver") + .property("hostname", "test-pserver") + .property("in-maint", false) + .property("source-of-truth", "JUNIT") + .next(); + } + + edgeRules.addTreeEdge(g, cloudRegionVertex, tenantVertex); + edgeRules.addEdge(g, cloudRegionVertex, pserverVertex); + + } catch(Exception ex){ + success = false; + logger.error("Unable to create the vertexes", ex); + } finally { + if(success){ + transaction.commit(); + } else { + transaction.rollback(); + fail("Unable to setup the graph"); + } + } + } + + @Test + public void testDupeTool(){ + + String[] args = { + "-userId", "testuser", + "-nodeType", "pserver", + "-timeWindowMinutes", "30", + "-autoFix", + "-maxFix", "30", + "-sleepMinutes", "0" + }; + + dupeTool.main(args); + } + + @After + public void tearDown(){ + + TitanTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + boolean success = true; + + try { + + GraphTraversalSource g = transaction.traversal(); + + g.V().has("source-of-truth", "JUNIT") + .toList() + .forEach(v -> v.remove()); + + } catch(Exception ex){ + success = false; + logger.error("Unable to remove the vertexes", ex); + } finally { + if(success){ + transaction.commit(); + } else { + transaction.rollback(); + fail("Unable to teardown the graph"); + } + } + + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/dbgen/ForceDeleteToolTest.java b/aai-resources/src/test/java/org/onap/aai/dbgen/ForceDeleteToolTest.java new file mode 100644 index 0000000..7f78421 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/dbgen/ForceDeleteToolTest.java @@ -0,0 +1,210 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.dbgen; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import com.thinkaurelius.titan.core.TitanTransaction; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Edge; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.After; +import org.junit.Before; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.serialization.db.EdgeRules; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.List; + +import static org.junit.Assert.fail; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class ForceDeleteToolTest extends AAISetup { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ForceDeleteToolTest.class); + + private ForceDeleteTool deleteTool; + + private Vertex cloudRegionVertex; + @Before + public void setup(){ + deleteTool = new ForceDeleteTool(); + deleteTool.SHOULD_EXIT_VM = false; + TitanTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + + EdgeRules edgeRules = EdgeRules.getInstance(); + + boolean success = true; + + try { + + GraphTraversalSource g = transaction.traversal(); + + cloudRegionVertex = g.addV() + .property("aai-node-type", "cloud-region") + .property("cloud-owner", "test-owner") + .property("cloud-region-id", "test-region") + .property("source-of-truth", "JUNIT") + .next(); + + Vertex tenantVertex = g.addV() + .property("aai-node-type", "tenant") + .property("tenant-id", "test-tenant") + .property("source-of-truth", "JUNIT") + .next(); + + Vertex pserverVertex = g.addV() + .property("aai-node-type", "pserver") + .property("hostname", "test-pserver") + .property("in-maint", false) + .property("source-of-truth", "JUNIT") + .next(); + + edgeRules.addTreeEdge(g, cloudRegionVertex, tenantVertex); + edgeRules.addEdge(g, cloudRegionVertex, pserverVertex); + + } catch(Exception ex){ + success = false; + logger.error("Unable to create the vertexes", ex); + } finally { + if(success){ + transaction.commit(); + } else { + transaction.rollback(); + fail("Unable to setup the graph"); + } + } + + + } + + @Test + public void testCollectDataForVertex(){ + + String [] args = { + + "-action", + "COLLECT_DATA", + "-userId", + "someuser", + "-params4Collect", + "cloud-owner|test-owner" + }; + + deleteTool.main(args); + } + + @Test + public void testDeleteNode(){ + + String id = cloudRegionVertex.id().toString(); + + String [] args = { + + "-action", + "DELETE_NODE", + "-userId", + "someuser", + "-vertexId", + id + }; + + deleteTool.main(args); + } + + @Test + public void testCollectDataForEdge(){ + + TitanTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + GraphTraversalSource g = transaction.traversal(); + List<Edge> edges = g.E().toList(); + String cloudRegionToPserverId = edges.get(0).id().toString(); + + String [] args = { + + "-action", + "COLLECT_DATA", + "-userId", + "someuser", + "-edgeId", + cloudRegionToPserverId + }; + + deleteTool.main(args); + } + + @Test + public void testDeleteForEdge(){ + + InputStream systemInputStream = System.in; + ByteArrayInputStream in = new ByteArrayInputStream("y".getBytes()); + System.setIn(in); + TitanTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + GraphTraversalSource g = transaction.traversal(); + List<Edge> edges = g.E().toList(); + String cloudRegionToPserverId = edges.get(0).id().toString(); + + String [] args = { + + "-action", + "DELETE_EDGE", + "-userId", + "someuser", + "-edgeId", + cloudRegionToPserverId + }; + + deleteTool.main(args); + System.setIn(systemInputStream); + } + @After + public void tearDown(){ + + TitanTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction(); + boolean success = true; + + try { + + GraphTraversalSource g = transaction.traversal(); + + g.V().has("source-of-truth", "JUNIT") + .toList() + .forEach(v -> v.remove()); + + } catch(Exception ex){ + success = false; + logger.error("Unable to remove the vertexes", ex); + } finally { + if(success){ + transaction.commit(); + } else { + transaction.rollback(); + fail("Unable to teardown the graph"); + } + } + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSInInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSInInterceptorTest.java deleted file mode 100644 index 01a6788..0000000 --- a/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSInInterceptorTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.interceptors; - -import org.apache.cxf.message.Exchange; -import org.apache.cxf.message.ExchangeImpl; -import org.apache.cxf.message.Message; -import org.junit.Before; -import org.junit.Test; -import org.onap.aai.AAISetup; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Mockito.*; - -public class AAILogJAXRSInInterceptorTest extends AAISetup { - - private AAILogJAXRSInInterceptor aaiLogJAXRSInInterceptor; - - private Message message; - private Exchange exchange; - private InputStream is; - private Map<String, List<String>> headers; - - - @Before - public void setup(){ - - aaiLogJAXRSInInterceptor = new AAILogJAXRSInInterceptor(); - - message = mock(Message.class); - exchange = spy(new ExchangeImpl()); - - is = getClass().getClassLoader().getResourceAsStream("logback.xml"); - - headers = new HashMap<>(); - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("X-TransactionId", Arrays.asList("JUNIT")); - headers.put("Content-Type", Arrays.asList("application/json")); - headers.put("Accept", Arrays.asList("application/json")); - } - - @Test - public void testHandleMessageWhenNotCamelRequest() throws IOException { - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(InputStream.class)).thenReturn(is); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - - when(message.get("CamelHttpUrl")).thenReturn("/somestring"); - aaiLogJAXRSInInterceptor.handleMessage(message); - } - - @Test - public void testHandleMessageWhenUUIDHasMultiple() throws IOException { - - Map<String, List<String>> headers = new HashMap<>(); - - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("X-TransactionId", Arrays.asList("jfasodjf:fjaosjfidsaj:afsidjfaodfja")); - headers.put("Content-Type", Arrays.asList("application/json")); - headers.put("Accept", Arrays.asList("application/json")); - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(InputStream.class)).thenReturn(is); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - - when(message.get("CamelHttpUrl")).thenReturn("/somestring"); - aaiLogJAXRSInInterceptor.handleMessage(message); - } - - @Test - public void testHandleMessageWhenMissingTransactionId() throws IOException { - - Map<String, List<String>> headers = new HashMap<>(); - - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("Content-Type", Arrays.asList("application/json")); - headers.put("Accept", Arrays.asList("application/json")); - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(InputStream.class)).thenReturn(is); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - - when(message.get("CamelHttpUrl")).thenReturn("/somestring"); - aaiLogJAXRSInInterceptor.handleMessage(message); - } - - @Test - public void testHandleMessageWhenMissingContentType() throws IOException { - - Map<String, List<String>> headers = new HashMap<>(); - - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("X-TransactionId", Arrays.asList("jfasodjf:fjaosjfidsaj:afsidjfaodfja")); - headers.put("Accept", Arrays.asList("application/json")); - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(InputStream.class)).thenReturn(is); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - - when(message.get("CamelHttpUrl")).thenReturn("/somestring"); - aaiLogJAXRSInInterceptor.handleMessage(message); - } - - @Test - public void testHandleMessageWhenQueryExistsAndUriEcho() throws IOException { - - Map<String, List<String>> headers = new HashMap<>(); - - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("X-TransactionId", Arrays.asList("jfasodjf:fjaosjfidsaj:afsidjfaodfja")); - headers.put("Content-Type", Arrays.asList("application/json")); - headers.put("Accept", Arrays.asList("application/json")); - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(InputStream.class)).thenReturn(is); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - when(message.get(Message.QUERY_STRING)).thenReturn(null); - when(exchange.containsKey("AAI_LOGGING_HBASE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_HBASE_ENABLED")).thenReturn(""); - when(exchange.containsKey("AAI_LOGGING_TRACE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_TRACE_ENABLED")).thenReturn(""); - when(message.get("CamelHttpUrl")).thenReturn("/util/echo"); - aaiLogJAXRSInInterceptor.handleMessage(message); - } - - @Test - public void testHandleMessageWhenQueryExistsAndUriTranslog() throws IOException { - - Map<String, List<String>> headers = new HashMap<>(); - - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("X-TransactionId", Arrays.asList("jfasodjf:fjaosjfidsaj:afsidjfaodfja")); - headers.put("Content-Type", Arrays.asList("application/json")); - headers.put("Accept", Arrays.asList("application/json")); - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(InputStream.class)).thenReturn(is); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - when(message.get(Message.QUERY_STRING)).thenReturn(null); - when(exchange.containsKey("AAI_LOGGING_HBASE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_HBASE_ENABLED")).thenReturn(""); - when(exchange.containsKey("AAI_LOGGING_TRACE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_TRACE_ENABLED")).thenReturn(""); - when(message.get("CamelHttpUrl")).thenReturn("/translog/"); - aaiLogJAXRSInInterceptor.handleMessage(message); - } - - @Test - public void testHandleMessageWhenPutMessageKeyReturnsException() throws IOException { - - Map<String, List<String>> headers = new HashMap<>(); - - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("X-TransactionId", Arrays.asList("jfasodjf:fjaosjfidsaj:afsidjfaodfja")); - headers.put("Content-Type", Arrays.asList("application/json")); - headers.put("Accept", Arrays.asList("application/json")); - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(InputStream.class)).thenReturn(is); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - when(message.get(Message.QUERY_STRING)).thenReturn(null); - when(exchange.containsKey("AAI_LOGGING_HBASE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_HBASE_ENABLED")).thenReturn(""); - when(exchange.containsKey("AAI_LOGGING_TRACE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_TRACE_ENABLED")).thenReturn(""); - when(message.get("CamelHttpUrl")).thenReturn("/translog/"); - when(message.get(Message.ENCODING)).thenReturn("http"); - when(message.get(Message.RESPONSE_CODE)).thenReturn(200); - - aaiLogJAXRSInInterceptor.handleMessage(message); - } -}
\ No newline at end of file diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSOutInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSOutInterceptorTest.java deleted file mode 100644 index 455aa2c..0000000 --- a/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSOutInterceptorTest.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.interceptors; - -import org.apache.cxf.io.CacheAndWriteOutputStream; -import org.apache.cxf.message.Exchange; -import org.apache.cxf.message.ExchangeImpl; -import org.apache.cxf.message.Message; -import org.junit.Before; -import org.junit.Test; -import org.onap.aai.AAISetup; - -import java.io.IOException; -import java.io.OutputStream; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.mockito.Mockito.*; - -public class AAILogJAXRSOutInterceptorTest extends AAISetup { - - private AAILogJAXRSOutInterceptor aaiLogJAXRSOutInterceptor; - - private Message message; - private Exchange exchange; - private OutputStream out; - private Map<String, List<String>> headers; - private Message outMessage; - private Message inMessage; - - - @Before - public void setup(){ - - aaiLogJAXRSOutInterceptor = new AAILogJAXRSOutInterceptor(); - - message = mock(Message.class); - exchange = spy(new ExchangeImpl()); - out = mock(OutputStream.class); - outMessage = mock(Message.class); - inMessage = mock(Message.class); - - - headers = new HashMap<>(); - headers.put("X-FromAppId", Arrays.asList("JUNIT")); - headers.put("X-TransactionId", Arrays.asList("JUNIT")); - headers.put("Content-Type", Arrays.asList("application/json")); - headers.put("Accept", Arrays.asList("application/json")); - } - - @Test - public void testHandleMessageWhenNotCamelRequest() throws IOException { - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(OutputStream.class)).thenReturn(out); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - when(exchange.getOutMessage()).thenReturn(outMessage); - when(outMessage.getContent(OutputStream.class)).thenReturn(out); - when(exchange.containsKey("AAI_LOGGING_HBASE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_HBASE_ENABLED")).thenReturn(""); - - when(message.get("CamelHttpUrl")).thenReturn("/somestring"); - aaiLogJAXRSOutInterceptor.handleMessage(message); - } - - @Test - public void testLogCallBack(){ - - when(message.getExchange()).thenReturn(exchange); - when(message.getContent(OutputStream.class)).thenReturn(out); - when(message.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(message.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - when(exchange.getOutMessage()).thenReturn(outMessage); - - when(outMessage.getContent(OutputStream.class)).thenReturn(out); - when(exchange.containsKey("AAI_LOGGING_HBASE_ENABLED")).thenReturn(true); - when(exchange.remove("AAI_LOGGING_HBASE_ENABLED")).thenReturn(""); - when(exchange.getInMessage()).thenReturn(inMessage); - - when(inMessage.getExchange()).thenReturn(exchange); - when(inMessage.getContent(OutputStream.class)).thenReturn(out); - when(inMessage.get(Message.PROTOCOL_HEADERS)).thenReturn(headers); - when(inMessage.get(Message.CONTENT_TYPE)).thenReturn("*/*"); - - AAILogJAXRSOutInterceptor.LoggingCallback loggingCallback = new AAILogJAXRSOutInterceptor().new LoggingCallback(message, out); - final CacheAndWriteOutputStream newOut = new CacheAndWriteOutputStream(out); - loggingCallback.onClose(newOut); - } - -}
\ No newline at end of file diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/PostAaiAjscInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/PostAaiAjscInterceptorTest.java deleted file mode 100644 index a1e0259..0000000 --- a/aai-resources/src/test/java/org/onap/aai/interceptors/PostAaiAjscInterceptorTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.interceptors; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.aai.logging.LoggingContext; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public class PostAaiAjscInterceptorTest { - - private PostAaiAjscInterceptor postAaiAjscInterceptor; - - @Before - public void setup(){ - postAaiAjscInterceptor = new PostAaiAjscInterceptor(); - } - - @Test - public void getInstance() throws Exception { - PostAaiAjscInterceptor interceptor = PostAaiAjscInterceptor.getInstance(); - assertNotNull(interceptor); - } - - @Test - public void testAllowOrRejectIfSuccess() throws Exception { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse resp = Mockito.mock(HttpServletResponse.class); - resp.setStatus(HttpServletResponse.SC_OK); - LoggingContext.put(LoggingContext.LoggingField.RESPONSE_CODE.toString(), "0"); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("/fadsjoifj")); - - boolean success = postAaiAjscInterceptor.allowOrReject(request, resp, null); - - assertTrue("Expecting the post interceptor to return success regardless", success); - } - - @Test - public void testAllowOrRejectIfFailure() throws Exception { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse resp = Mockito.mock(HttpServletResponse.class); - resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); - LoggingContext.put(LoggingContext.LoggingField.RESPONSE_CODE.toString(), "400"); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("/fadsjoifj")); - - boolean success = postAaiAjscInterceptor.allowOrReject(request, resp, null); - - assertTrue("Expecting the post interceptor to return success regardless", success); - } -} diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/PreAaiAjscInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/PreAaiAjscInterceptorTest.java deleted file mode 100644 index 35651c3..0000000 --- a/aai-resources/src/test/java/org/onap/aai/interceptors/PreAaiAjscInterceptorTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.interceptors; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; - -import javax.servlet.http.HttpServletRequest; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Matchers.anyString; - -public class PreAaiAjscInterceptorTest { - - private PreAaiAjscInterceptor preAaiAjscInterceptor; - - @Before - public void setup(){ - preAaiAjscInterceptor = new PreAaiAjscInterceptor(); - } - - @Test - public void getInstance() throws Exception { - PreAaiAjscInterceptor interceptor = PreAaiAjscInterceptor.getInstance(); - assertNotNull(interceptor); - } - - @Test - public void testAllowOrRejectIfSuccess() throws Exception { - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - Mockito.when(request.getRequestURI()).thenReturn("/fadsjoifj"); - Mockito.when(request.getHeader(anyString())).thenReturn("JUNIT-Test"); - Mockito.when(request.getMethod()).thenReturn("GET"); - - boolean success = preAaiAjscInterceptor.allowOrReject(request, null, null); - - assertTrue("Expecting the post interceptor to return success regardless", success); - } - -}
\ No newline at end of file diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java index 747f319..f85eeb8 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java @@ -154,6 +154,8 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { Response response = legacyMoxyConsumer.getLegacy(
"",
+ "-1",
+ "-1",
Version.getLatest().toString(),
uri,
"all",
@@ -187,6 +189,8 @@ public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction { queryParameters.add("depth", "10000");
response = legacyMoxyConsumer.getLegacy(
"",
+ "-1",
+ "-1",
Version.getLatest().toString(),
uri,
"all",
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java index 8c14697..260e2ae 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java @@ -140,6 +140,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); Response response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -172,6 +174,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "10000", @@ -216,6 +220,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -361,6 +367,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { mockReq = new MockHttpServletRequest("GET", uri); response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -417,7 +425,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { int code = response.getStatus(); System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); response = legacyMoxyConsumer.updateRelationship( payload, @@ -430,11 +438,13 @@ public class LegacyMoxyConsumerTest extends AAISetup { code = response.getStatus(); System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); mockReq = new MockHttpServletRequest("GET", uri); response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -445,7 +455,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { ); assertNotNull("Response from the legacy moxy consumer returned null", response); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); mockReq = new MockHttpServletRequest("DELETE", uri); queryParameters.add("resource-version", "3434394839483"); @@ -471,7 +481,7 @@ public class LegacyMoxyConsumerTest extends AAISetup { mockReq ); code = response.getStatus(); - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); } @Test @@ -491,6 +501,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { MockHttpServletRequest mockReq = new MockHttpServletRequest("GET", uri); Response response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -550,6 +562,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); Response response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -584,6 +598,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { queryParameters.add("depth", "10000"); response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -697,6 +713,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); Response response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", @@ -724,6 +742,8 @@ public class LegacyMoxyConsumerTest extends AAISetup { MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); Response response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java new file mode 100644 index 0000000..b5ea4d9 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java @@ -0,0 +1,115 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.jayway.jsonpath.JsonPath; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.aai.ResourcesApp; +import org.onap.aai.ResourcesTestConfiguration; +import org.onap.aai.config.PropertyPasswordConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.embedded.LocalServerPort; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; +import org.springframework.http.*; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.client.RestTemplate; + +import java.util.Collections; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; + +/** + * A sample junit test using spring boot that provides the ability to spin + * up the application from the junit layer and run rest requests against + * SpringBootTest annotation with web environment requires which spring boot + * class to load and the random port starts the application on a random port + * and injects back into the application for the field with annotation LocalServerPort + * <p> + * + * This can be used to potentially replace a lot of the fitnesse tests since + * they will be testing against the same thing except fitnesse uses hbase + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ResourcesApp.class) +@TestPropertySource(locations = "classpath:application-test.properties") +@ContextConfiguration(initializers = PropertyPasswordConfiguration.class) +@Import(ResourcesTestConfiguration.class) +public class PserverTest { + + @Autowired + RestTemplate restTemplate; + + @LocalServerPort + int randomPort; + + private HttpEntity httpEntity; + + private String baseUrl; + + @Before + public void setup(){ + + HttpHeaders headers = new HttpHeaders(); + + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setContentType(MediaType.APPLICATION_JSON); + headers.add("Real-Time", "true"); + headers.add("X-FromAppId", "JUNIT"); + headers.add("X-TransactionId", "JUNIT"); + + httpEntity = new HttpEntity(headers); + baseUrl = "https://localhost:" + randomPort; + } + + @Test + public void testPutPserverExtractVertexAndThenDoGetByVertexIdAndThenDeleteIt() { + + String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/test" + UUID.randomUUID().toString(); + + ResponseEntity responseEntity = null; + + responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class); + assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode()); + + responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class); + assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode()); + + String vertexId = responseEntity.getHeaders().getFirst("vertex-id"); + responseEntity = restTemplate.exchange(baseUrl + "/aai/v11/resources/id/" + vertexId, HttpMethod.GET, httpEntity, String.class); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + + responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class); + assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); + + String body = responseEntity.getBody().toString(); + String resourceVersion = JsonPath.read(body, "$.resource-version"); + + responseEntity = restTemplate.exchange(baseUrl + endpoint+ "?resource-version=" + resourceVersion, HttpMethod.DELETE, httpEntity, String.class); + assertEquals(HttpStatus.NO_CONTENT, responseEntity.getStatusCode()); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java index 982cedf..f732a6d 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java @@ -129,6 +129,8 @@ public class URLFromVertexIdConsumerTest extends AAISetup { MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); Response response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", diff --git a/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java index fb639ce..aab2470 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java @@ -129,6 +129,8 @@ public class VertexIdConsumerTest extends AAISetup { MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri); Response response = legacyMoxyConsumer.getLegacy( "", + "-1", + "-1", Version.getLatest().toString(), uri, "all", diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java index 66846b6..50964a3 100644 --- a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java +++ b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java @@ -26,6 +26,7 @@ import com.att.eelf.configuration.EELFManager; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; +import org.onap.aai.AAISetup; import org.onap.aai.introspection.Version; import javax.ws.rs.core.*; @@ -36,7 +37,7 @@ import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.anyObject; import static org.mockito.Mockito.when; -public abstract class RetiredConsumerTest { +public abstract class RetiredConsumerTest extends AAISetup { protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); diff --git a/aai-resources/src/test/java/org/onap/aai/schema/db/AuditOXMTest.java b/aai-resources/src/test/java/org/onap/aai/schema/db/AuditOXMTest.java deleted file mode 100644 index d3c7302..0000000 --- a/aai-resources/src/test/java/org/onap/aai/schema/db/AuditOXMTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.schema.db; - -import com.thinkaurelius.titan.core.TitanFactory; -import com.thinkaurelius.titan.core.TitanGraph; -import org.codehaus.jackson.JsonGenerationException; -import org.codehaus.jackson.map.JsonMappingException; -import org.codehaus.jackson.map.ObjectMapper; -import org.junit.Ignore; -import org.junit.Test; -import org.onap.aai.AAISetup; -import org.onap.aai.db.schema.AuditDoc; -import org.onap.aai.db.schema.AuditOXM; -import org.onap.aai.db.schema.Auditor; -import org.onap.aai.db.schema.AuditorFactory; -import org.onap.aai.introspection.Version; - -import java.io.IOException; - -@Ignore("not ready for testing") -public class AuditOXMTest extends AAISetup { - - - /** - * Gets the graph audit. - * - * @return the graph audit - * @throws JsonGenerationException the json generation exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void getGraphAudit() throws JsonGenerationException, JsonMappingException, IOException { - TitanGraph graph = TitanFactory.open("bundleconfig-local/etc/appprops/aaiconfig.properties"); - Auditor a = AuditorFactory.getGraphAuditor(graph); - AuditDoc doc = a.getAuditDoc(); - - ObjectMapper mapper = new ObjectMapper(); - - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); - System.out.println(json); - - } - - /** - * Gets the audit. - * - * @return the audit - * @throws JsonGenerationException the json generation exception - * @throws JsonMappingException the json mapping exception - * @throws IOException Signals that an I/O exception has occurred. - */ - @Test - public void getAudit() throws JsonGenerationException, JsonMappingException, IOException { - AuditOXM oxm = new AuditOXM(Version.v8); - - AuditDoc doc = oxm.getAuditDoc(); - - ObjectMapper mapper = new ObjectMapper(); - - String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); - System.out.println(json); - } -} diff --git a/aai-resources/src/test/java/org/onap/aai/serialization/db/DBSerializerMaxRetryTest.java b/aai-resources/src/test/java/org/onap/aai/serialization/db/DBSerializerMaxRetryTest.java deleted file mode 100644 index b64c261..0000000 --- a/aai-resources/src/test/java/org/onap/aai/serialization/db/DBSerializerMaxRetryTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * 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.aai.serialization.db; - - -import com.att.eelf.configuration.EELFLogger; -import com.thinkaurelius.titan.core.TitanException; -import com.thinkaurelius.titan.core.TitanGraph; -import com.thinkaurelius.titan.core.TitanTransaction; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.onap.aai.db.props.AAIProperties; -import org.onap.aai.exceptions.AAIException; -import org.onap.aai.introspection.LoaderFactory; -import org.onap.aai.parsers.query.QueryParser; -import org.onap.aai.rest.db.HttpEntry; -import org.onap.aai.serialization.engines.TransactionalGraphEngine; -import org.onap.aai.serialization.engines.query.QueryEngine; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -@Ignore -@RunWith(PowerMockRunner.class) -@PrepareForTest({QueryParser.class, TransactionalGraphEngine.class, TitanGraph.class, TitanTransaction.class, LoaderFactory.class, DBSerializer.class}) -public class DBSerializerMaxRetryTest { - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * Test. - * - * @throws Exception the exception - */ - @Test - public void test() throws Exception { - - HttpEntry mockEntry = PowerMockito.mock(HttpEntry.class); - QueryParser mockQuery = PowerMockito.mock(QueryParser.class); - PowerMockito.when(mockQuery.isDependent()).thenReturn(true); - TransactionalGraphEngine mockEngine = PowerMockito.mock(TransactionalGraphEngine.class); - TitanGraph mockGraph = PowerMockito.mock(TitanGraph.class); - //PowerMockito.when(mockEngine.getGraph()).thenReturn(mockGraph); - TitanTransaction mockGraphTrans = PowerMockito.mock(TitanTransaction.class); - PowerMockito.when(mockGraph.newTransaction()).thenReturn(mockGraphTrans); - QueryEngine mockQueryEngine = PowerMockito.mock(QueryEngine.class); - PowerMockito.when(mockEngine.getQueryEngine()).thenReturn(mockQueryEngine); - PowerMockito.when(mockQuery.getQueryBuilder().getParentQuery().toList()).thenThrow(new TitanException("mock error")); - EELFLogger mockLogger = PowerMockito.mock(EELFLogger.class); - - PowerMockito.whenNew(EELFLogger.class).withAnyArguments().thenReturn(mockLogger); - - PowerMockito.mockStatic(LoaderFactory.class); - - DBSerializer dbs = new DBSerializer(AAIProperties.LATEST, mockEngine, null, null); - - thrown.expect(AAIException.class); - thrown.expectMessage("AAI_6134"); - dbs.serializeToDb(null, null, mockQuery, null, null); - } - -} diff --git a/aai-resources/src/test/java/org/onap/aai/util/AAIAppServletContextListenerTest.java b/aai-resources/src/test/java/org/onap/aai/util/AAIAppServletContextListenerTest.java deleted file mode 100644 index c079007..0000000 --- a/aai-resources/src/test/java/org/onap/aai/util/AAIAppServletContextListenerTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.util; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.PatternLayout; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.AppenderBase; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.onap.aai.dbmap.AAIGraph; -import org.onap.aai.logging.ErrorLogHelper; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.agent.PowerMockAgent; -import org.powermock.modules.junit4.rule.PowerMockRule; -import org.slf4j.LoggerFactory; - -import javax.servlet.ServletContextEvent; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertTrue; - -@PrepareForTest({AAIGraph.class, AAIConfig.class, ErrorLogHelper.class}) -public class AAIAppServletContextListenerTest { - - @Rule - public PowerMockRule rule = new PowerMockRule(); - - static { - PowerMockAgent.initializeIfNeeded(); - } - - private ServletContextEvent arg; - private AAIAppServletContextListener listener; - - /** - * Initialize. - */ - @Before - @PrepareForTest({AAIGraph.class, AAIConfig.class, ErrorLogHelper.class}) - public void initialize(){ - arg = PowerMockito.mock(ServletContextEvent.class); - PowerMockito.mockStatic(AAIGraph.class); - PowerMockito.mockStatic(AAIConfig.class); - PowerMockito.mockStatic(ErrorLogHelper.class); - - listener = new AAIAppServletContextListener(); - configureLog(); - } - - /** - * Test contextDestroyed. - */ - @Test - @Ignore - public void testContextDestroyed(){ - listener.contextDestroyed(arg); - assertTrue(logContains(Level.DEBUG, "AAI Server shutdown")); - assertTrue(logContains(Level.INFO, "AAI graph shutdown")); - } - - /** - * Test contextInitialized. - */ - @Test - @Ignore - public void testContextInitialized(){ - listener.contextInitialized(arg); - assertTrue(logContains(Level.DEBUG, "Loading aaiconfig.properties")); - assertTrue(logContains(Level.DEBUG, "Loading error.properties")); - assertTrue(logContains(Level.DEBUG, "Loading graph database")); - assertTrue(logContains(Level.INFO, "AAI Server initialization")); - } - - - /** - * Helper method to check if a String appears in the desired log level. - * - * @param level Log level to use - * @param expected String to search for - * @return True if search String is found, false otherwise - */ - private boolean logContains(Level level, String expected) { - String actual[] = RecordingAppender.messages(); - for (String log : actual) { - if (log.contains(level.toString()) && log.contains(expected)) - return true; - } - return false; - } - - /** - * Set logging level, and initialize log-appender. - */ - private void configureLog() { - Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); - rootLogger.setLevel(Level.DEBUG); - rootLogger.detachAndStopAllAppenders(); - rootLogger.addAppender(RecordingAppender.appender(new PatternLayout())); - } - -} - - -/** - * Appender class that appends log messages to a String List when some logging event occurs - */ -class RecordingAppender extends AppenderBase<ILoggingEvent> { - private static List<String> messages = new ArrayList<String>(); - private static RecordingAppender appender = new RecordingAppender(); - private PatternLayout patternLayout; - - private RecordingAppender() { - super(); - } - - /** - * @param patternLayout Pattern to format log message - * @return Current appender - */ - public static RecordingAppender appender(PatternLayout patternLayout) { - appender.patternLayout = patternLayout; - appender.clear(); - return appender; - } - - @Override - protected void append(ILoggingEvent event) { - messages.add(patternLayout.doLayout(event)); - } - - public void close() {} - - public boolean requiresLayout() { - return false; - } - - /** - * @return Return logs as a String array - */ - public static String[] messages() { - return (String[]) messages.toArray(new String[messages.size()]); - } - - /** - * Clear the message container - */ - private void clear() { - messages.clear(); - } - -} diff --git a/aai-resources/src/test/java/org/onap/aai/util/AAICSVWriterTest.java b/aai-resources/src/test/java/org/onap/aai/util/AAICSVWriterTest.java deleted file mode 100644 index dae280f..0000000 --- a/aai-resources/src/test/java/org/onap/aai/util/AAICSVWriterTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * org.onap.aai - * ================================================================================ - * Copyright © 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========================================================= - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -package org.onap.aai.util; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.powermock.modules.agent.PowerMockAgent; -import org.powermock.modules.junit4.rule.PowerMockRule; - -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Paths; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -public class AAICSVWriterTest { - - @Rule - public PowerMockRule rule = new PowerMockRule(); - - static { - PowerMockAgent.initializeIfNeeded(); - } - - - Writer writer; - File f; - AAICSVWriter testObj; - String fileName = "test_csvWriter.csv"; - String lineEnd = "\n"; - char quoteChar = '\"'; - String separator = ","; - String str1[], str2[]; - - /** - * Initialize. - */ - @Before - public void initialize(){ - str1 = new String[]{"s0", "s1"}; - - str2 = new String[]{"t0", "t1"}; - - try { - f = new File(fileName); - f.createNewFile(); - writer = new PrintWriter(f); - testObj = new AAICSVWriter(new FileWriter(fileName), separator, quoteChar, lineEnd); - } catch (FileNotFoundException e) { - fail("Input csv file not found."); - e.printStackTrace(); - } catch (IOException e) { - fail("Can't create csv file."); - e.printStackTrace(); - } - } - - /** - * Test writeNextLine with String arrays. - */ - @Test - public void testWriteNextLine(){ - populateAndGetFileSize(false, str1, str2); - String wholeText = str1[0] + separator + str1[1] + lineEnd + str2[0] + separator + str2[1] + lineEnd; - assertTrue("CSV file missing text", allLinesFound(wholeText)); - } - - /** - * Test writeNextLine with null. - */ - @Test - public void testWriteNextLine_withNull(){ - populateAndGetFileSize(false, null, null); - assertTrue("CSV file should not contain any text", f.length() == 0); - } - - - /** - * Test writeColumn with String arrays. - */ - @Test - public void testWriteColumn(){ - populateAndGetFileSize(true, str1, str2); - String wholeText = str1[0] + str1[1] + lineEnd + str2[0] + str2[1] + lineEnd; - assertTrue("CSV file missing text", allLinesFound(wholeText)); - } - - - /** - * Test writeColumn with null. - */ - @Test - public void testWriteColumn_withNull(){ - populateAndGetFileSize(true, null, null); - assertTrue("CSV file should not contain any text", f.length() == 0); - } - - /** - * Helper method to create file with given data. - * - * @param isColumnWise True if csv file is to be written in column wise, false otherwise - * @param c1 First set of data - * @param c2 Second set of data - */ - private void populateAndGetFileSize(boolean isColumnWise, String c1[], String c2[]){ - if ( isColumnWise ){ - testObj.writeColumn(c1); - testObj.writeColumn(c2); - } else{ - testObj.writeNext(c1, false); - testObj.writeNext(c2, false); - } - try { - testObj.close(); - } catch (IOException e) { - fail("Can't close stream"); - e.printStackTrace(); - } - } - - - /** - * Helper method to check if a file contains required data. - * - * @param all Data to look for - * @return True if data is found, false otherwise - */ - private boolean allLinesFound(String all){ - String fileContents = ""; - try { - fileContents = new String(Files.readAllBytes(Paths.get(fileName))); - } catch (IOException e1) { - fail("csv file not found"); - e1.printStackTrace(); - } - - return all.equals(fileContents); - } - - - /** - * Cleanup. - */ - @After - public void cleanup(){ - if ( f.exists() ){ - f.delete(); - } - } - -} diff --git a/aai-resources/src/test/resources/application-test.properties b/aai-resources/src/test/resources/application-test.properties new file mode 100644 index 0000000..e6edb6d --- /dev/null +++ b/aai-resources/src/test/resources/application-test.properties @@ -0,0 +1,70 @@ +# The following info parameters are being referenced by ajsc6 +info.build.artifact=aai-resources +info.build.name=resources +info.build.description=Resources Microservice +info.build.version=1.1.0 + +spring.application.name=aai-resources +spring.jersey.type=filter + +server.contextPath=/ +spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration + +spring.profiles.active=production +#The max number of active threads in this pool +server.tomcat.max-threads=200 +#The minimum number of threads always kept alive +server.tomcat.min-Spare-Threads=25 +#The number of milliseconds before an idle thread shutsdown, unless the number of active threads are less or equal to minSpareThreads +server.tomcat.max-idle-time=60000 + + +#Add this properties only if you want to change the URL, AJSC Framework interceptors will intercept +#com.att.ajsc.common.interceptors.PreInterceptor.url=/** +#com.att.ajsc.common.interceptors.PostInterceptor.url=/** + +#Servlet context parameters +server.context_parameters.p-name=value #context parameter with p-name as key and value as value. +kubernetes.namespace=org-onap-aai + +# If you get an application startup failure that the port is already taken +# If thats not it, please check if the key-store file path makes sense +server.local.startpath=src/main/resources/ +server.basic.auth.location=${server.local.startpath}etc/auth/realm.properties + +server.port=8447 +server.ssl.enabled-protocols=TLSv1.1,TLSv1.2 +server.ssl.key-store=${server.local.startpath}etc/auth/aai_keystore +server.ssl.key-store-password=password(OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0) +server.ssl.trust-store=${server.local.startpath}etc/auth/aai_keystore +server.ssl.trust-store-password=password(OBF:1vn21ugu1saj1v9i1v941sar1ugw1vo0) +server.ssl.client-auth=want +server.ssl.key-store-type=JKS + +# JMS bind address host port +jms.bind.address=tcp://localhost:61647 +dmaap.ribbon.eureka.enabled=false +dmaap.ribbon.listOfServers=localhost:3904 +# Number of milliseconds to wait before making ping requests again +dmaap.ribbon.ServerListRefreshInterval=75000 +dmaap.ribbon.NFLoadBalancerPingInterval=75000 +dmaap.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.AvailabilityFilteringRule +dmaap.ribbon.NFLoadBalancerPingClassName=org.onap.aai.config.HttpPingImpl +dmaap.ribbon.EnableMarkingServerDownOnReachingFailureLimit=true +dmaap.ribbon.ServerDownFailureLimit=1 +# This needs to be verified but it seems that adding this property should automatically +# Make the dmaap client change the url from http to https depending on the server +dmaap.ribbon.securePorts=3905 + +# Custom Dmaap Specific Configuration +dmaap.ribbon.health.endpoint=/topics/AAI-EVENT +# Number of seconds to wait for the ping to work and might need to increase this if the pings are all failing +dmaap.ribbon.pingport.timeout=3 + +niws.loadbalancer.dmaap.filterCircuitTripped=true +niws.loadbalancer.dmaap.connectionFailureCountThreshold=3 +niws.loadbalancer.dmaap.circuitTripMaxTimeoutSeconds=180 +#dmaap.ribbon.retryableStatusCodes=404,503 +#dmaap.ribbon.retryableStatusCodes.MaxAutoRetriesNextServer=2 +#dmaap.ribbon.retryableStatusCodes.MaxAutoRetries=2 +#dmaap.ribbon.retryableStatusCodes.OkToRetryOnAllOperations=true diff --git a/aai-resources/src/test/resources/logback.xml b/aai-resources/src/test/resources/logback.xml index bece12d..a6e4345 100644 --- a/aai-resources/src/test/resources/logback.xml +++ b/aai-resources/src/test/resources/logback.xml @@ -22,24 +22,50 @@ --> <configuration scan="true" scanPeriod="60 seconds" debug="false"> - <contextName>${module.ajsc.namespace.name}</contextName> + <statusListener class="ch.qos.logback.core.status.NopStatusListener" /> + + <property resource="application.properties" /> + + <property name="namespace" value="aai-resources"/> + + <property name="AJSC_HOME" value="${AJSC_HOME:-.}" /> <jmxConfigurator /> <property name="logDirectory" value="${AJSC_HOME}/logs" /> - - <!-- Example evaluator filter applied against console appender --> + <property name="eelfLogPattern" value="%ecompStartTime|%date{yyyy-MM-dd'T'HH:mm:ss.SSSZ, UTC}|%X{requestId}|%X{serviceInstanceId}|%-10t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{responseCode}|%replace(%replace(%X{responseDescription}){'\\|', '!'}){'\r|\n', '^'}|%X{instanceUUID}|%level|%X{severity}|%X{serverIpAddress}|%ecompElapsedTime|%X{server}|%X{clientIpAddress}|%eelfClassOfCaller|%X{unused}|%X{processKey}|%X{customField1}|%X{customField2}|%X{customField3}|%X{customField4}|co=%X{component}:%replace(%replace(%m){'\\|', '!'}){'\r|\n', '^'}%n"/> + <property name="eelfAuditLogPattern" value="%ecompStartTime|%date{yyyy-MM-dd'T'HH:mm:ss.SSSZ, UTC}|%X{requestId}|%X{serviceInstanceId}|%-10t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{responseCode}|%replace(%replace(%X{responseDescription}){'\\|', '!'}){'\r|\n|\r\n', '^'}|%X{instanceUUID}|%level|%X{severity}|%X{serverIpAddress}|%ecompElapsedTime|%X{server}|%X{clientIpAddress}|%eelfClassOfCaller|%X{unused}|%X{processKey}|%X{customField1}|%X{customField2}|%X{customField3}|%X{customField4}|co=%X{component}:%replace(%replace(%m){'\\|', '!'}){'\r|\n', '^'}%n"/> + <property name="eelfMetricLogPattern" value="%ecompStartTime|%date{yyyy-MM-dd'T'HH:mm:ss.SSSZ, UTC}|%X{requestId}|%X{serviceInstanceId}|%-10t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%X{statusCode}|%X{responseCode}|%replace(%replace(%X{responseDescription}){'\\|', '!'}){'\r|\n', '^'}|%X{instanceUUID}|%level|%X{severity}|%X{serverIpAddress}|%ecompElapsedTime|%X{server}|%X{clientIpAddress}|%eelfClassOfCaller|%X{unused}|%X{processKey}|%X{targetVirtualEntity}|%X{customField1}|%X{customField2}|%X{customField3}|%X{customField4}|co=%X{component}:%replace(%replace(%m){'\\|', '!'}){'\r|\n', '^'}%n"/> + <!-- <property name="eelfErrorLogPattern" value="%ecompStartTime|%X{requestId}|%-10t|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%ecompErrorCategory|%X{responseCode}|%replace(%replace(%X{responseDescription}){'\\|', '!'}){'\r|\n|\r\n', '^'}|co=%X{component}:%replace(%replace(%m){'\\|', '!'}){'\r|\n', '^'}%n"/> --> + <property name="eelfErrorLogPattern" value="%ecompStartTime|%X{requestId}|%-10t|%X{serviceName}|%X{partnerName}|%X{targetEntity}|%X{targetServiceName}|%ecompErrorCategory|%ecompResponseCode|%ecompResponseDescription|co=%X{component}:%replace(%replace(%m){'\\|', '!'}){'\r|\n', '^'}%n"/> + <property name="eelfTransLogPattern" value="%ecompStartTime|%date{yyyy-MM-dd'T'HH:mm:ss.SSSZ, UTC}|%X{requestId}|%X{serviceInstanceId}|%-10t|%X{serverName}|%X{serviceName}|%X{partnerName}|%X{statusCode}|%X{responseCode}|%replace(%replace(%X{responseDescription}){'\\|', '!'}){'\r|\n', '^'}|%X{instanceUUID}|%level|%X{severity}|%X{serverIpAddress}|%ecompElapsedTime|%X{server}|%X{clientIpAddress}|%eelfClassOfCaller|%X{unused}|%X{processKey}|%X{customField1}|%X{customField2}|%X{customField3}|%X{customField4}|co=%X{partnerName}:%m%n"/> + + <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" /> + <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" /> + <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" /> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> - <filter class="ch.qos.logback.classic.filter.LevelFilter"> - <!-- <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> --> - <level>ERROR</level> - <onMatch>ACCEPT</onMatch> - <onMismatch>DENY</onMismatch> - </filter> + <encoder> + <pattern> + %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx} + </pattern> + </encoder> + </appender> + + <appender name="SANE" class="ch.qos.logback.core.rolling.RollingFileAppender"> + <file>${logDirectory}/rest/sane.log</file> + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/rest/sane.log.%d{yyyy-MM-dd}</fileNamePattern> + </rollingPolicy> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n </pattern> </encoder> </appender> + <appender name="asyncSANE" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="SANE" /> + </appender> + <appender name="METRIC" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.LevelFilter"> @@ -47,124 +73,180 @@ <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> - <file>${logDirectory}/rest/metric.log</file> + <file>${logDirectory}/rest/metrics.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> - <fileNamePattern>${logDirectory}/rest/metric.log.%d{yyyy-MM-dd}</fileNamePattern> + <fileNamePattern>${logDirectory}/rest/metrics.log.%d{yyyy-MM-dd} + </fileNamePattern> </rollingPolicy> - <!-- <triggeringPolicy - class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy> --> - <encoder> - <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%m%n</pattern> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfMetricLogPattern}</pattern> </encoder> </appender> + <appender name="asyncMETRIC" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="METRIC" /> + </appender> <appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender"> - <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>DEBUG</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <file>${logDirectory}/rest/debug.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> - <fileNamePattern>${logDirectory}/rest/debug.log.%d{yyyy-MM-dd}</fileNamePattern> + <fileNamePattern>${logDirectory}/rest/debug.log.%d{yyyy-MM-dd} + </fileNamePattern> </rollingPolicy> - <!-- <triggeringPolicy - class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy>--> - <encoder> - <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%m%n</pattern> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfLogPattern}</pattern> </encoder> </appender> + <appender name="asyncDEBUG" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="DEBUG" /> + </appender> + <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>WARN</level> - <onMatch>ACCEPT</onMatch> - <onMismatch>DENY</onMismatch> </filter> <file>${logDirectory}/rest/error.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> - <fileNamePattern>${logDirectory}/rest/error.log.%d{yyyy-MM-dd}</fileNamePattern> + <fileNamePattern>${logDirectory}/rest/error.log.%d{yyyy-MM-dd} + </fileNamePattern> </rollingPolicy> - <!-- <triggeringPolicy - class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy>--> - <encoder> - <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n"</pattern> --> - <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%m%n</pattern> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfErrorLogPattern}</pattern> </encoder> </appender> - - <appender name="AUDIT" + + <appender name="asyncERROR" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="ERROR" /> + </appender> + + <appender name="AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender"> - <filter class="ch.qos.logback.core.filter.EvaluatorFilter"> - <evaluator> - <matcher> - <Name>audit</Name> - <!-- filter out odd numbered statements --> - <regex>co\=aairest</regex> - </matcher> - <expression>level == INFO && audit.matches(formattedMessage)</expression> - </evaluator> - <OnMatch>ACCEPT</OnMatch> - <OnMismatch>DENY</OnMismatch> - </filter> <file>${logDirectory}/rest/audit.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> - <fileNamePattern>${logDirectory}/rest/metric.log.%d{yyyy-MM-dd}</fileNamePattern> + <fileNamePattern>${logDirectory}/rest/audit.log.%d{yyyy-MM-dd} + </fileNamePattern> </rollingPolicy> - <encoder> - <pattern>%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}|%m%n</pattern> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfAuditLogPattern}</pattern> + </encoder> + </appender> + + <appender name="asyncAUDIT" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="AUDIT" /> + </appender> + + <appender name="translog" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.LevelFilter"> + <level>DEBUG</level> + <onMatch>ACCEPT</onMatch> + <onMismatch>DENY</onMismatch> + </filter> + <file>${logDirectory}/rest/translog.log</file> + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/rest/translog.log.%d{yyyy-MM-dd} + </fileNamePattern> + </rollingPolicy> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfTransLogPattern}</pattern> </encoder> </appender> - <appender name="auditLogs" + <appender name="asynctranslog" class="ch.qos.logback.classic.AsyncAppender"> + <queueSize>1000</queueSize> + <includeCallerData>true</includeCallerData> + <appender-ref ref="translog" /> + </appender> + + <appender name="dmaapAAIEventConsumer" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <level>WARN</level> </filter> - <file>${logDirectory}/rest/audit.log</file> + <File>${logDirectory}/dmaapAAIEventConsumer/error.log</File> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> - <fileNamePattern>${logDirectory}/rest/audit.%d{yyyy-MM-dd}.log.zip + <fileNamePattern>${logDirectory}/dmaapAAIEventConsumer/error.log.%d{yyyy-MM-dd} </fileNamePattern> </rollingPolicy> - <triggeringPolicy - class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy> - <encoder> - <pattern>"%d [%thread] %-5level %logger{1024} - %msg%n"</pattern> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfLogPattern}</pattern> </encoder> </appender> - - <appender name="perfLogs" + + <appender name="dmaapAAIEventConsumerDebug" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.LevelFilter"> + <level>DEBUG</level> + <onMatch>ACCEPT</onMatch> + <onMismatch>DENY</onMismatch> + </filter> + <File>${logDirectory}/dmaapAAIEventConsumer/debug.log</File> + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/dmaapAAIEventConsumer/debug.log.%d{yyyy-MM-dd} + </fileNamePattern> + </rollingPolicy> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfLogPattern}</pattern> + </encoder> + </appender> + <appender name="dmaapAAIEventConsumerMetric" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.LevelFilter"> + <level>INFO</level> + <onMatch>ACCEPT</onMatch> + <onMismatch>DENY</onMismatch> + </filter> + <File>${logDirectory}/dmaapAAIEventConsumer/metrics.log</File> + <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> + <fileNamePattern>${logDirectory}/dmaapAAIEventConsumer/metrics.log.%d{yyyy-MM-dd} + </fileNamePattern> + </rollingPolicy> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfMetricLogPattern}</pattern> + </encoder> + </appender> + <appender name="external" class="ch.qos.logback.core.rolling.RollingFileAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> + <level>WARN</level> </filter> - <file>${logDirectory}/rest/perform.log</file> + <file>${logDirectory}/external/external.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> - <fileNamePattern>${logDirectory}/rest/perform.%d{yyyy-MM-dd}.log.zip + <fileNamePattern>${logDirectory}/external/external.log.%d{yyyy-MM-dd} </fileNamePattern> </rollingPolicy> - <!-- <triggeringPolicy - class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> - <maxFileSize>5MB</maxFileSize> - </triggeringPolicy> --> - <encoder> - <pattern>"%d [%thread] %-5level %logger{1024} - %msg%n"</pattern> + <encoder class="org.onap.aai.logging.EcompEncoder"> + <pattern>${eelfLogPattern}</pattern> </encoder> </appender> + <logger name="org.onap.aai" level="DEBUG" additivity="true"> + <appender-ref ref="asyncDEBUG" /> + <appender-ref ref="asyncERROR" /> + <appender-ref ref="asyncMETRIC" /> + <appender-ref ref="asyncSANE" /> + </logger> <!-- Spring related loggers --> <logger name="org.springframework" level="WARN" /> <logger name="org.springframework.beans" level="WARN" /> <logger name="org.springframework.web" level="WARN" /> <logger name="com.blog.spring.jms" level="WARN" /> + <logger name="com.jayway.jsonpath" level="WARN" /> <!-- AJSC Services (bootstrap services) --> <logger name="ajsc" level="WARN" /> @@ -175,9 +257,11 @@ <logger name="ajsc.UserDefinedJarService" level="WARN" /> <logger name="ajsc.UserDefinedBeansDefService" level="WARN" /> <logger name="ajsc.LoggingConfigurationService" level="WARN" /> - + <!-- AJSC related loggers (DME2 Registration, csi logging, restlet, servlet logging) --> + <logger name="org.codehaus.groovy" level="WARN" /> + <logger name="com.att.scamper" level="WARN" /> <logger name="ajsc.utils" level="WARN" /> <logger name="ajsc.utils.DME2Helper" level="WARN" /> <logger name="ajsc.filters" level="WARN" /> @@ -187,6 +271,9 @@ <logger name="com.att.ajsc" level="WARN" /> <logger name="com.att.ajsc.csi.logging" level="WARN" /> <logger name="com.att.ajsc.filemonitor" level="WARN" /> + <logger name="com.netflix.loadbalancer" level="WARN" /> + + <logger name="org.apache.zookeeper" level="WARN" /> <!-- Other Loggers that may help troubleshoot --> <logger name="net.sf" level="WARN" /> @@ -205,54 +292,101 @@ <logger name="org.restlet" level="WARN" /> <logger name="org.apache.camel.component.restlet" level="WARN" /> + <logger name="org.hibernate.validator" level="WARN" /> + <logger name="org.hibernate" level="WARN" /> + <logger name="org.hibernate.ejb" level="OFF" /> + <!-- logback internals logging --> - <logger name="ch.qos.logback.classic" level="INFO" /> - <logger name="ch.qos.logback.core" level="INFO" /> + <logger name="ch.qos.logback.classic" level="WARN" /> + <logger name="ch.qos.logback.core" level="WARN" /> - <appender name="ASYNC-audit" class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>1000</queueSize> - <discardingThreshold>0</discardingThreshold> - <appender-ref ref="Audit-Record-Queue" /> + <logger name="org.eclipse.jetty" level="WARN" /> + + <!-- logback jms appenders & loggers definition starts here --> + <appender name="auditLogs" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.ThresholdFilter" /> + <file>${logDirectory}/perf-audit/Audit-${lrmRVer}-${lrmRO}-${Pid}.log + </file> + <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/perf-audit/Audit-${lrmRVer}-${lrmRO}-${Pid}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>9</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>5MB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>"%d [%thread] %-5level %logger{1024} - %msg%n"</pattern> + </encoder> </appender> - - <appender name="ASYNC-perf" class="ch.qos.logback.classic.AsyncAppender"> - <queueSize>1000</queueSize> - <discardingThreshold>0</discardingThreshold> - <appender-ref ref="Performance-Tracker-Queue" /> + <appender name="perfLogs" + class="ch.qos.logback.core.rolling.RollingFileAppender"> + <filter class="ch.qos.logback.classic.filter.ThresholdFilter" /> + <file>${logDirectory}/perf-audit/Perform-${lrmRVer}-${lrmRO}-${Pid}.log + </file> + <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> + <fileNamePattern>${logDirectory}/perf-audit/Perform-${lrmRVer}-${lrmRO}-${Pid}.%i.log.zip + </fileNamePattern> + <minIndex>1</minIndex> + <maxIndex>9</maxIndex> + </rollingPolicy> + <triggeringPolicy + class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> + <maxFileSize>5MB</maxFileSize> + </triggeringPolicy> + <encoder> + <pattern>"%d [%thread] %-5level %logger{1024} - %msg%n"</pattern> + </encoder> </appender> - - <!-- - <logger name="AuditRecord" level="INFO" additivity="FALSE"> - <appender-ref ref="ASYNC-audit" /> + <logger name="AuditRecord" level="INFO" additivity="false"> <appender-ref ref="auditLogs" /> </logger> - <logger name="AuditRecord_DirectCall" level="INFO" additivity="FALSE"> - <appender-ref ref="ASYNC-audit" /> + <logger name="AuditRecord_DirectCall" level="INFO" additivity="false"> <appender-ref ref="auditLogs" /> </logger> - <logger name="PerfTrackerRecord" level="INFO" additivity="FALSE"> - <appender-ref ref="ASYNC-perf" /> + <logger name="PerfTrackerRecord" level="INFO" additivity="false"> <appender-ref ref="perfLogs" /> - </logger> - --> - - <logger name="org.onap.aai" level="INFO" /> - - <!-- - <logger name="org.onap.aai.util" level="WARN" /> - <logger name="org.onap.aai.rest" level="WARN" /> - <logger name="org.onap.aai.rest.Business" level="WARN" /> - --> - + </logger> + <!-- logback jms appenders & loggers definition ends here --> + + <logger name="org.onap.aai.interceptors.post" level="DEBUG" + additivity="false"> + <appender-ref ref="asynctranslog" /> + </logger> + + <logger name="org.onap.aai.interceptors.pre.SetLoggingContext" level="DEBUG"> + <appender-ref ref="asyncAUDIT"/> + </logger> + + <logger name="org.onap.aai.interceptors.post.ResetLoggingContext" level="DEBUG"> + <appender-ref ref="asyncAUDIT"/> + </logger> + + <logger name="org.onap.aai.dmaap" level="DEBUG" additivity="false"> + <appender-ref ref="dmaapAAIEventConsumer" /> + <appender-ref ref="dmaapAAIEventConsumerDebug" /> + <appender-ref ref="dmaapAAIEventConsumerMetric" /> + </logger> + <logger name="org.apache" level="WARN" /> <logger name="org.zookeeper" level="WARN" /> <logger name="com.thinkaurelius" level="WARN" /> + <logger name="com.att.aft.dme2" level="WARN" /> - <root level="WARN"> - <appender-ref ref="DEBUG" /> - <appender-ref ref="ERROR" /> - <appender-ref ref="METRIC" /> - <appender-ref ref="AUDIT" /> - </root> + <!-- ============================================================================ --> + <!-- General EELF logger --> + <!-- ============================================================================ --> + <logger name="com.att.eelf" level="WARN" additivity="false"> + <appender-ref ref="asyncDEBUG" /> + <appender-ref ref="asyncERROR" /> + <appender-ref ref="asyncMETRIC" /> + </logger> + <root level="DEBUG"> + <appender-ref ref="external" /> + <appender-ref ref="STDOUT" /> + </root> </configuration> |