From f3bf5dd360b93fd7ef6cc8d871a9903de9f27e5a Mon Sep 17 00:00:00 2001 From: "mark.j.leonard" Date: Tue, 26 Jun 2018 11:37:52 +0100 Subject: [PATCH] Fix remaining Sonar code smells Code reformatting to address Sonar code smells, excluding the cyclomatic complexity errors which will require some heavier refactoring. Issue-ID: AAI-1242 Change-Id: I0f2502c8038b1e70f53f3b82b9d4d0761d9137cc Signed-off-by: mark.j.leonard --- .../onap/aai/babel/csar/CsarToXmlConverter.java | 45 +++++++------ .../aai/babel/csar/extractor/YamlExtractor.java | 54 ++++++++------- .../service/GenerateArtifactsServiceImpl.java | 2 +- .../org/onap/aai/babel/util/RequestValidator.java | 18 ++--- .../babel/xml/generator/api/ArtifactGenerator.java | 1 + .../org/onap/aai/babel/MicroServiceAuthTest.java | 11 ++- .../babel/csar/extractor/YamlExtractorTest.java | 78 ++++++++++++---------- .../babel/csar/fixture/ArtifactInfoBuilder.java | 19 ++++-- .../babel/csar/fixture/TestArtifactInfoImpl.java | 19 +++--- .../java/org/onap/aai/babel/logging/LogReader.java | 5 +- .../aai/babel/logging/TestApplicationLogger.java | 52 +++++++-------- .../org/onap/aai/babel/parser/TestToscaParser.java | 20 +++--- .../aai/babel/service/CsarToXmlConverterTest.java | 58 +++++++++------- .../service/TestGenerateArtifactsServiceImpl.java | 56 ++++++++-------- .../onap/aai/babel/service/TestInfoService.java | 2 +- .../org/onap/aai/babel/util/ArtifactTestUtils.java | 59 +++++++++++----- .../onap/aai/babel/util/TestRequestValidator.java | 9 ++- .../babel/xml/generator/model/TestVfModule.java | 14 ++-- .../aai/babel/xml/generator/model/TestWidget.java | 3 +- src/test/resources/response/response.json | 2 +- 20 files changed, 287 insertions(+), 240 deletions(-) diff --git a/src/main/java/org/onap/aai/babel/csar/CsarToXmlConverter.java b/src/main/java/org/onap/aai/babel/csar/CsarToXmlConverter.java index be6ef58..98db8ae 100644 --- a/src/main/java/org/onap/aai/babel/csar/CsarToXmlConverter.java +++ b/src/main/java/org/onap/aai/babel/csar/CsarToXmlConverter.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -22,7 +22,6 @@ package org.onap.aai.babel.csar; import java.util.List; import java.util.Objects; - import org.apache.commons.lang3.time.StopWatch; import org.onap.aai.babel.csar.extractor.InvalidArchiveException; import org.onap.aai.babel.csar.extractor.YamlExtractor; @@ -34,47 +33,51 @@ import org.onap.aai.babel.xml.generator.XmlArtifactGenerationException; import org.onap.aai.babel.xml.generator.data.Artifact; /** - * This class is responsible for converting content in a csar archive into one or more xml artifacts. + * This class is responsible for converting CSAR content into one or more XML artifacts. */ public class CsarToXmlConverter { private static final LogHelper logger = LogHelper.INSTANCE; + private final YamlExtractor yamlExtractor; + + public CsarToXmlConverter() { + yamlExtractor = new YamlExtractor(); + } + /** - * This method is responsible for extracting one or more yaml files from the given csarArtifact and then using them - * to generate xml artifacts. + * This method is responsible for generating Artifacts from YAML files within CSAR content. * - * @param csarArchive the artifact that contains the csar archive to generate xml artifacts from - * @param name the name of the archive file - * @param version the version of the archive file - * @return List a list of generated xml artifacts - * @throws CsarConverterException if there is an error either extracting the yaml files or generating xml artifacts + * @param csarArchive + * the artifact that contains the csar archive to generate XML artifacts from + * @param name + * the name of the archive file + * @param version + * the version of the archive file + * @return List a list of generated XML artifacts + * @throws CsarConverterException + * if there is an error either extracting the YAML files or generating XML artifacts */ public List generateXmlFromCsar(byte[] csarArchive, String name, String version) throws CsarConverterException { + validateArguments(csarArchive, name, version); StopWatch stopwatch = new StopWatch(); stopwatch.start(); - validateArguments(csarArchive, name, version); - logger.info(ApplicationMsgs.DISTRIBUTION_EVENT, - "Starting to process csarArchive to convert contents to xml artifacts"); + "Starting to process csarArchive to convert contents to XML artifacts"); List xmlArtifacts; try { - logger.debug("Calling YamlExtractor to extract ymlFiles"); - List ymlFiles = YamlExtractor.extract(csarArchive, name, version); - - logger.debug("Calling XmlArtifactGenerator to generateXmlArtifacts"); + List ymlFiles = yamlExtractor.extract(csarArchive, name, version); xmlArtifacts = new ModelGenerator().generateArtifacts(csarArchive, ymlFiles); - - logger.debug(xmlArtifacts.size() + " xml artifacts have been generated"); + logger.debug(xmlArtifacts.size() + " XML artifact(s) have been generated"); } catch (InvalidArchiveException e) { throw new CsarConverterException( - "An error occurred trying to extract the yml files from the csar file : " + e); + "An error occurred trying to extract the YMAL files from the csar file : " + e); } catch (XmlArtifactGenerationException e) { throw new CsarConverterException( - "An error occurred trying to generate xml files from a collection of yml files : " + e); + "An error occurred trying to generate XML files from a collection of YAML files : " + e); } finally { logger.logMetrics(stopwatch, LogHelper.getCallerMethodName(0)); } diff --git a/src/main/java/org/onap/aai/babel/csar/extractor/YamlExtractor.java b/src/main/java/org/onap/aai/babel/csar/extractor/YamlExtractor.java index 73d364e..15d77a1 100644 --- a/src/main/java/org/onap/aai/babel/csar/extractor/YamlExtractor.java +++ b/src/main/java/org/onap/aai/babel/csar/extractor/YamlExtractor.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -37,35 +37,29 @@ import org.onap.aai.babel.xml.generator.data.Artifact; import org.onap.aai.cl.api.Logger; /** - * The purpose of this class is to process a .csar file in the form of a byte array and extract yaml files from it. + * This class extracts YAML files from CSAR (compressed archive) content. * - * A .csar file is a compressed archive like a zip file and this class will treat the byte array as it if were a zip - * file. */ public class YamlExtractor { private static Logger logger = LogHelper.INSTANCE; private static final Pattern YAMLFILE_EXTENSION_REGEX = Pattern.compile("(?i).*\\.ya?ml$"); - /** Private constructor */ - private YamlExtractor() { - throw new IllegalAccessError("Utility class"); - } - /** * This method is responsible for filtering the contents of the supplied archive and returning a collection of - * {@link Artifact}s that represent the yml files that have been found in the archive.
- *
- * If the archive contains no yml files it will return an empty list.
+ * {@link Artifact}s that represent the YAML files that have been found in the archive. * - * @param archive the zip file in the form of a byte array containing one or more yml files - * @param name the name of the archive file - * @param version the version of the archive file - * @return List collection of yml files found in the archive - * @throws InvalidArchiveException if an error occurs trying to extract the yml files from the archive, if the - * archive is not a zip file or there are no yml files + * @param archive + * the compressed archive in the form of a byte array, expected to contain one or more YAML files + * @param name + * the name of the archive + * @param version + * the version of the archive + * @return List<Artifact> collection of YAML artifacts found in the archive + * @throws InvalidArchiveException + * if an error occurs trying to extract the YAML file(s) from the archive, or no files were found */ - public static List extract(byte[] archive, String name, String version) throws InvalidArchiveException { + public List extract(byte[] archive, String name, String version) throws InvalidArchiveException { validateRequest(archive, name, version); logger.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Extracting CSAR archive: " + name); @@ -81,7 +75,7 @@ public class YamlExtractor { } } if (ymlFiles.isEmpty()) { - throw new InvalidArchiveException("No valid yml files were found in the csar file."); + throw new InvalidArchiveException("No valid YAML files were found in the csar file."); } } catch (IOException e) { throw new InvalidArchiveException( @@ -94,7 +88,15 @@ public class YamlExtractor { return ymlFiles; } - private static void validateRequest(byte[] archive, String name, String version) throws InvalidArchiveException { + /** + * Throw an error if the supplied parameters are not valid. + * + * @param archive + * @param name + * @param version + * @throws InvalidArchiveException + */ + private void validateRequest(byte[] archive, String name, String version) throws InvalidArchiveException { if (archive == null || archive.length == 0) { throw new InvalidArchiveException("An archive must be supplied for processing."); } else if (StringUtils.isBlank(name)) { @@ -105,13 +107,15 @@ public class YamlExtractor { } /** + * Determine whether the file name matches the pattern for YAML content. + * * @param entry - * @return + * the entry + * @return true, if successful */ - private static boolean fileShouldBeExtracted(ZipArchiveEntry entry) { + private boolean fileShouldBeExtracted(ZipArchiveEntry entry) { boolean extractFile = YAMLFILE_EXTENSION_REGEX.matcher(entry.getName()).matches(); - logger.debug(ApplicationMsgs.DISTRIBUTION_EVENT, - "Checking if " + entry.getName() + " should be extracted... " + extractFile); + logger.debug(ApplicationMsgs.DISTRIBUTION_EVENT, "Extraction of " + entry.getName() + "=" + extractFile); return extractFile; } } diff --git a/src/main/java/org/onap/aai/babel/service/GenerateArtifactsServiceImpl.java b/src/main/java/org/onap/aai/babel/service/GenerateArtifactsServiceImpl.java index 532d8c7..25499b8 100644 --- a/src/main/java/org/onap/aai/babel/service/GenerateArtifactsServiceImpl.java +++ b/src/main/java/org/onap/aai/babel/service/GenerateArtifactsServiceImpl.java @@ -144,7 +144,7 @@ public class GenerateArtifactsServiceImpl implements GenerateArtifactsService { Gson gson = new GsonBuilder().disableHtmlEscaping().create(); BabelRequest babelRequest = gson.fromJson(requestBody, BabelRequest.class); - RequestValidator.validateRequest(babelRequest); + new RequestValidator().validateRequest(babelRequest); byte[] csarFile = Base64.getDecoder().decode(babelRequest.getCsar()); List babelArtifacts = new CsarToXmlConverter().generateXmlFromCsar(csarFile, diff --git a/src/main/java/org/onap/aai/babel/util/RequestValidator.java b/src/main/java/org/onap/aai/babel/util/RequestValidator.java index c0d2c98..be45e17 100644 --- a/src/main/java/org/onap/aai/babel/util/RequestValidator.java +++ b/src/main/java/org/onap/aai/babel/util/RequestValidator.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -22,20 +22,20 @@ package org.onap.aai.babel.util; import org.onap.aai.babel.service.data.BabelRequest; -/** Utility class */ +/** + * Validator for a Babel request. + * + */ public class RequestValidator { - /** Empty constructor */ - private RequestValidator() { - // Prevent instantiation - } - /** * Validates that the request body contains the required attributes * - * @param request the request body to validate + * @param request + * the request body to validate + * @throws RequestValidationException */ - public static void validateRequest(BabelRequest request) throws RequestValidationException { + public void validateRequest(BabelRequest request) throws RequestValidationException { if (request.getCsar() == null) { throw new RequestValidationException("No csar attribute found in the request body."); } diff --git a/src/main/java/org/onap/aai/babel/xml/generator/api/ArtifactGenerator.java b/src/main/java/org/onap/aai/babel/xml/generator/api/ArtifactGenerator.java index 0dc64bf..bb40182 100644 --- a/src/main/java/org/onap/aai/babel/xml/generator/api/ArtifactGenerator.java +++ b/src/main/java/org/onap/aai/babel/xml/generator/api/ArtifactGenerator.java @@ -26,6 +26,7 @@ import org.onap.aai.babel.xml.generator.data.Artifact; import org.onap.aai.babel.xml.generator.data.GenerationData; /** Artifact Generation. Note that there is only one implementation of this interface currently. */ +@FunctionalInterface public interface ArtifactGenerator { /** diff --git a/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java index e6f5aa6..a8f1f92 100644 --- a/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java +++ b/src/test/java/org/onap/aai/babel/MicroServiceAuthTest.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -116,8 +116,6 @@ public class MicroServiceAuthTest { assertThat(AAIMicroServiceAuthCore.authorize(VALID_ADMIN_USER, "WRONG:action"), is(false)); } - - @Test public void testValidateRequest() throws AAIAuthException { AAIMicroServiceAuth auth = createStandardAuth(); @@ -137,7 +135,6 @@ public class MicroServiceAuthTest { * @throws AAIAuthException */ private AAIMicroServiceAuth createAuthService(JSONObject roles) throws IOException, AAIAuthException { - BabelAuthConfig babelAuthConfig = new BabelAuthConfig(); File file = File.createTempFile("auth-policy", "json"); file.deleteOnExit(); FileWriter fileWriter = new FileWriter(file); @@ -145,6 +142,7 @@ public class MicroServiceAuthTest { fileWriter.flush(); fileWriter.close(); + BabelAuthConfig babelAuthConfig = new BabelAuthConfig(); babelAuthConfig.setAuthPolicyFile(file.getAbsolutePath()); return new AAIMicroServiceAuth(babelAuthConfig); } @@ -190,8 +188,6 @@ public class MicroServiceAuthTest { private JSONObject createRoleObject(String roleName, JSONArray usersArray, JSONArray functionsArray) throws JSONException { - JSONObject roles = new JSONObject(); - JSONObject role = new JSONObject(); role.put("name", roleName); role.put("functions", functionsArray); @@ -199,8 +195,9 @@ public class MicroServiceAuthTest { JSONArray rolesArray = new JSONArray(); rolesArray.put(role); - roles.put("roles", rolesArray); + JSONObject roles = new JSONObject(); + roles.put("roles", rolesArray); return roles; } diff --git a/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java b/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java index 77517ad..b53f38d 100644 --- a/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java +++ b/src/test/java/org/onap/aai/babel/csar/extractor/YamlExtractorTest.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -27,13 +27,12 @@ import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import org.apache.commons.io.IOUtils; import org.junit.Test; import org.onap.aai.babel.util.ArtifactTestUtils; import org.onap.aai.babel.xml.generator.data.Artifact; /** - * Tests @see YamlExtractor + * Tests {@link YamlExtractor}. */ public class YamlExtractorTest { @@ -44,90 +43,72 @@ public class YamlExtractorTest { private static final String SUPPLY_VERSION = "The version must be supplied for processing."; @Test - public void extract_nullContentSupplied() { + public void testNullContentSupplied() { invalidArgumentsTest(null, FOO, FOO, SUPPLY_AN_ARCHIVE); } - private void invalidArgumentsTest(byte[] archive, String name, String version, String expectedErrorMessage) { - try { - YamlExtractor.extract(archive, name, version); - fail("An instance of InvalidArchiveException should have been thrown"); - } catch (Exception ex) { - assertTrue(ex instanceof InvalidArchiveException); - assertEquals(expectedErrorMessage, ex.getLocalizedMessage()); - } - } - @Test - public void extract_emptyContentSupplied() { + public void testEmptyContentSupplied() { invalidArgumentsTest(new byte[0], FOO, FOO, SUPPLY_AN_ARCHIVE); } @Test - public void extract_nullNameSupplied() { + public void testNullNameSupplied() { invalidArgumentsTest(SOME_BYTES.getBytes(), null, FOO, SUPPLY_NAME); } @Test - public void extract_blankNameSupplied() { + public void testBlankNameSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), " \t ", FOO, SUPPLY_NAME); } @Test - public void extract_emptyNameSupplied() { + public void testEmptyNameSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), "", FOO, SUPPLY_NAME); } @Test - public void extract_nullVersionSupplied() { + public void testNullVersionSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, null, SUPPLY_VERSION); } @Test - public void extract_blankVersionSupplied() { + public void testBlankVersionSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, " \t ", SUPPLY_VERSION); } @Test - public void extract_emptyVersionSupplied() { + public void testEmptyVersionSupplied() { invalidArgumentsTest("just some bytes that will pass the firsts validation".getBytes(), FOO, "", SUPPLY_VERSION); } @Test - public void extract_invalidContentSupplied() { + public void testInvalidContentSupplied() { invalidArgumentsTest("This is a piece of nonsense and not a zip file".getBytes(), FOO, FOO, "An error occurred trying to create a ZipFile. Is the content being converted really a csar file?"); } @Test - public void extract_archiveContainsNoYmlFiles() throws IOException { + public void testArchiveContainsNoYmlFiles() throws IOException { try { - YamlExtractor.extract(loadResource("compressedArtifacts/noYmlFilesArchive.zip"), "noYmlFilesArchive.zip", - "v1"); + extractArchive("noYmlFilesArchive.zip"); fail("An instance of InvalidArchiveException should have been thrown."); } catch (Exception e) { assertTrue("An instance of InvalidArchiveException should have been thrown.", e instanceof InvalidArchiveException); - assertEquals("Incorrect message was returned", "No valid yml files were found in the csar file.", + assertEquals("Incorrect message was returned", "No valid YAML files were found in the csar file.", e.getMessage()); } } - private byte[] loadResource(final String archiveName) throws IOException { - return IOUtils.toByteArray(YamlExtractor.class.getClassLoader().getResource(archiveName)); - } - @Test - public void extract_archiveContainsOnlyTheExpectedYmlFilesFromSdWanService() + public void testArchiveContainsOnlyTheExpectedYmlFilesFromSdWanService() throws IOException, InvalidArchiveException { - List ymlFiles = - YamlExtractor.extract(loadResource("compressedArtifacts/service-SdWanServiceTest-csar.csar"), - "service-SdWanServiceTest-csar.csar", "v1"); - + final List ymlFiles = extractArchive("service-SdWanServiceTest-csar.csar"); List payloads = new ArrayList<>(); payloads.add("ymlFiles/resource-SdWanTestVsp-template.yml"); payloads.add("ymlFiles/resource-TunnelXconntest-template.yml"); @@ -137,5 +118,30 @@ public class YamlExtractorTest { new ArtifactTestUtils().performYmlAsserts(ymlFiles, payloads); } -} + /** + * @param archive + * @param name + * @param version + * @param expectedErrorMessage + */ + private void invalidArgumentsTest(byte[] archive, String name, String version, String expectedErrorMessage) { + try { + new YamlExtractor().extract(archive, name, version); + fail("An instance of InvalidArchiveException should have been thrown"); + } catch (Exception ex) { + assertTrue(ex instanceof InvalidArchiveException); + assertEquals(expectedErrorMessage, ex.getLocalizedMessage()); + } + } + + /** + * @param resourceName + * @return + * @throws InvalidArchiveException + * @throws IOException + */ + private List extractArchive(String resourceName) throws InvalidArchiveException, IOException { + return new YamlExtractor().extract(new ArtifactTestUtils().getCompressedArtifact(resourceName), resourceName, "v1"); + } +} diff --git a/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java b/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java index 96f1b2d..cb70677 100644 --- a/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java +++ b/src/test/java/org/onap/aai/babel/csar/fixture/ArtifactInfoBuilder.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -33,10 +33,14 @@ public class ArtifactInfoBuilder { * Builds an implementation of IArtifactInfo for test purposes. *

* - * @param type type of artifact - * @param name name of artifact - * @param description description of artifact - * @param version version of artifact + * @param type + * type of artifact + * @param name + * name of artifact + * @param description + * description of artifact + * @param version + * version of artifact * @return IArtifactInfo implementation of IArtifactInfo from given parameters for test purposes */ public static IArtifactInfo build(final String type, final String name, final String description, @@ -61,8 +65,9 @@ public class ArtifactInfoBuilder { * where the elements of the second dimension are the arguments to {@link #build(String, String, String, String)}. *

* - * @param artifactInfoBits a two dimensional array of data used to build the artifacts - * @return List a list of artifacts built from the given array of info + * @param artifactInfoBits + * a two dimensional array of data used to build the artifacts + * @return List<IArtifactInfo> a list of artifacts built from the given array of info */ static List buildArtifacts(final String[][] artifactInfoBits) { List artifacts = new ArrayList<>(); diff --git a/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java b/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java index f686911..6c0078d 100644 --- a/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java +++ b/src/test/java/org/onap/aai/babel/csar/fixture/TestArtifactInfoImpl.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -102,19 +102,18 @@ public class TestArtifactInfoImpl implements IArtifactInfo { @Override public boolean equals(Object obj) { + if (this == obj) { + return true; + } if (!(obj instanceof TestArtifactInfoImpl)) { return false; - } else if (obj == this) { - return true; } TestArtifactInfoImpl rhs = (TestArtifactInfoImpl) obj; - // @formatter:off - return new EqualsBuilder() - .append(artifactType, rhs.artifactType) - .append(artifactDescription, rhs.artifactDescription) - .append(artifactVersion, rhs.artifactVersion) - .isEquals(); - // @formatter:on + return new EqualsBuilder() // + .append(artifactType, rhs.artifactType) // + .append(artifactDescription, rhs.artifactDescription) // + .append(artifactVersion, rhs.artifactVersion) // + .isEquals(); } @Override diff --git a/src/test/java/org/onap/aai/babel/logging/LogReader.java b/src/test/java/org/onap/aai/babel/logging/LogReader.java index 0c4de64..77b8d60 100644 --- a/src/test/java/org/onap/aai/babel/logging/LogReader.java +++ b/src/test/java/org/onap/aai/babel/logging/LogReader.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -27,6 +27,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -67,7 +68,7 @@ public class LogReader { if (cachedLog == null) { Optional latestFilePath = Files.list(Paths.get(logDirectory)) .filter(f -> Files.isDirectory(f) == false && f.getFileName().toString().startsWith(filenamePrefix)) - .max((f1, f2) -> (int) (f1.toFile().lastModified() - f2.toFile().lastModified())); + .max(Comparator.comparingLong(f -> f.toFile().lastModified())); if (latestFilePath.isPresent()) { cachedLog = latestFilePath.get(); } else { diff --git a/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java index ed9dac4..0c350c2 100644 --- a/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java +++ b/src/test/java/org/onap/aai/babel/logging/TestApplicationLogger.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -61,7 +61,7 @@ public class TestApplicationLogger { Logger logger = LogHelper.INSTANCE; LogReader errorReader = new LogReader(LogHelper.getLogDirectory(), "error"); LogReader debugReader = new LogReader(LogHelper.getLogDirectory(), "debug"); - String[] args = {"1", "2", "3", "4"}; + String[] args = { "1", "2", "3", "4" }; for (ApplicationMsgs msg : Arrays.asList(ApplicationMsgs.values())) { if (msg.name().endsWith("ERROR")) { logger.error(msg, args); @@ -106,8 +106,8 @@ public class TestApplicationLogger { */ @Test public void logAuditMessage() throws IOException { - LogHelper logger = LogHelper.INSTANCE; - LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); + final LogHelper logger = LogHelper.INSTANCE; + final LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); HttpHeaders headers = Mockito.mock(HttpHeaders.class); Mockito.when(headers.getHeaderString("X-ECOMP-RequestID")).thenReturn("ecomp-request-id"); @@ -115,20 +115,20 @@ public class TestApplicationLogger { // Call logAudit without first calling startAudit logger.logAuditSuccess("first call: bob"); - String s = reader.getNewLines(); - assertThat(s, is(notNullValue())); - assertThat("audit message log level", s, containsString("INFO")); - assertThat("audit message content", s, containsString("bob")); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("audit message log level", str, containsString("INFO")); + assertThat("audit message content", str, containsString("bob")); // This time call the start method logger.startAudit(headers, null); logger.logAuditSuccess("second call: foo"); - s = reader.getNewLines(); - assertThat(s, is(notNullValue())); - assertThat("audit message log level", s, containsString("INFO")); - assertThat("audit message content", s, containsString("foo")); - assertThat("audit message content", s, containsString("ecomp-request-id")); - assertThat("audit message content", s, containsString("app-id")); + str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("audit message log level", str, containsString("INFO")); + assertThat("audit message content", str, containsString("foo")); + assertThat("audit message content", str, containsString("ecomp-request-id")); + assertThat("audit message content", str, containsString("app-id")); } /** @@ -142,10 +142,10 @@ public class TestApplicationLogger { LogReader reader = new LogReader(LogHelper.getLogDirectory(), "audit"); logger.startAudit(null, null); logger.logAuditSuccess("foo"); - String s = reader.getNewLines(); - assertThat(s, is(notNullValue())); - assertThat("audit message log level", s, containsString("INFO")); - assertThat("audit message content", s, containsString("foo")); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("audit message log level", str, containsString("INFO")); + assertThat("audit message content", str, containsString("foo")); } /** @@ -158,10 +158,10 @@ public class TestApplicationLogger { LogReader reader = new LogReader(LogHelper.getLogDirectory(), "metrics"); LogHelper logger = LogHelper.INSTANCE; logger.logMetrics("metrics: fred"); - String s = reader.getNewLines(); - assertThat(s, is(notNullValue())); - assertThat("metrics message log level", s, containsString("INFO")); - assertThat("metrics message content", s, containsString("fred")); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat("metrics message log level", str, containsString("INFO")); + assertThat("metrics message content", str, containsString("fred")); } @Test @@ -212,7 +212,7 @@ public class TestApplicationLogger { private void callUnsupportedOperationMethod(TriConsumer, LogFields, String[]> logMethod, ApplicationMsgs dummyMsg) { try { - logMethod.accept(dummyMsg, new LogFields(), new String[] {""}); + logMethod.accept(dummyMsg, new LogFields(), new String[] { "" }); org.junit.Assert.fail("method should have thrown execption"); // NOSONAR as code not reached } catch (UnsupportedOperationException e) { // Expected to reach here @@ -228,8 +228,8 @@ public class TestApplicationLogger { * @throws IOException */ private void validateLoggedMessage(ApplicationMsgs msg, LogReader reader, String severity) throws IOException { - String s = reader.getNewLines(); - assertThat(s, is(notNullValue())); - assertThat(msg.toString() + " log level", s, containsString(severity)); + String str = reader.getNewLines(); + assertThat(str, is(notNullValue())); + assertThat(msg.toString() + " log level", str, containsString(severity)); } } diff --git a/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java b/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java index 14fa9f3..d27396d 100644 --- a/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java +++ b/src/test/java/org/onap/aai/babel/parser/TestToscaParser.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -27,16 +27,15 @@ import static org.junit.Assert.assertThat; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; -import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; -import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Test; import org.onap.aai.babel.csar.extractor.InvalidArchiveException; import org.onap.aai.babel.csar.extractor.YamlExtractor; +import org.onap.aai.babel.util.ArtifactTestUtils; import org.onap.aai.babel.xml.generator.api.AaiArtifactGenerator; import org.onap.aai.babel.xml.generator.data.AdditionalParams; import org.onap.aai.babel.xml.generator.data.Artifact; @@ -57,9 +56,8 @@ public class TestToscaParser { @Before public void setup() throws FileNotFoundException, IOException { - URL url = TestToscaParser.class.getClassLoader().getResource("artifact-generator.properties"); - System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, url.getPath()); - + System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, + new ArtifactTestUtils().getResourcePath("artifact-generator.properties")); InputStream in = TestToscaParser.class.getClassLoader().getResourceAsStream("artifact-generator.properties"); Properties properties = new Properties(); properties.load(in); @@ -69,20 +67,18 @@ public class TestToscaParser { @Test public void testParserWithCsarFile() throws IOException, InvalidArchiveException { - byte[] csar = loadResource("compressedArtifacts/catalog_csar.csar"); - List ymlFiles = YamlExtractor.extract(csar, "catalog_csar.csar", "1.0"); + String csarResourceName = "catalog_csar.csar"; + byte[] csarBytes = new ArtifactTestUtils().getCompressedArtifact(csarResourceName); + List ymlFiles = new YamlExtractor().extract(csarBytes, csarResourceName, "1.0"); Map additionalParams = new HashMap<>(); additionalParams.put(AdditionalParams.SERVICE_VERSION.getName(), "1.0"); AaiArtifactGenerator generator = new AaiArtifactGenerator(); - GenerationData data = generator.generateArtifact(csar, ymlFiles, additionalParams); + GenerationData data = generator.generateArtifact(csarBytes, ymlFiles, additionalParams); assertThat(data.getErrorData().size(), is(equalTo(0))); assertThat(data.getResultData().size(), is(equalTo(2))); } - private byte[] loadResource(String resourceName) throws IOException { - return IOUtils.toByteArray(TestToscaParser.class.getClassLoader().getResource(resourceName)); - } } diff --git a/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java b/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java index 9310d2d..0bc7c31 100644 --- a/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java +++ b/src/test/java/org/onap/aai/babel/service/CsarToXmlConverterTest.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -22,7 +22,6 @@ package org.onap.aai.babel.service; import static org.junit.Assert.assertThat; -import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; @@ -49,29 +48,45 @@ import org.onap.aai.babel.xml.generator.data.GeneratorConstants; public class CsarToXmlConverterTest { private static final String ARTIFACT_GENERATOR_CONFIG = "artifact-generator.properties"; - private static final String CSAR_FOLDER = "compressedArtifacts"; - private static final String VALID_CSAR_FILE = "service-SdWanServiceTest-csar.csar"; private static final String INCORRECT_CSAR_NAME = "the_name_of_the_csar_file.csar"; private static final String SERVICE_VERSION = "1.0"; - private CsarToXmlConverter converter; - static { if (System.getProperty("APP_HOME") == null) { System.setProperty("APP_HOME", "."); } } + private enum CsarTest { + VALID_CSAR_FILE("service-SdWanServiceTest-csar.csar"), NO_YAML_FILES("noYmlFilesArchive.zip"); + + private String filename; + private ArtifactTestUtils artifactTestUtils = new ArtifactTestUtils(); + + CsarTest(String filename) { + this.filename = filename; + } + + public String getName() { + return filename; + } + + public byte[] getContent() throws IOException { + return artifactTestUtils.getCompressedArtifact(filename); + } + } + + // The class to be tested. + private CsarToXmlConverter converter; + @Rule public ExpectedException exception = ExpectedException.none(); - private ArtifactTestUtils artifactTestUtils; @Before public void setup() { System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, - CsarToXmlConverterTest.class.getClassLoader().getResource(ARTIFACT_GENERATOR_CONFIG).getPath()); + new ArtifactTestUtils().getResourcePath(ARTIFACT_GENERATOR_CONFIG)); converter = new CsarToXmlConverter(); - artifactTestUtils = new ArtifactTestUtils(); } @After @@ -86,12 +101,12 @@ public class CsarToXmlConverterTest { @Test(expected = NullPointerException.class) public void generateXmlFromCsar_missingName() throws CsarConverterException, IOException { - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), null, null); + converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), null, null); } @Test(expected = NullPointerException.class) public void generateXmlFromCsar_missingVersion() throws CsarConverterException, IOException { - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), INCORRECT_CSAR_NAME, null); + converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), INCORRECT_CSAR_NAME, null); } @Test(expected = CsarConverterException.class) @@ -101,25 +116,26 @@ public class CsarToXmlConverterTest { @Test(expected = CsarConverterException.class) public void generateXmlFromCsar_csarFileHasNoYmlFiles() throws CsarConverterException, IOException { - converter.generateXmlFromCsar(getCsar("noYmlFilesArchive.zip"), "noYmlFilesArchive.zip", SERVICE_VERSION); + converter.generateXmlFromCsar(CsarTest.NO_YAML_FILES.getContent(), "noYmlFilesArchive.zip", SERVICE_VERSION); } @Test - public void generateXmlFromCsar_artifactgenerator_config_systemPropertyNotSet() + public void testArtifactGeneratorConfigMissing() throws IOException, XmlArtifactGenerationException, CsarConverterException { exception.expect(CsarConverterException.class); exception.expectMessage("Cannot generate artifacts. artifactgenerator.config system property not configured"); // Unset the required system property System.clearProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE); - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), VALID_CSAR_FILE, SERVICE_VERSION); + converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), CsarTest.VALID_CSAR_FILE.getName(), + SERVICE_VERSION); } @Test public void generateXmlFromCsar() throws CsarConverterException, IOException, XmlArtifactGenerationException { Map expectedXmlFiles = createExpectedXmlFiles(); - List generatedArtifacts = - converter.generateXmlFromCsar(getCsar(VALID_CSAR_FILE), VALID_CSAR_FILE, SERVICE_VERSION); + List generatedArtifacts = converter.generateXmlFromCsar(CsarTest.VALID_CSAR_FILE.getContent(), + CsarTest.VALID_CSAR_FILE.getName(), SERVICE_VERSION); generatedArtifacts .forEach(ga -> assertThat("The content of " + ga.getName() + " must match the expected content", @@ -131,8 +147,8 @@ public class CsarToXmlConverterTest { protected String theExpected = expected; @Override - public boolean matches(Object o) { - return artifactTestUtils.compareXMLStrings((String) o, theExpected); + public boolean matches(Object item) { + return new ArtifactTestUtils().compareXmlStrings((String) item, theExpected); } @Override @@ -142,10 +158,6 @@ public class CsarToXmlConverterTest { }; } - private byte[] getCsar(String csarFileName) throws IOException { - return artifactTestUtils.loadResource(CSAR_FOLDER + File.separator + csarFileName); - } - private Map createExpectedXmlFiles() throws IOException { Map xmlMap = new HashMap<>(); @@ -156,7 +168,7 @@ public class CsarToXmlConverterTest { filesToLoad.add("AAI-SD-WAN-Test-VSP-resource-1.0.xml"); for (String filename : filesToLoad) { - xmlMap.put(filename, artifactTestUtils.loadResourceAsString("generatedXml" + File.separator + filename)); + xmlMap.put(filename, new ArtifactTestUtils().loadResourceAsString("generatedXml/" + filename)); } return xmlMap; diff --git a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java index 5840cd7..4cc8c8c 100644 --- a/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java +++ b/src/test/java/org/onap/aai/babel/service/TestGenerateArtifactsServiceImpl.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -26,14 +26,10 @@ import static org.junit.Assert.assertThat; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Paths; import java.security.cert.X509Certificate; import java.util.Collections; import java.util.List; import java.util.Map.Entry; -import java.util.stream.Collectors; import javax.inject.Inject; import javax.security.auth.x500.X500Principal; import javax.ws.rs.core.HttpHeaders; @@ -45,6 +41,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.onap.aai.auth.AAIMicroServiceAuth; +import org.onap.aai.babel.util.ArtifactTestUtils; import org.onap.aai.babel.xml.generator.data.GeneratorConstants; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ContextConfiguration; @@ -55,7 +52,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * */ @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = {"classpath:/babel-beans.xml"}) +@ContextConfiguration(locations = { "classpath:/babel-beans.xml" }) public class TestGenerateArtifactsServiceImpl { static { @@ -70,58 +67,55 @@ public class TestGenerateArtifactsServiceImpl { @BeforeClass public static void setup() { - URL url = TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource("artifact-generator.properties"); - System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, url.getPath()); + System.setProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE, + new ArtifactTestUtils().getResourcePath("artifact-generator.properties")); } @Test public void testInvalidCsarFile() throws URISyntaxException, IOException { - String jsonRequest = readstringFromFile("jsonFiles/invalid_csar_request.json"); - Response response = processJsonRequest(jsonRequest); + Response response = processJsonRequest("invalid_csar_request.json"); assertThat(response.getStatus(), is(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); assertThat(response.getEntity(), is("Error converting CSAR artifact to XML model.")); } @Test public void testInvalidJsonFile() throws URISyntaxException, IOException { - String jsonRequest = readstringFromFile("jsonFiles/invalid_json_request.json"); - Response response = processJsonRequest(jsonRequest); + Response response = processJsonRequest("invalid_json_request.json"); assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); assertThat(response.getEntity(), is("Malformed request.")); } @Test public void testMissingArtifactName() throws Exception { - String jsonRequest = readstringFromFile("jsonFiles/missing_artifact_name_request.json"); - Response response = processJsonRequest(jsonRequest); + Response response = processJsonRequest("missing_artifact_name_request.json"); assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); assertThat(response.getEntity(), is("No artifact name attribute found in the request body.")); } @Test public void testMissingArtifactVersion() throws Exception { - String jsonRequest = readstringFromFile("jsonFiles/missing_artifact_version_request.json"); - Response response = processJsonRequest(jsonRequest); + Response response = processJsonRequest("missing_artifact_version_request.json"); assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); assertThat(response.getEntity(), is("No artifact version attribute found in the request body.")); } @Test public void testMissingCsarFile() throws Exception { - String jsonRequest = readstringFromFile("jsonFiles/missing_csar_request.json"); - Response response = processJsonRequest(jsonRequest); + Response response = processJsonRequest("missing_csar_request.json"); assertThat(response.getStatus(), is(Response.Status.BAD_REQUEST.getStatusCode())); assertThat(response.getEntity(), is("No csar attribute found in the request body.")); } /** * Create a (mocked) HTTPS request and invoke the Babel generate artifacts API - * - * @param request for the Babel Service + * + * @param resource + * path to the incoming JSON request * @return the Response from the HTTP API * @throws URISyntaxException + * @throws IOException */ - private Response processJsonRequest(String jsonRequest) throws URISyntaxException { + private Response processJsonRequest(String resource) throws URISyntaxException, IOException { UriInfo mockUriInfo = Mockito.mock(UriInfo.class); Mockito.when(mockUriInfo.getRequestUri()).thenReturn(new URI("/validate")); // NOSONAR (mocked) Mockito.when(mockUriInfo.getPath(false)).thenReturn("validate"); // URI prefix is stripped by AJSC routing @@ -150,22 +144,24 @@ public class TestGenerateArtifactsServiceImpl { Mockito.when(mockCertificate.getSubjectX500Principal()) .thenReturn(new X500Principal("CN=test, OU=qa, O=Test Ltd, L=London, ST=London, C=GB")); - servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] {mockCertificate}); + servletRequest.setAttribute("javax.servlet.request.X509Certificate", new X509Certificate[] { mockCertificate }); servletRequest.setAttribute("javax.servlet.request.cipher_suite", ""); GenerateArtifactsServiceImpl service = new GenerateArtifactsServiceImpl(auth); - return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonRequest); + String jsonString = getRequestJson(resource); + return service.generateArtifacts(mockUriInfo, headers, servletRequest, jsonString); } - private List createSingletonList(String listItem) { - return Collections.singletonList(listItem); + private String getRequestJson(String resource) throws IOException, URISyntaxException { + return new ArtifactTestUtils().getRequestJson(resource); + } + + private String getResponseJson(String jsonResponse) throws IOException, URISyntaxException { + return new ArtifactTestUtils().getResponseJson(jsonResponse); } - private String readstringFromFile(String resourceFile) throws IOException, URISyntaxException { - return Files - .lines(Paths - .get(TestGenerateArtifactsServiceImpl.class.getClassLoader().getResource(resourceFile).toURI())) - .collect(Collectors.joining()); + private List createSingletonList(String listItem) { + return Collections.singletonList(listItem); } } diff --git a/src/test/java/org/onap/aai/babel/service/TestInfoService.java b/src/test/java/org/onap/aai/babel/service/TestInfoService.java index 1d60839..b97aa92 100644 --- a/src/test/java/org/onap/aai/babel/service/TestInfoService.java +++ b/src/test/java/org/onap/aai/babel/service/TestInfoService.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. diff --git a/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java index 69d7819..cf96d24 100644 --- a/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java +++ b/src/test/java/org/onap/aai/babel/util/ArtifactTestUtils.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -24,11 +24,15 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.IOException; +import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Paths; import java.util.Base64; import java.util.List; import java.util.Set; +import java.util.function.Function; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.custommonkey.xmlunit.Diff; @@ -40,19 +44,23 @@ import org.xml.sax.SAXException; */ public class ArtifactTestUtils { + private static final String JSON_REQUESTS_FOLDER = "jsonFiles/"; + private static final String JSON_RESPONSES_FOLDER = "response/"; + private static final String CSAR_INPUTS_FOLDER = "compressedArtifacts/"; + public void performYmlAsserts(List toscaFiles, List ymlPayloadsToLoad) { - assertThat("An unexpected number of yml files have been extracted", toscaFiles.size(), + assertThat("An unexpected number of YAML files have been extracted", toscaFiles.size(), is(ymlPayloadsToLoad.size())); - Set ymlPayloads = ymlPayloadsToLoad.stream().map(s -> { + Function loadResource = s -> { try { return loadResourceAsString(s); } catch (IOException e) { throw new RuntimeException(e); } - }).collect(Collectors.toSet()); - - compareXMLPayloads(toscaFiles, ymlPayloads); + }; + Set ymlPayloads = ymlPayloadsToLoad.stream().map(loadResource).collect(Collectors.toSet()); + compareXmlPayloads(toscaFiles, ymlPayloads); } /** @@ -62,7 +70,7 @@ public class ArtifactTestUtils { * @param string2 * @return true if similar */ - public boolean compareXMLStrings(String string1, String string2) { + public boolean compareXmlStrings(String string1, String string2) { boolean similar = false; try { @@ -74,7 +82,11 @@ public class ArtifactTestUtils { return similar; } - public byte[] loadResource(String resourceName) throws IOException { + public byte[] getCompressedArtifact(String resourceName) throws IOException { + return loadResourceBytes(CSAR_INPUTS_FOLDER + resourceName); + } + + public byte[] loadResourceBytes(String resourceName) throws IOException { return IOUtils.toByteArray(getResource(resourceName)); } @@ -82,26 +94,43 @@ public class ArtifactTestUtils { return IOUtils.toString(getResource(resourceName), Charset.defaultCharset()); } - private void compareXMLPayloads(List toscaFiles, Set ymlPayloads) { + public String getRequestJson(String resource) throws IOException { + return loadResourceAsString(JSON_REQUESTS_FOLDER + resource); + } + + public String getResponseJson(String jsonResponse) throws IOException, URISyntaxException { + return readstringFromFile(JSON_RESPONSES_FOLDER + jsonResponse); + } + + public String readstringFromFile(String resourceFile) throws IOException, URISyntaxException { + return Files.lines(Paths.get(getResource(resourceFile).toURI())).collect(Collectors.joining()); + } + + public String getResourcePath(String resourceName) { + return getResource(resourceName).getPath(); + } + + private URL getResource(String resourceName) { + return ArtifactTestUtils.class.getClassLoader().getResource(resourceName); + } + + private void compareXmlPayloads(List toscaFiles, Set ymlPayloads) { for (Artifact artifact : toscaFiles) { boolean payloadFound = false; for (String ymlPayload : ymlPayloads) { - if (compareXMLStrings(convertToString(artifact.getPayload()), ymlPayload)) { + if (compareXmlStrings(convertToString(artifact.getPayload()), ymlPayload)) { payloadFound = true; break; } } - assertThat("The content of each yml file must match the actual content of the file extracted (" + assertThat("The content of each YAML file must match the actual content of the file extracted (" + artifact.getName() + ")", payloadFound, is(true)); } } - private URL getResource(String resourceName) { - return ArtifactTestUtils.class.getClassLoader().getResource(resourceName); - } - private String convertToString(byte[] byteArray) { return new String(Base64.getDecoder().decode(byteArray), Charset.defaultCharset()); } + } diff --git a/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java b/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java index aff27cc..db7d882 100644 --- a/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java +++ b/src/test/java/org/onap/aai/babel/util/TestRequestValidator.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -39,10 +39,9 @@ public class TestRequestValidator { request.setCsar("UEsDBBQACAgIAGsrz0oAAAAAAAAAAAAAAAAJAAAAY3Nhci5tZXRhC3Z"); request.setArtifactVersion("1.0"); request.setArtifactName(null); - RequestValidator.validateRequest(request); + new RequestValidator().validateRequest(request); } - @Test public void testMissingArtifactVersionExceptionThrown() throws Exception { exception.expect(RequestValidationException.class); @@ -52,7 +51,7 @@ public class TestRequestValidator { request.setCsar("UEsDBBQACAgIAGsrz0oAAAAAAAAAAAAAAAAJAAAAY3Nhci5tZXRhC3Z"); request.setArtifactVersion(null); request.setArtifactName("hello"); - RequestValidator.validateRequest(request); + new RequestValidator().validateRequest(request); } @Test @@ -64,7 +63,7 @@ public class TestRequestValidator { request.setCsar(null); request.setArtifactVersion("1.0"); request.setArtifactName("hello"); - RequestValidator.validateRequest(request); + new RequestValidator().validateRequest(request); } } diff --git a/src/test/java/org/onap/aai/babel/xml/generator/model/TestVfModule.java b/src/test/java/org/onap/aai/babel/xml/generator/model/TestVfModule.java index b4ce96d..5572fe2 100644 --- a/src/test/java/org/onap/aai/babel/xml/generator/model/TestVfModule.java +++ b/src/test/java/org/onap/aai/babel/xml/generator/model/TestVfModule.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -70,7 +70,7 @@ public class TestVfModule { } @Test - public void testNonMemberWidgetToVF() { + public void testNonMemberWidgetToVf() { VfModule vf = new VfModule(); Widget widget = Widget.getWidget(Type.SERVICE); vf.setMembers(Collections.singletonList(widget.getId())); @@ -78,19 +78,19 @@ public class TestVfModule { } @Test - public void testAddServiceWidgetToVF() { + public void testAddServiceWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.SERVICE); } @Test - public void testAddVServerWidgetToVF() { + public void testAddVServerWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.VSERVER); } @Test - public void testAddLIntfWidgetToVF() { + public void testAddLIntfWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.LINT); addWidgetToModule(vf, Type.VSERVER); @@ -98,7 +98,7 @@ public class TestVfModule { } @Test - public void testAddVolumeWidgetToVF() { + public void testAddVolumeWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.VOLUME); addWidgetToModule(vf, Type.VSERVER); @@ -106,7 +106,7 @@ public class TestVfModule { } @Test - public void testAddOAMNetworkWidgetToVF() { + public void testAddOamNetworkWidgetToVf() { VfModule vf = new VfModule(); addWidgetToModule(vf, Type.OAM_NETWORK); } diff --git a/src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java b/src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java index 6f2dcca..1865968 100644 --- a/src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java +++ b/src/test/java/org/onap/aai/babel/xml/generator/model/TestWidget.java @@ -1,5 +1,5 @@ /** - * ============LICENSE_START======================================================= + * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. @@ -51,5 +51,4 @@ public class TestWidget { new VolumeGroupWidget().getWidgetType(); } - } diff --git a/src/test/resources/response/response.json b/src/test/resources/response/response.json index a5c7088..e2a0951 100644 --- a/src/test/resources/response/response.json +++ b/src/test/resources/response/response.json @@ -1 +1 @@ -[{"name":"AAI-29NFOD_S-service-1.0.xml","type":"MODEL","payload":"\n 4da8d1e8-f59a-4370-84ea-c6de836821fc\n service\n \n \n a76ed81f-23d2-4e69-8972-eb1c69855e64\n 29NFOD_S\n 1.0\n 29NFOD\n \n \n T\n unbounded\n \n \n T\n unbounded\n \n \n \n model-ver\n \n model-ver.model-version-id\n 3f283439-4e0e-4a6a-9b31-da5d0cb05b52\n \n \n model.model-invariant-id\n bc3622d2-a645-4806-80f2-96b04a866bbf\n \n \n \n \n \n \n \n model-ver\n \n model-ver.model-version-id\n 46b92144-923a-4d20-b85a-3cbd847668a9\n \n \n model.model-invariant-id\n 82194af1-3c2c-485a-8f44-420e22a9eaa4\n \n \n \n \n \n \n \n"},{"name":"AAI-29NFOD-resource-1.0.xml","type":"MODEL","payload":"\n bc3622d2-a645-4806-80f2-96b04a866bbf\n resource\n \n \n 3f283439-4e0e-4a6a-9b31-da5d0cb05b52\n 29NFOD\n 1.0\n 29NFOD\n \n \n T\n unbounded\n \n \n \n model-ver\n \n model-ver.model-version-id\n 93a6166f-b3d5-4f06-b4ba-aed48d009ad9\n \n \n model.model-invariant-id\n acc6edd8-a8d4-4b93-afaa-0994068be14c\n \n \n \n \n \n \n \n"},{"name":"vnfVendorImageConfigurations","type":"VNFCATALOG","payload":"[{\"application\":\"VM00\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.1\"},{\"application\":\"VM00\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.9\"},{\"application\":\"VM01\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.1\"},{\"application\":\"VM01\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.9\"}]"}] \ No newline at end of file +[{"name":"AAI-29NFOD_S-service-1.0.xml","type":"MODEL","payload":"\n 4da8d1e8-f59a-4370-84ea-c6de836821fc\n service\n \n \n a76ed81f-23d2-4e69-8972-eb1c69855e64\n 29NFOD_S\n 1.0\n 29NFOD\n \n \n T\n unbounded\n \n \n T\n unbounded\n \n \n \n model-ver\n \n model-ver.model-version-id\n 3f283439-4e0e-4a6a-9b31-da5d0cb05b52\n \n \n model.model-invariant-id\n bc3622d2-a645-4806-80f2-96b04a866bbf\n \n \n \n \n \n \n \n model-ver\n \n model-ver.model-version-id\n 46b92144-923a-4d20-b85a-3cbd847668a9\n \n \n model.model-invariant-id\n 82194af1-3c2c-485a-8f44-420e22a9eaa4\n \n \n \n \n \n \n \n"},{"name":"AAI-29NFOD-resource-1.0.xml","type":"MODEL","payload":"\n bc3622d2-a645-4806-80f2-96b04a866bbf\n resource\n \n \n 3f283439-4e0e-4a6a-9b31-da5d0cb05b52\n 29NFOD\n 1.0\n 29NFOD\n \n \n T\n unbounded\n \n \n \n model-ver\n \n model-ver.model-version-id\n 93a6166f-b3d5-4f06-b4ba-aed48d009ad9\n \n \n model.model-invariant-id\n acc6edd8-a8d4-4b93-afaa-0994068be14c\n \n \n \n \n \n \n \n"},{"name":"vnfVendorImageConfigurations","type":"VNFCATALOG","payload":"[{\"application\":\"VM00\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.1\"},{\"application\":\"VM00\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.9\"},{\"application\":\"VM01\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.1\"},{\"application\":\"VM01\",\"application-vendor\":\"29NFOD\",\"application-version\":\"3.16.9\"}]"}] \ No newline at end of file -- 2.16.6