diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/IMPORTANT.md b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/IMPORTANT.md index 3e8201b35..8e2526efb 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/IMPORTANT.md +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/IMPORTANT.md @@ -7,7 +7,7 @@ The structure of this folder is being reworked. Classes are being moved based on - [x] Aria Automation - [ ] Aria Orchestrator - [ ] Aria Logs -- [ ] Aria Operations +- [x] Aria Operations - [ ] SSH - [ ] vCD - [ ] CS diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/PackageStoreFactory.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/PackageStoreFactory.java index d15ebe316..408c716ef 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/PackageStoreFactory.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/PackageStoreFactory.java @@ -26,7 +26,11 @@ import org.slf4j.LoggerFactory; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.store.VropsPackageStore; import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; +import com.vmware.pscoe.iac.artifact.aria.automation.pack.VraNgPackageStore; import com.vmware.pscoe.iac.artifact.cli.CliManagerFactory; import com.vmware.pscoe.iac.artifact.cli.CliManagerVrops; import com.vmware.pscoe.iac.artifact.model.Version; diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/automation/package/VraNgPackageStore.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/automation/pack/VraNgPackageStore.java similarity index 95% rename from common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/automation/package/VraNgPackageStore.java rename to common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/automation/pack/VraNgPackageStore.java index ec5777083..f6d41410b 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/automation/package/VraNgPackageStore.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/automation/pack/VraNgPackageStore.java @@ -16,7 +16,7 @@ * LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact; +package com.vmware.pscoe.iac.artifact.aria.automation.pack; import java.io.File; import java.io.IOException; @@ -25,12 +25,15 @@ import java.util.Collections; import java.util.List; +import com.vmware.pscoe.iac.artifact.GenericPackageStore; +import com.vmware.pscoe.iac.artifact.PackageManager; +import com.vmware.pscoe.iac.artifact.PackageStore; import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageContent.Content; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageAdapter; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageContent; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageAdapter; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageContent; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import com.vmware.pscoe.iac.artifact.aria.automation.store.VraNgTypeStoreFactory; @@ -58,7 +61,7 @@ public class VraNgPackageStore extends GenericPackageStore { private static final String VROPS_AUTH_TOKEN_URI = "/suite-api/api/auth/token/acquire"; @@ -51,7 +52,7 @@ public class RestClientVropsAuthNInterceptor extends RestClientRequestIntercepto private String vropsAuthToken; private LocalDateTime vropsTokenExpirationTime; - protected RestClientVropsAuthNInterceptor(ConfigurationVrops configuration, RestTemplate restTemplate) { + public RestClientVropsAuthNInterceptor(ConfigurationVrops configuration, RestTemplate restTemplate) { super(configuration, restTemplate); } @@ -74,7 +75,8 @@ public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttp private void acquireToken(HttpRequest request) throws JsonProcessingException { logger.info("Acquiring VROPS auth token."); - final URI vropsTokenUri = UriComponentsBuilder.newInstance().scheme(request.getURI().getScheme()).host(getConfiguration().getHost()) + final URI vropsTokenUri = UriComponentsBuilder.newInstance().scheme(request.getURI().getScheme()) + .host(getConfiguration().getHost()) .port(getConfiguration().getPort()).path(VROPS_AUTH_TOKEN_URI).build().toUri(); logger.info("VROPS Auth Token URL: {}", vropsTokenUri); @@ -87,11 +89,13 @@ private void acquireToken(HttpRequest request) throws JsonProcessingException { payload.put("authSource", getConfiguration().getVropsAuthSource()); final HttpEntity entity = new HttpEntity<>(new ObjectMapper().writeValueAsString(payload), headers); - ResponseEntity response = getRestTemplate().exchange(vropsTokenUri, HttpMethod.POST, entity, String.class); + ResponseEntity response = getRestTemplate().exchange(vropsTokenUri, HttpMethod.POST, entity, + String.class); final DocumentContext responseBody = JsonPath.parse(response.getBody()); final long ttl = responseBody.read("$.validity"); - this.vropsTokenExpirationTime = LocalDateTime.now(ZoneOffset.UTC).plus(ttl, ChronoField.MINUTE_OF_HOUR.getBaseUnit()); + this.vropsTokenExpirationTime = LocalDateTime.now(ZoneOffset.UTC).plus(ttl, + ChronoField.MINUTE_OF_HOUR.getBaseUnit()); this.vropsAuthToken = responseBody.read("$.token"); } diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/RestClientVropsBasicAuthInterceptor.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/rest/RestClientVropsBasicAuthInterceptor.java similarity index 81% rename from common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/RestClientVropsBasicAuthInterceptor.java rename to common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/rest/RestClientVropsBasicAuthInterceptor.java index 24e0c92de..879695283 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/RestClientVropsBasicAuthInterceptor.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/rest/RestClientVropsBasicAuthInterceptor.java @@ -12,7 +12,7 @@ * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact.rest; +package com.vmware.pscoe.iac.artifact.aria.operations.rest; import java.io.IOException; @@ -22,11 +22,12 @@ import org.springframework.http.client.support.BasicAuthenticationInterceptor; import org.springframework.web.client.RestTemplate; -import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.rest.RestClientRequestInterceptor; public class RestClientVropsBasicAuthInterceptor extends RestClientRequestInterceptor { - protected RestClientVropsBasicAuthInterceptor(ConfigurationVrops configuration, RestTemplate restTemplate) { + public RestClientVropsBasicAuthInterceptor(ConfigurationVrops configuration, RestTemplate restTemplate) { super(configuration, restTemplate); } diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/VropsPackageStore.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/VropsPackageStore.java similarity index 80% rename from common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/VropsPackageStore.java rename to common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/VropsPackageStore.java index 825d6a6f4..1569497a0 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/VropsPackageStore.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/VropsPackageStore.java @@ -12,7 +12,7 @@ * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact; +package com.vmware.pscoe.iac.artifact.aria.operations.store; import java.io.File; import java.io.FileFilter; @@ -60,6 +60,9 @@ import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.jcraft.jsch.JSchException; +import com.vmware.pscoe.iac.artifact.GenericPackageStore; +import com.vmware.pscoe.iac.artifact.PackageManager; +import com.vmware.pscoe.iac.artifact.PackageStore; import com.vmware.pscoe.iac.artifact.cli.CliManagerVrops; import com.vmware.pscoe.iac.artifact.cli.ZipUtilities; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationException; @@ -67,19 +70,19 @@ import com.vmware.pscoe.iac.artifact.model.PackageContent; import com.vmware.pscoe.iac.artifact.model.PackageContent.Content; import com.vmware.pscoe.iac.artifact.model.Version; -import com.vmware.pscoe.iac.artifact.model.vrops.VropsPackageDescriptor; -import com.vmware.pscoe.iac.artifact.model.vrops.VropsPackageMemberType; -import com.vmware.pscoe.iac.artifact.rest.RestClientVrops; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.AlertDefinitionDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.AuthGroupDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.CustomGroupDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.PolicyDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.RecommendationDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.ReportDefinitionDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.SupermetricDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.SymptomDefinitionDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.ViewDefinitionDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.AuthUserDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.store.models.VropsPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.operations.store.models.VropsPackageMemberType; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.models.AlertDefinitionDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.AuthGroupDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.CustomGroupDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.PolicyDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.RecommendationDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.ReportDefinitionDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.SupermetricDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.SymptomDefinitionDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.ViewDefinitionDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.AuthUserDTO; /** * This is the class that abstracts the operations for working with vROps @@ -163,7 +166,7 @@ public final class VropsPackageStore extends GenericPackageStore getPackages() { /** * Exports all packages. + * * @param packages the packages to export - * @param dryrun whether it should be dry run + * @param dryrun whether it should be dry run * @return the exported packages */ @Override @@ -254,28 +265,36 @@ public List exportAllPackages(final List packages, final boole /** * Imports all packages. - * @param pkg the packages to import - * @param dryrun whether it should be dry run + * + * @param pkg the packages to import + * @param dryrun whether it should be dry run * @param enableBackup whether it should back up the packages on import * @return the imported package */ @Override public List importAllPackages(final List pkg, final boolean dryrun, final boolean enableBackup) { - return this.importAllPackages(pkg, dryrun, false, enableBackup); + return this.importAllPackages(pkg, dryrun, false, enableBackup); } /** - * Implement the push use case, so push the packages that are packed in the local project ot the remote vROps server and if we are not ia a dryrun mode, then + * Implement the push use case, so push the packages that are packed in the + * local project ot the remote vROps server and if we are not ia a dryrun mode, + * then * effectively import it into vROps. - * @param packages Locally available packages. - * @param dryrun Just test the whole process without actually import the packages in vROps. + * + * @param packages Locally available packages. + * @param dryrun Just test the whole process without actually import the + * packages in vROps. * @param mergePackages Whether to merge the packages - * @param enableBackup Whether to enable backup - * @return The list of pushed packages. The actual package objects may be different, for example the file content they are associated with may be different file on - * the file system. + * @param enableBackup Whether to enable backup + * @return The list of pushed packages. The actual package objects may be + * different, for example the file content they are associated with may + * be different file on + * the file system. */ @Override - public List importAllPackages(final List packages, final boolean dryrun, final boolean mergePackages, final boolean enableBackup) { + public List importAllPackages(final List packages, final boolean dryrun, + final boolean mergePackages, final boolean enableBackup) { validateFilesystem(packages); List sourceEndpointPackages = packages; @@ -292,14 +311,17 @@ public List importAllPackages(final List packages, final boole } /** - * Implement the pull use case, so pull all of the packages described in the {@code vropsPackageDescriptor} (constructed from content.yaml). - * @param vropsPackage vropsPackage + * Implement the pull use case, so pull all of the packages described in the + * {@code vropsPackageDescriptor} (constructed from content.yaml). + * + * @param vropsPackage vropsPackage * @param vropsPackageDescriptor vropsPackageDescriptor - * @param dryrun dryrun + * @param dryrun dryrun * @return package */ @Override - public Package exportPackage(final Package vropsPackage, final VropsPackageDescriptor vropsPackageDescriptor, final boolean dryrun) { + public Package exportPackage(final Package vropsPackage, final VropsPackageDescriptor vropsPackageDescriptor, + final boolean dryrun) { logger.info(String.format(PackageStore.PACKAGE_EXPORT, vropsPackage)); if (!Files.exists(tempVropsExportDir.toPath())) { @@ -382,7 +404,8 @@ public Package exportPackage(final Package vropsPackage, final VropsPackageDescr PackageManager.copyContents(tempVropsExportDir, destDir); } } catch (IOException ioe) { - throw new RuntimeException(String.format("Cannot copy content of downloaded and extracted package from temp dir %s to actual project dir %s : %s", + throw new RuntimeException(String.format( + "Cannot copy content of downloaded and extracted package from temp dir %s to actual project dir %s : %s", tempVropsExportDir.getAbsolutePath(), vropsPackage.getFilesystemPath(), ioe.getMessage())); } finally { try { @@ -398,9 +421,11 @@ public Package exportPackage(final Package vropsPackage, final VropsPackageDescr /** * Export views from vROPs. + * * @param vropsPackage Package to export views to. - * @param viewNames List of views to be exported. - * @throws RuntimeException if there are no views on vROPs server or the export fails. + * @param viewNames List of views to be exported. + * @throws RuntimeException if there are no views on vROPs server or the export + * fails. */ private void exportViews(final Package vropsPackage, final List viewNames) { ViewDefinitionDTO allViewDefinitions = restClient.getAllViewDefinitions(); @@ -422,7 +447,8 @@ private void exportViews(final Package vropsPackage, final List viewName filteredViews.forEach(view -> copyViewToFilesystem(view, viewsDir)); } catch (JSchException e) { String message = "Unable to export views in package '%s', error in connection to '%s'. '%s' : '%s' Use command '%s' for troubleshooting"; - message = String.format(message, vropsPackage.getFQName(), cliManager, e.getClass().getName(), e.getMessage(), cliManager.toSshComand()); + message = String.format(message, vropsPackage.getFQName(), cliManager, e.getClass().getName(), + e.getMessage(), cliManager.toSshComand()); logger.error(message); throw new RuntimeException(message, e); } finally { @@ -432,9 +458,11 @@ private void exportViews(final Package vropsPackage, final List viewName /** * Export super metrics from vROPs. - * @param vropsPackage Package to export super metrics to. - * @param superMetricNames List of super metrics to be exported. - * @throws RuntimeException if there are no super metrics on vROPs server or the export fails. + * + * @param vropsPackage Package to export super metrics to. + * @param superMetricNames List of super metrics to be exported. + * @throws RuntimeException if there are no super metrics on vROPs server or the + * export fails. */ private void exportSuperMetrics(final Package vropsPackage, final List superMetricNames) { SupermetricDTO allSupermetrics = restClient.getAllSupermetrics(); @@ -458,7 +486,8 @@ private void exportSuperMetrics(final Package vropsPackage, final List s filteredSupermetrics.forEach(superMetric -> this.copySuperMetricToFilesystem(superMetric, superMetricsDir)); } catch (JSchException e) { String message = "Unable to export super metrics in package '%s', error in connection to '%s'. '%s' : '%s' Use command '%s' for troubleshooting"; - message = String.format(message, vropsPackage.getFQName(), cliManager, e.getClass().getName(), e.getMessage(), cliManager.toSshComand()); + message = String.format(message, vropsPackage.getFQName(), cliManager, e.getClass().getName(), + e.getMessage(), cliManager.toSshComand()); logger.error(message); throw new RuntimeException(message, e); } finally { @@ -468,7 +497,8 @@ private void exportSuperMetrics(final Package vropsPackage, final List s /** * Export metrics configs from vROPs. - * @param vropsPackage Package to export metric configs to. + * + * @param vropsPackage Package to export metric configs to. * @param metricConfigNames List of metric configs to be exported. * @throws RuntimeException If the the export fails. */ @@ -483,7 +513,9 @@ private void exportMetricConfigs(final Package vropsPackage, final List cliManager.connect(); for (String metricConfigName : metricConfigNames) { if (metricConfigName.contains(WILDCARD_MATCH_SYMBOL)) { - logger.warn("Unable to export metric configs with pattern '{}' as vROPs metric config export does not support regex", metricConfigName); + logger.warn( + "Unable to export metric configs with pattern '{}' as vROPs metric config export does not support regex", + metricConfigName); } else { // Could be stored with or without extension in vROps, so search for both this.copyMetricConfigToFilesystem(metricConfigName, metricConfigsDir); @@ -492,7 +524,8 @@ private void exportMetricConfigs(final Package vropsPackage, final List } } catch (JSchException e) { String message = "Unable to export metric config in package '%s', error in connection to '%s'. '%s' : '%s' Use command '%s' for troubleshooting"; - message = String.format(message, vropsPackage.getFQName(), cliManager, e.getClass().getName(), e.getMessage(), cliManager.toSshComand()); + message = String.format(message, vropsPackage.getFQName(), cliManager, e.getClass().getName(), + e.getMessage(), cliManager.toSshComand()); logger.error(message); throw new RuntimeException(message, e); } finally { @@ -502,18 +535,20 @@ private void exportMetricConfigs(final Package vropsPackage, final List /** * Copy the exported views from vROPs to the local file system. + * * @param view view to be copied. - * @param dir directory where the view to be copied. + * @param dir directory where the view to be copied. * @throws RuntimeException If the the copy fails. */ private void copyViewToFilesystem(final String view, final File dir) { try { - File viewDir = new File(tempDir, "iac-view-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis()); + File viewDir = new File(tempDir, + "iac-view-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis()); viewDir.mkdirs(); cliManager.exportView(view, viewDir); File zip = new File(viewDir, view + ".zip"); ZipUtilities.unzip(zip, viewDir); - + File content = new File(viewDir, "content.xml"); moveFile(content, new File(dir, view + ".xml")); zip.delete(); @@ -528,16 +563,18 @@ private void copyViewToFilesystem(final String view, final File dir) { /** * Copy the exported super metric from vROPs to the local file system. + * * @param superMetric super metric to be copied. - * @param dir directory where the view to be copied. + * @param dir directory where the view to be copied. * @throws RuntimeException If the the copy fails. */ private void copySuperMetricToFilesystem(final String superMetric, final File dir) { try { - File superMetricDir = new File(this.tempDir, "iac-supermetric-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis()); + File superMetricDir = new File(this.tempDir, + "iac-supermetric-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis()); superMetricDir.mkdirs(); this.cliManager.exportSuperMetric(superMetric, superMetricDir); - File content = new File(superMetricDir, superMetric + ".json"); + File content = new File(superMetricDir, superMetric + ".json"); moveFile(content, new File(dir, superMetric + ".json")); mergeLocalizationResources(new File(superMetricDir, "resources"), new File(dir, "resources")); } catch (JSchException | IOException e) { @@ -550,21 +587,23 @@ private void copySuperMetricToFilesystem(final String superMetric, final File di /** * Copy the exported metric config from vROPs to the local file system. + * * @param metricConfig metric config to be copied. - * @param dir directory where the view to be copied. + * @param dir directory where the view to be copied. * @throws RuntimeException If the the copy fails. */ private void copyMetricConfigToFilesystem(final String metricConfig, final File dir) { try { - File metricConfigsDir = new File(this.tempDir, "iac-metricconfig-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis()); + File metricConfigsDir = new File(this.tempDir, + "iac-metricconfig-" + UUID.randomUUID().toString() + "-" + System.currentTimeMillis()); metricConfigsDir.mkdirs(); this.cliManager.exportMetricConfig(metricConfig, metricConfigsDir); - File content = new File(metricConfigsDir, metricConfig); + File content = new File(metricConfigsDir, metricConfig); if (content.exists()) { moveFile(content, new File(dir, metricConfig)); } - + } catch (JSchException | IOException e) { String message = "Unable to pull metric config '%s' from remote vROps location '%s' to local filesystem '%s' : '%s'"; message = String.format(message, metricConfig, cliManager, e.getClass().getName(), e.getMessage()); @@ -575,8 +614,9 @@ private void copyMetricConfigToFilesystem(final String metricConfig, final File /** * Export dashboards from vROPs. - * @param vropsPackage Package to export dashboards to. - * @param dashboardNames List of dashboards to be exported. + * + * @param vropsPackage Package to export dashboards to. + * @param dashboardNames List of dashboards to be exported. * @throws RuntimeException if the export fails. */ private void exportDashboards(final Package vropsPackage, final List dashboardNames) { @@ -587,7 +627,9 @@ private void exportDashboards(final Package vropsPackage, final List das cliManager.connect(); for (String dashboardName : dashboardNames) { if (dashboardName.contains(WILDCARD_MATCH_SYMBOL)) { - logger.warn("Unable to export dashboards with pattern '{}' as vROPs dashboard export does not support regex", dashboardName); + logger.warn( + "Unable to export dashboards with pattern '{}' as vROPs dashboard export does not support regex", + dashboardName); } else { copyDashboardToFilesystem(dashboardName, dashboardsDir); } @@ -600,7 +642,8 @@ private void exportDashboards(final Package vropsPackage, final List das storeDashboardActivationMetadata(dashboardsDir, dashboardNames, true); } catch (JSchException e) { String message = "Unable to pull dashboards '%s' from remote vROPs location to local package '%s' : '%s' : '%s' Use command '%s' for troubleshooting remote SSH connection"; - message = String.format(message, String.join(", ", dashboardNames), vropsPackage.getFQName(), e.getClass().getName(), e.getMessage(), + message = String.format(message, String.join(", ", dashboardNames), vropsPackage.getFQName(), + e.getClass().getName(), e.getMessage(), cliManager.toSshComand()); logger.error(message); throw new RuntimeException(message, e); @@ -611,9 +654,11 @@ private void exportDashboards(final Package vropsPackage, final List das /** * Export reports from vROPs. + * * @param vropsPackage Package to export reports to. - * @param reportNames List of reports to be exported. - * @throws RuntimeException if there are no reports on the server or the export fails. + * @param reportNames List of reports to be exported. + * @throws RuntimeException if there are no reports on the server or the export + * fails. */ private void exportReports(final Package vropsPackage, final List reportNames) { ReportDefinitionDTO allReportDefinitions = restClient.getAllReportDefinitions(); @@ -635,7 +680,8 @@ private void exportReports(final Package vropsPackage, final List report filteredReports.forEach(report -> copyReportToFilesystem(report, reportsDir)); } catch (JSchException e) { String message = "Unable to pull reports '%s' from remote vROPs location to local package '%s' : '%s' : '%s' Use command '%s' for troubleshooting remote SSH connection"; - message = String.format(message, String.join(", ", reportNames), vropsPackage.getFQName(), e.getClass().getName(), e.getMessage(), + message = String.format(message, String.join(", ", reportNames), vropsPackage.getFQName(), + e.getClass().getName(), e.getMessage(), cliManager.toSshComand()); logger.error(message); throw new RuntimeException(message, e); @@ -645,9 +691,11 @@ private void exportReports(final Package vropsPackage, final List report } /** - * Import definitions in vROPs. The following definitions are supported: alert definitions, symptom definitions, recommendations. + * Import definitions in vROPs. The following definitions are supported: alert + * definitions, symptom definitions, recommendations. + * * @param vropsPackage Package to export reports to. - * @param tmpDir Directory where the definitions will be read from. + * @param tmpDir Directory where the definitions will be read from. * @throws RuntimeException if the import fails. */ private void importDefinitions(final Package vropsPackage, final File tmpDir) throws IOException { @@ -655,24 +703,29 @@ private void importDefinitions(final Package vropsPackage, final File tmpDir) th ObjectMapper mapper = new ObjectMapper(); Map dependentDefinitionsMap = new HashMap<>(); - List symptomDefinitionFiles = addDefinitionsToImportList(tmpDir, VropsPackageMemberType.SYMPTOM_DEFINITION); + List symptomDefinitionFiles = addDefinitionsToImportList(tmpDir, + VropsPackageMemberType.SYMPTOM_DEFINITION); Map symptomDefinitionsMap = new HashMap<>(); for (File definitionFile : symptomDefinitionFiles) { String defninitionJson; try { defninitionJson = FileUtils.readFileToString(definitionFile, StandardCharsets.UTF_8); - SymptomDefinitionDTO.SymptomDefinition symptomDefinition = mapper.readValue(defninitionJson, SymptomDefinitionDTO.SymptomDefinition.class); + SymptomDefinitionDTO.SymptomDefinition symptomDefinition = mapper.readValue(defninitionJson, + SymptomDefinitionDTO.SymptomDefinition.class); symptomDefinitionsMap.put(symptomDefinition.getId(), symptomDefinition); } catch (IOException e) { - messages.append(String.format("Error reading %s : %s", VropsPackageMemberType.SYMPTOM_DEFINITION, e.getMessage())); + messages.append(String.format("Error reading %s : %s", VropsPackageMemberType.SYMPTOM_DEFINITION, + e.getMessage())); } catch (Exception e) { - messages.append(String.format("Error parsing %s : %s", VropsPackageMemberType.SYMPTOM_DEFINITION, e.getMessage())); + messages.append(String.format("Error parsing %s : %s", VropsPackageMemberType.SYMPTOM_DEFINITION, + e.getMessage())); } } symptomDefinitionsMap.keySet().stream().forEach(item -> { dependentDefinitionsMap.put(item, symptomDefinitionsMap.get(item)); }); - restClient.importDefinitionsInVrops(symptomDefinitionsMap, VropsPackageMemberType.SYMPTOM_DEFINITION, dependentDefinitionsMap); + restClient.importDefinitionsInVrops(symptomDefinitionsMap, VropsPackageMemberType.SYMPTOM_DEFINITION, + dependentDefinitionsMap); List recommendationFiles = addDefinitionsToImportList(tmpDir, VropsPackageMemberType.RECOMMENDATION); Map recommendationsMap = new HashMap<>(); @@ -680,18 +733,22 @@ private void importDefinitions(final Package vropsPackage, final File tmpDir) th String recommendationJson; try { recommendationJson = FileUtils.readFileToString(recommendationFile, StandardCharsets.UTF_8); - RecommendationDTO.Recommendation recommendation = mapper.readValue(recommendationJson, RecommendationDTO.Recommendation.class); + RecommendationDTO.Recommendation recommendation = mapper.readValue(recommendationJson, + RecommendationDTO.Recommendation.class); recommendationsMap.put(recommendation.getId(), recommendation); } catch (IOException e) { - messages.append(String.format("Error reading %s : %s", VropsPackageMemberType.RECOMMENDATION, e.getMessage())); + messages.append( + String.format("Error reading %s : %s", VropsPackageMemberType.RECOMMENDATION, e.getMessage())); } catch (Exception e) { - messages.append(String.format("Error parsing %s : %s", VropsPackageMemberType.RECOMMENDATION, e.getMessage())); + messages.append( + String.format("Error parsing %s : %s", VropsPackageMemberType.RECOMMENDATION, e.getMessage())); } } recommendationsMap.keySet().stream().forEach(item -> { dependentDefinitionsMap.put(item, recommendationsMap.get(item)); }); - restClient.importDefinitionsInVrops(recommendationsMap, VropsPackageMemberType.RECOMMENDATION, dependentDefinitionsMap); + restClient.importDefinitionsInVrops(recommendationsMap, VropsPackageMemberType.RECOMMENDATION, + dependentDefinitionsMap); List alertDefinitionFiles = addDefinitionsToImportList(tmpDir, VropsPackageMemberType.ALERT_DEFINITION); Map alertDefinitionsMap = new HashMap<>(); @@ -699,18 +756,22 @@ private void importDefinitions(final Package vropsPackage, final File tmpDir) th String defninitionJson; try { defninitionJson = FileUtils.readFileToString(definitionFile, StandardCharsets.UTF_8); - AlertDefinitionDTO.AlertDefinition alertDefinition = mapper.readValue(defninitionJson, AlertDefinitionDTO.AlertDefinition.class); + AlertDefinitionDTO.AlertDefinition alertDefinition = mapper.readValue(defninitionJson, + AlertDefinitionDTO.AlertDefinition.class); alertDefinitionsMap.put(alertDefinition.getId(), alertDefinition); } catch (IOException e) { - messages.append(String.format("Error reading %s : %s", VropsPackageMemberType.ALERT_DEFINITION, e.getMessage())); + messages.append(String.format("Error reading %s : %s", VropsPackageMemberType.ALERT_DEFINITION, + e.getMessage())); } catch (Exception e) { - messages.append(String.format("Error parsing %s : %s", VropsPackageMemberType.ALERT_DEFINITION, e.getMessage())); + messages.append(String.format("Error parsing %s : %s", VropsPackageMemberType.ALERT_DEFINITION, + e.getMessage())); } } alertDefinitionsMap.keySet().stream().forEach(item -> { dependentDefinitionsMap.put(item, alertDefinitionsMap.get(item)); }); - restClient.importDefinitionsInVrops(alertDefinitionsMap, VropsPackageMemberType.ALERT_DEFINITION, dependentDefinitionsMap); + restClient.importDefinitionsInVrops(alertDefinitionsMap, VropsPackageMemberType.ALERT_DEFINITION, + dependentDefinitionsMap); if (messages.length() > 0) { throw new IOException(messages.toString()); @@ -718,13 +779,18 @@ private void importDefinitions(final Package vropsPackage, final File tmpDir) th } /** - * Activate / Deactivate dashboards per user or group, based on the data in the activation metadata file. - * @param rootDir Root directory where the dashboards and the metadata files reside. + * Activate / Deactivate dashboards per user or group, based on the data in the + * activation metadata file. + * + * @param rootDir Root directory where the dashboards and the metadata + * files reside. * @param isGroupActivation flag whether group activation is specified. - * @throws RuntimeException if the activation / deactivation per user or group fails. + * @throws RuntimeException if the activation / deactivation per user or group + * fails. */ private void manageDashboardActivation(final File rootDir, final boolean isGroupActivation) { - Map>> activationMetadata = this.getDashboardActivationMetadata(rootDir, isGroupActivation); + Map>> activationMetadata = this.getDashboardActivationMetadata(rootDir, + isGroupActivation); if (activationMetadata.isEmpty()) { return; } @@ -739,26 +805,33 @@ private void manageDashboardActivation(final File rootDir, final boolean isGroup if (resources.isEmpty()) { return; } - // check whether all of the users with that dashboard will be activated / deactivated + // check whether all of the users with that dashboard will be activated / + // deactivated // exist on the target vROPs - List missingResources = isGroupActivation ? this.getMissingGroups(resources) : this.getMissingUsers(resources); + List missingResources = isGroupActivation ? this.getMissingGroups(resources) + : this.getMissingUsers(resources); if (missingResources != null && !missingResources.isEmpty()) { - throw new RuntimeException(String.format("Unable to %s dashboard '%s' as resourcee of type %s '%s' do not exists on target vROPs", action, + throw new RuntimeException(String.format( + "Unable to %s dashboard '%s' as resourcee of type %s '%s' do not exists on target vROPs", + action, dashboard, resourceType, String.join(", ", missingResources.toArray(new String[0])))); } switch (action) { case ACTION_ACTIVATE: { - logger.info("Activating dashboard: '{}' for resource of type {}: '{}'", dashboard, resourceType, String.join(", ", resources)); + logger.info("Activating dashboard: '{}' for resource of type {}: '{}'", dashboard, resourceType, + String.join(", ", resources)); this.cliManager.activateDashboard(dashboard, resources, isGroupActivation); break; } case ACTION_DEACTIVATE: { - logger.info("Deactivating dashboard: '{}' for resource of type {}: '{}'", dashboard, resourceType, String.join(", ", resources)); + logger.info("Deactivating dashboard: '{}' for resource of type {}: '{}'", dashboard, + resourceType, String.join(", ", resources)); this.cliManager.deactivateDashboard(dashboard, resources, isGroupActivation); break; } default: { - logger.warn("Invalid action: '{}' for resource type {}, supported actions 'share, unshare'", action, resourceType); + logger.warn("Invalid action: '{}' for resource type {}, supported actions 'share, unshare'", + action, resourceType); } } }); @@ -767,7 +840,9 @@ private void manageDashboardActivation(final File rootDir, final boolean isGroup /** * Share / un-share dashboards based on the dashboard sharing metadata file. - * @param rootDir Root directory where the dashboards and the metadata file reside. + * + * @param rootDir Root directory where the dashboards and the metadata file + * reside. * @throws RuntimeException if the sharing / unsharing per user or group fails. */ private void manageDashboardSharing(final File rootDir) { @@ -789,17 +864,20 @@ private void manageDashboardSharing(final File rootDir) { // exist on the target vROPs List missingGroups = this.getMissingGroups(groups); if (missingGroups != null && !missingGroups.isEmpty()) { - throw new RuntimeException(String.format("Unable to %s dashboard '%s' as resources of type group '%s' do not exists on target vROPs", - action, dashboard, String.join(", ", missingGroups.toArray(new String[0])))); + throw new RuntimeException(String.format( + "Unable to %s dashboard '%s' as resources of type group '%s' do not exists on target vROPs", + action, dashboard, String.join(", ", missingGroups.toArray(new String[0])))); } switch (action) { case ACTION_SHARE: { - logger.info("Sharing dashboard: '{}' with resources of type group: '{}'", dashboard, String.join(", ", groups)); + logger.info("Sharing dashboard: '{}' with resources of type group: '{}'", dashboard, + String.join(", ", groups)); this.cliManager.shareDashboard(dashboard, groups.toArray(new String[0])); break; } case ACTION_UNSHARE: { - logger.info("Unsharing dashboard: '{}' resources of type group: '{}'", dashboard, String.join(", ", groups)); + logger.info("Unsharing dashboard: '{}' resources of type group: '{}'", dashboard, + String.join(", ", groups)); this.cliManager.unshareDashboard(dashboard, groups.toArray(new String[0])); break; } @@ -812,8 +890,11 @@ private void manageDashboardSharing(final File rootDir) { } /** - * Return the missing groups for dashboard sharing / unsharing / activation / deactivation. - * @param groups List of groups to be checked whether they are present on vROPs server. + * Return the missing groups for dashboard sharing / unsharing / activation / + * deactivation. + * + * @param groups List of groups to be checked whether they are present on vROPs + * server. * @return list of missing groups. */ private List getMissingGroups(final List groups) { @@ -822,12 +903,16 @@ private List getMissingGroups(final List groups) { return groups; } - return groups.stream().filter(group -> foundGroups.stream().noneMatch(t -> t.getDisplayName().equals(group))).collect(Collectors.toList()); + return groups.stream().filter(group -> foundGroups.stream().noneMatch(t -> t.getDisplayName().equals(group))) + .collect(Collectors.toList()); } /** - * Return the missing users for dashboard sharing / unsharing / activation / deactivation. - * @param users List of users to be checked whether they are present on vROPs server. + * Return the missing users for dashboard sharing / unsharing / activation / + * deactivation. + * + * @param users List of users to be checked whether they are present on vROPs + * server. * @return list of missing users. */ private List getMissingUsers(final List users) { @@ -836,11 +921,13 @@ private List getMissingUsers(final List users) { return users; } - return users.stream().filter(user -> foundUsers.stream().noneMatch(t -> t.getUsername().equals(user))).collect(Collectors.toList()); + return users.stream().filter(user -> foundUsers.stream().noneMatch(t -> t.getUsername().equals(user))) + .collect(Collectors.toList()); } /** * Gets policy metadata. + * * @param rootDir * @return policy metadata */ @@ -873,6 +960,7 @@ private Map getPolicyMetadata(final File rootDir) { /** * Gets dashboard sharing metadata. + * * @param rootDir root directory of the dashboard sharing metadata file. * @return the dashboard sharing metadata hashmap. */ @@ -894,30 +982,36 @@ private Map>> getDashboardSharingMetadata(final dashboardSharingMetadataFileName = dashboardShareMetadataFile.getName(); dashboardSharingMetadata = FileUtils.readFileToString(dashboardShareMetadataFile, StandardCharsets.UTF_8); } catch (IOException e) { - throw new RuntimeException(String.format("An error occurred reading file '%s'", dashboardSharingMetadataFileName), e); + throw new RuntimeException( + String.format("An error occurred reading file '%s'", dashboardSharingMetadataFileName), e); } try { return new ObjectMapper().readValue(dashboardSharingMetadata, HashMap.class); } catch (JsonProcessingException e) { - throw new RuntimeException(String.format("An error occurred parsing file '%s'", dashboardSharingMetadataFileName), e); + throw new RuntimeException( + String.format("An error occurred parsing file '%s'", dashboardSharingMetadataFileName), e); } } /** * Gets dashboard activation metadata. - * @param rootDir root directory of the dashboard activation metadata file. + * + * @param rootDir root directory of the dashboard activation metadata + * file. * @param isGroupActivation return the group activation metadata. * @return the dashboard activation metadata hashmap. */ @SuppressWarnings("unchecked") - private Map>> getDashboardActivationMetadata(final File rootDir, final boolean isGroupActivation) { + private Map>> getDashboardActivationMetadata(final File rootDir, + final boolean isGroupActivation) { // get dashboard activation metadata File dashboardsDir = new File(rootDir.getPath(), "dashboards"); if (!dashboardsDir.exists()) { return Collections.emptyMap(); } String dashboardActivationMetadata = ""; - String fileName = isGroupActivation ? DASHBOARD_GROUP_ACTIVATE_METADATA_FILENAME : DASHBOARD_USER_ACTIVATE_METADATA_FILENAME; + String fileName = isGroupActivation ? DASHBOARD_GROUP_ACTIVATE_METADATA_FILENAME + : DASHBOARD_USER_ACTIVATE_METADATA_FILENAME; String resourceType = isGroupActivation ? "group" : "user"; try { File dashboardActivationMetadataFile = new File(dashboardsDir, fileName); @@ -925,20 +1019,26 @@ private Map>> getDashboardActivationMetadata(fi return Collections.emptyMap(); } logger.info("Reading dashboard sharing metadata file '{}' for resource type {}", fileName, resourceType); - dashboardActivationMetadata = FileUtils.readFileToString(dashboardActivationMetadataFile, StandardCharsets.UTF_8); + dashboardActivationMetadata = FileUtils.readFileToString(dashboardActivationMetadataFile, + StandardCharsets.UTF_8); } catch (IOException e) { - throw new RuntimeException(String.format("An error occurred reading file '%s' for resource type %s", fileName, resourceType), e); + throw new RuntimeException( + String.format("An error occurred reading file '%s' for resource type %s", fileName, resourceType), + e); } try { return new ObjectMapper().readValue(dashboardActivationMetadata, HashMap.class); } catch (JsonProcessingException e) { - throw new RuntimeException(String.format("An error occurred parsing file '%s' for resource type %s", fileName, resourceType), e); + throw new RuntimeException( + String.format("An error occurred parsing file '%s' for resource type %s", fileName, resourceType), + e); } } /** * Store the policy metadata file. - * @param rootDir root directory where to store policy metadata file. + * + * @param rootDir root directory where to store policy metadata file. * @param policyMetadata hashmap with policy meta data. */ private void storePolicyMetadata(final File rootDir, final Map policyMetadata) { @@ -950,12 +1050,14 @@ private void storePolicyMetadata(final File rootDir, final Map p policyMetadataContent = policyMetadataContent == null ? "" : policyMetadataContent; Files.write(policyMetadataFile.toPath(), policyMetadataContent.getBytes(), StandardOpenOption.CREATE_NEW); } catch (JsonProcessingException e) { - String message = String.format("Error generating policy metadata file %s : %s", policyMetadataFile.getName(), e.getMessage()); + String message = String.format("Error generating policy metadata file %s : %s", + policyMetadataFile.getName(), e.getMessage()); logger.error(message); throw new RuntimeException(message, e); } catch (IOException e) { - String message = String.format("Error exporting policy metadata file %s : %s", policyMetadataFile.getName(), e.getMessage()); + String message = String.format("Error exporting policy metadata file %s : %s", policyMetadataFile.getName(), + e.getMessage()); logger.error(message); throw new RuntimeException(message, e); @@ -964,7 +1066,9 @@ private void storePolicyMetadata(final File rootDir, final Map p /** * Store the dashboard sharing metadata file. - * @param rootDir root directory where to store the dashboard sharing metadata file. + * + * @param rootDir root directory where to store the dashboard sharing + * metadata file. * @param dashboards list of dashboards to be put in the file. */ private void storeDashboardSharingMetadata(final File rootDir, final List dashboards) { @@ -988,25 +1092,33 @@ private void storeDashboardSharingMetadata(final File rootDir, final List dashboards, final boolean isGroupActivation) { + private void storeDashboardActivationMetadata(final File rootDir, final List dashboards, + final boolean isGroupActivation) { // generate dashboard activation metadata file - String fileName = isGroupActivation ? DASHBOARD_GROUP_ACTIVATE_METADATA_FILENAME : DASHBOARD_USER_ACTIVATE_METADATA_FILENAME; + String fileName = isGroupActivation ? DASHBOARD_GROUP_ACTIVATE_METADATA_FILENAME + : DASHBOARD_USER_ACTIVATE_METADATA_FILENAME; File dashboardActivationMetadataFile = new File(rootDir, fileName); // if file exist return here and do not generate sample contents if (dashboardActivationMetadataFile.exists()) { @@ -1023,24 +1135,31 @@ private void storeDashboardActivationMetadata(final File rootDir, final List policyMetadataMap = getPolicyMetadata(tmpDir); StringBuilder messages = new StringBuilder(); - for (File customGroupFile : FileUtils.listFiles(customGroupsDir, new String[] {"json"}, false)) { + for (File customGroupFile : FileUtils.listFiles(customGroupsDir, new String[] { "json" }, false)) { String customGroup = FilenameUtils.removeExtension(customGroupFile.getName()); try { logger.info("Importing custom group: '{}'", customGroup); @@ -1059,7 +1178,8 @@ private void importCustomGroups(final Package vropsPackage, final File tmpDir) { restClient.importCustomGroupInVrops(customGroup, customGroupPayload, policyMetadataMap); logger.info("Imported custom group: '{}'", customGroup); } catch (Exception e) { - messages.append(String.format("The custom group '%s' could not be imported : %s %n", customGroup, e.getMessage())); + messages.append(String.format("The custom group '%s' could not be imported : %s %n", customGroup, + e.getMessage())); } } @@ -1070,6 +1190,7 @@ private void importCustomGroups(final Package vropsPackage, final File tmpDir) { /** * Read custom group file. + * * @param customGroupFile JSON file to read from. * @return string with JSON data read from file. * @throws IOException if the file cannot be read. @@ -1078,14 +1199,16 @@ private String readCustomGroupFile(final File customGroupFile) throws IOExceptio try { return FileUtils.readFileToString(customGroupFile, StandardCharsets.UTF_8); } catch (IOException e) { - throw new IOException(String.format("An error occurred reading file %s : %s %n", customGroupFile.getName(), e.getMessage())); + throw new IOException(String.format("An error occurred reading file %s : %s %n", customGroupFile.getName(), + e.getMessage())); } } /** * Import policies to vROPs. + * * @param vropsPackage package to read policies from. - * @param tmpDir temporary dir where to unwrap polices to. + * @param tmpDir temporary dir where to unwrap polices to. * @throws RuntimeException if the polices cannot be imported. */ private void importPolicies(final Package vropsPackage, final File tmpDir) { @@ -1095,14 +1218,15 @@ private void importPolicies(final Package vropsPackage, final File tmpDir) { } StringBuilder messages = new StringBuilder(); - for (File policy : FileUtils.listFiles(policiesDir, new String[] {"zip"}, Boolean.FALSE)) { + for (File policy : FileUtils.listFiles(policiesDir, new String[] { "zip" }, Boolean.FALSE)) { String policyName = FilenameUtils.removeExtension(policy.getName()); try { logger.info("Importing policy: '{}'", policyName); restClient.importPolicyFromZip(policyName, policy, Boolean.TRUE); logger.info("Imported policy: '{}'", policyName); } catch (Exception e) { - String message = String.format("The policy '%s' could not be imported : '%s'", policyName, e.getMessage()); + String message = String.format("The policy '%s' could not be imported : '%s'", policyName, + e.getMessage()); logger.error(message); messages.append(message); } @@ -1117,8 +1241,9 @@ private void importPolicies(final Package vropsPackage, final File tmpDir) { * Set the default policy in vROPs. Note it will not do anything if: * 1. vROPs version is below 8.12 (as it is not supported by the vROPS API). * 2. No default policy is set in the content.yaml file. + * * @param vropsPackage package to read policies from. - * @param tmpDir temporary directory where the content.yaml file resides. + * @param tmpDir temporary directory where the content.yaml file resides. * @throws RuntimeException if the default policy cannot be set. */ private void setDefaultPolicy(final Package vropsPackage, final File tmpDir) { @@ -1142,12 +1267,15 @@ private void setDefaultPolicy(final Package vropsPackage, final File tmpDir) { } /** - * Set the policy priorities. The ordering of the policies in the content.yaml file - * will define policy priorities (first will be with top priority, last with least priority). + * Set the policy priorities. The ordering of the policies in the content.yaml + * file + * will define policy priorities (first will be with top priority, last with + * least priority). * Note it will not do anything if: vROPs version is below 8.17.0. * (as it is not supported by the vROPS API). + * * @param vropsPackage package to read policies from. - * @param tmpDir temporary directory where the content.yaml file resides. + * @param tmpDir temporary directory where the content.yaml file resides. * @throws RuntimeException if the policy priorities cannot be set. */ private void setPolicyPriorities(final Package vropsPackage, final File tmpDir) { @@ -1160,8 +1288,10 @@ private void setPolicyPriorities(final Package vropsPackage, final File tmpDir) if (descriptor.getPolicy() == null || descriptor.getPolicy().isEmpty()) { return; } - // if the policies contain wild card then skip setting priorities (as the ordering cannot be guaranteed) - boolean hasWildCard = descriptor.getPolicy().stream().allMatch(policy -> policy.endsWith(WILDCARD_MATCH_SYMBOL)); + // if the policies contain wild card then skip setting priorities (as the + // ordering cannot be guaranteed) + boolean hasWildCard = descriptor.getPolicy().stream() + .allMatch(policy -> policy.endsWith(WILDCARD_MATCH_SYMBOL)); if (hasWildCard) { return; } @@ -1174,8 +1304,10 @@ private void setPolicyPriorities(final Package vropsPackage, final File tmpDir) /** * Parse the content.yaml file. + * * @param contentYamlFile content.yaml file handle. - * @return VropsPackageDescriptor POJO with the populated values from the content.yaml file. + * @return VropsPackageDescriptor POJO with the populated values from the + * content.yaml file. * @throws RuntimeException if the content yaml cannot be parsed. */ private VropsPackageDescriptor parseContentYamlFile(final File contentYamlFile) { @@ -1184,14 +1316,18 @@ private VropsPackageDescriptor parseContentYamlFile(final File contentYamlFile) try { return mapper.readValue(contentYamlFile, VropsPackageDescriptor.class); } catch (Exception e) { - throw new RuntimeException(String.format("Unable to load vROps Package Descriptor ['%s'] : %s", contentYamlFile.getName(), e.getMessage())); + throw new RuntimeException(String.format("Unable to load vROps Package Descriptor ['%s'] : %s", + contentYamlFile.getName(), e.getMessage())); } } /** - * Export definitions from vrops (alert definitions, symptom definitions definitions, recommendations). - * @param definitionType definition type to be exported (aler, symptom, recommendation). - * @param definitions list of definitions to be exported. + * Export definitions from vrops (alert definitions, symptom definitions + * definitions, recommendations). + * + * @param definitionType definition type to be exported (aler, symptom, + * recommendation). + * @param definitions list of definitions to be exported. * @throws RuntimeException if the export fails. */ private void exportDefinitions(final VropsPackageMemberType definitionType, final List definitions) { @@ -1219,50 +1355,60 @@ private void exportDefinitions(final VropsPackageMemberType definitionType, fina Object allDefinitions = restClient.exportDefinitionsFromVrops(definitionType); logger.info("Extracted definitions of type '{}' to '{}'", definitionType, definitionsDir.getAbsolutePath()); - Map definitionsJsonMap = this.generateDefinitionsJsonMap(allDefinitions, definitions, definitionType); + Map definitionsJsonMap = this.generateDefinitionsJsonMap(allDefinitions, definitions, + definitionType); generateDefinitionsFile(definitionsJsonMap, definitionsDir); } /** * Generate the definitions JSON mapping. + * * @param definitionData the definition data. - * @param definitions list of definitions (alert, symptom or recommendation). + * @param definitions list of definitions (alert, symptom or recommendation). * @param definitionType type of the definition. * @return Mapping of definition name and data. */ - private Map generateDefinitionsJsonMap(final Object definitionData, final List definitions, final VropsPackageMemberType definitionType) { + private Map generateDefinitionsJsonMap(final Object definitionData, final List definitions, + final VropsPackageMemberType definitionType) { Map retVal = new HashMap<>(); if (definitionData instanceof AlertDefinitionDTO) { - for (AlertDefinitionDTO.AlertDefinition definition : ((AlertDefinitionDTO) definitionData).getAlertDefinitions()) { + for (AlertDefinitionDTO.AlertDefinition definition : ((AlertDefinitionDTO) definitionData) + .getAlertDefinitions()) { if (definitions.stream().anyMatch(name -> this.isPackageAssetMatching(name, definition.getName()))) { String payload = this.serializeObject(definition); if (!StringUtils.isEmpty(payload)) { retVal.put(definition.getName(), payload); - logger.info("Exporting definition '{}' (Type: '{}')", definition.getName(), definitionType.name()); + logger.info("Exporting definition '{}' (Type: '{}')", definition.getName(), + definitionType.name()); } } } } if (definitionData instanceof SymptomDefinitionDTO) { - for (SymptomDefinitionDTO.SymptomDefinition definition : ((SymptomDefinitionDTO) definitionData).getSymptomDefinitions()) { + for (SymptomDefinitionDTO.SymptomDefinition definition : ((SymptomDefinitionDTO) definitionData) + .getSymptomDefinitions()) { if (definitions.stream().anyMatch(name -> this.isPackageAssetMatching(name, definition.getName()))) { String payload = this.serializeObject(definition); if (!StringUtils.isEmpty(payload)) { retVal.put(definition.getName(), payload); - logger.info("Exporting definition '{}' (Type: '{}')", definition.getName(), definitionType.name()); + logger.info("Exporting definition '{}' (Type: '{}')", definition.getName(), + definitionType.name()); } } } } if (definitionData instanceof RecommendationDTO) { - for (RecommendationDTO.Recommendation definition : ((RecommendationDTO) definitionData).getRecommendations()) { - if (definitions.stream().anyMatch(name -> this.isPackageAssetMatching(name, definition.getDescription()))) { + for (RecommendationDTO.Recommendation definition : ((RecommendationDTO) definitionData) + .getRecommendations()) { + if (definitions.stream() + .anyMatch(name -> this.isPackageAssetMatching(name, definition.getDescription()))) { String payload = this.serializeObject(definition); if (!StringUtils.isEmpty(payload)) { retVal.put(definition.getDescription(), payload); - logger.info("Exporting definition '{}' (Type: '{}')", definition.getDescription(), definitionType.name()); + logger.info("Exporting definition '{}' (Type: '{}')", definition.getDescription(), + definitionType.name()); } } } @@ -1273,8 +1419,9 @@ private Map generateDefinitionsJsonMap(final Object definitionDa /** * Generate the definition file based on definition data. + * * @param definitionJson mapping of the definition JSON data. - * @param dir directory where to put generated file. + * @param dir directory where to put generated file. * @throws IOException if the writing of the file fails. */ private void generateDefinitionsFile(final Map definitionJson, final File dir) { @@ -1283,14 +1430,16 @@ private void generateDefinitionsFile(final Map definitionJson, f try { FileUtils.write(definitionFile, definition.getValue(), StandardCharsets.UTF_8); } catch (IOException e) { - logger.error("Error generating definitions file file '{}', message {}.", definitionFile, e.getMessage()); + logger.error("Error generating definitions file file '{}', message {}.", definitionFile, + e.getMessage()); } } } /** * Export custom groups from vROPs server. - * @param vropsPackage package where to put the custom groups to. + * + * @param vropsPackage package where to put the custom groups to. * @param customGroupNames names of the custom groups to be exported. * @throws RuntimeException if the export fails. */ @@ -1306,22 +1455,25 @@ private void exportCustomGroups(final Package vropsPackage, final List c logger.error("No custom groups found in vROPs"); return; } - + StringBuilder messages = new StringBuilder(); for (CustomGroupDTO.Group customGroup : customGroups) { - if (customGroupNames.stream().anyMatch(name -> this.isPackageAssetMatching(name, customGroup.getResourceKey().getName()))) { + if (customGroupNames.stream() + .anyMatch(name -> this.isPackageAssetMatching(name, customGroup.getResourceKey().getName()))) { String payload = this.serializeObject(customGroup); - if (!StringUtils.isEmpty(payload)) { + if (!StringUtils.isEmpty(payload)) { logger.info("Exporting custom group '{}'", customGroup.getResourceKey().getName()); - File customGroupFile = new File(customGroupTargetDir, customGroup.getResourceKey().getName() + ".json"); + File customGroupFile = new File(customGroupTargetDir, + customGroup.getResourceKey().getName() + ".json"); try { Files.write(customGroupFile.toPath(), payload.getBytes(), StandardOpenOption.CREATE_NEW); } catch (IOException e) { - messages.append(String.format("Error writing file %s : %s", customGroupFile.getName(), e.getMessage())); - } + messages.append( + String.format("Error writing file %s : %s", customGroupFile.getName(), e.getMessage())); + } } } - } + } if (messages.length() > 0) { throw new RuntimeException(messages.toString()); @@ -1330,7 +1482,8 @@ private void exportCustomGroups(final Package vropsPackage, final List c /** * Export policies from vROPs server. - * @param vropsPackage package where to put the exported polices to. + * + * @param vropsPackage package where to put the exported polices to. * @param policyEntries names the polices to be exported. * @throws RuntimeException if the export fails. */ @@ -1369,28 +1522,31 @@ private void exportPolicies(final Package vropsPackage, final List polic /** * Copy dashboard contents to the file system. + * * @param dashboard dashboard name to be copied. - * @param dir directory where dashboard to be copied to. + * @param dir directory where dashboard to be copied to. * @throws IOException | JSchException if copy fails. */ private void copyDashboardToFilesystem(final String dashboard, final File dir) { try { File dashboardDir = new File(tempDir, "iac-dash-" + UUID.randomUUID().toString() + "-" - + System.currentTimeMillis()); + + System.currentTimeMillis()); dashboardDir.mkdirs(); cliManager.exportDashboard(dashboard, dashboardDir); File zip = new File(dashboardDir, dashboard + ".zip"); ZipUtilities.unzip(zip, dashboardDir); File subdir = new File(dashboardDir, "dashboard"); - File content = new File(subdir, "dashboard.json"); + File content = new File(subdir, "dashboard.json"); moveFile(content, new File(dir, dashboard + ".json")); zip.delete(); mergeLocalizationResources(new File(subdir, "resources"), new File(dir, "resources")); } catch (IOException | JSchException e) { - String message = String.format("Unable to pull dashboard '%s' from remote vROps location '%s' to local filesystem dir '%s' : %s : %s", dashboard, + String message = String.format( + "Unable to pull dashboard '%s' from remote vROps location '%s' to local filesystem dir '%s' : %s : %s", + dashboard, cliManager, dir.getAbsolutePath(), e.getClass().getName(), e.getMessage()); logger.error(message); logger.debug(message, e); @@ -1400,28 +1556,31 @@ private void copyDashboardToFilesystem(final String dashboard, final File dir) { /** * Copy report contents to the file system. + * * @param report report name to be copied. - * @param dir directory where report to be copied to. + * @param dir directory where report to be copied to. * @throws IOException | JSchException if copy fails. */ private void copyReportToFilesystem(final String report, final File dir) { try { File reportDir = new File(tempDir, "iac-dash-" + UUID.randomUUID().toString() + "-" - + System.currentTimeMillis()); - + + System.currentTimeMillis()); + reportDir.mkdirs(); cliManager.exportReport(report, reportDir); File zip = new File(reportDir, report + ".zip"); File contentDir = new File(reportDir, report); ZipUtilities.unzip(zip, contentDir); - File content = new File(reportDir, "content.xml"); + File content = new File(reportDir, "content.xml"); content.renameTo(new File(contentDir, report)); FileUtils.copyDirectory(contentDir, new File(dir, report)); zip.delete(); } catch (IOException | JSchException e) { - String message = String.format("Unable to pull report '%s' from remote vROps location '%s' to local filesystem dir '%s' : %s : %s", report, + String message = String.format( + "Unable to pull report '%s' from remote vROps location '%s' to local filesystem dir '%s' : %s : %s", + report, cliManager, dir.getAbsolutePath(), e.getClass().getName(), e.getMessage()); logger.error(message); logger.debug(message, e); @@ -1431,7 +1590,8 @@ private void copyReportToFilesystem(final String report, final File dir) { /** * Exports a package. - * @param pkg the package to export + * + * @param pkg the package to export * @param dryrun whether it should be a dry run * @return the exported package */ @@ -1442,9 +1602,10 @@ public Package exportPackage(final Package pkg, final boolean dryrun) { /** * Exports a package. - * @param pkg the package to export + * + * @param pkg the package to export * @param exportDescriptor the descriptor of the package to export - * @param dryrun whether it should be dry run + * @param dryrun whether it should be dry run * @return the exported package */ @Override @@ -1456,8 +1617,9 @@ public Package exportPackage(final Package pkg, final File exportDescriptor, fin /** * Imports a package. - * @param pkg the package to import - * @param dryrun whether it should be dry run + * + * @param pkg the package to import + * @param dryrun whether it should be dry run * @param mergePackages whether to merge the packages * @return the imported package */ @@ -1476,23 +1638,23 @@ public Package importPackage(final Package pkg, final boolean dryrun, final bool try { new PackageManager(pkg).unpack(tmpDir); - + addViewToImportList(pkg, tmpDir); addDashboardToImportList(pkg, tmpDir); addReportToImportList(pkg, tmpDir); addSuperMetricToImportList(pkg, tmpDir); addMetricConfigToImportList(pkg, tmpDir); - + if (cliManager.hasAnyCommands()) { cliManager.connect(); cliManager.importFilesToVrops(); } - + importDefinitions(pkg, tmpDir); importPolicies(pkg, tmpDir); importCustomGroups(pkg, tmpDir); // manage dashboard sharing per groups - manageDashboardSharing(tmpDir); + manageDashboardSharing(tmpDir); // manage dashboard activation per groups manageDashboardActivation(tmpDir, true); // manage dashboard activation per users @@ -1502,7 +1664,8 @@ public Package importPackage(final Package pkg, final boolean dryrun, final bool // set policy priorities setPolicyPriorities(pkg, tmpDir); } catch (IOException | JSchException | ConfigurationException e) { - String message = String.format("Unable to push package '%s' to vROps Server '%s' : %s : %s", pkg.getFQName(), cliManager, e.getClass().getName(), + String message = String.format("Unable to push package '%s' to vROps Server '%s' : %s : %s", + pkg.getFQName(), cliManager, e.getClass().getName(), e.getMessage()); logger.error(message); logger.debug(message, e); @@ -1515,12 +1678,13 @@ public Package importPackage(final Package pkg, final boolean dryrun, final bool FileUtils.deleteDirectory(tmpDir); } } catch (IOException ioe) { - String message = String.format("Cannot delete temporary directory '%s' : %s , leaving it there", tmpDir.getAbsolutePath(), ioe.getMessage()); + String message = String.format("Cannot delete temporary directory '%s' : %s , leaving it there", + tmpDir.getAbsolutePath(), ioe.getMessage()); logger.warn(message); logger.debug(message, ioe); } } - + return pkg; } @@ -1546,7 +1710,7 @@ private void addViewToImportList(final Package pkg, final File tmp) throws IOExc if (!viewsFolder.exists()) { return; } - for (File view : FileUtils.listFiles(viewsFolder, new String[] {"xml"}, false)) { + for (File view : FileUtils.listFiles(viewsFolder, new String[] { "xml" }, false)) { File viewZip = createViewZip(view); cliManager.addViewToImportList(viewZip); } @@ -1569,14 +1733,15 @@ private List addDefinitionsToImportList(final File tmpDir, final VropsPack break; } default: - throw new RuntimeException(String.format("Definition type %s is not supported!", definitionType.name())); + throw new RuntimeException( + String.format("Definition type %s is not supported!", definitionType.name())); } File definitionsDir = new File(tmpDir.getPath(), definitionsSubDir); if (!definitionsDir.exists()) { return definitions; } - FileUtils.listFiles(definitionsDir, new String[] {"json"}, false).stream().forEach(definitions::add); - + FileUtils.listFiles(definitionsDir, new String[] { "json" }, false).stream().forEach(definitions::add); + return definitions; } @@ -1585,7 +1750,7 @@ private void addDashboardToImportList(final Package pkg, final File tmp) throws if (!dashboardsFolder.exists()) { return; } - for (File dashboard : FileUtils.listFiles(dashboardsFolder, new String[] {"json"}, false)) { + for (File dashboard : FileUtils.listFiles(dashboardsFolder, new String[] { "json" }, false)) { // skip dashboard sharing metadata file if (dashboard.getName().contains(DASHBOARD_SHARE_METADATA_FILENAME)) { continue; @@ -1611,7 +1776,7 @@ private void addSuperMetricToImportList(final Package pkg, final File tmp) throw if (!superMetricsFolder.exists()) { return; } - for (File superMetric : FileUtils.listFiles(superMetricsFolder, new String[] {"json"}, false)) { + for (File superMetric : FileUtils.listFiles(superMetricsFolder, new String[] { "json" }, false)) { this.cliManager.addSuperMetricsToImportList(superMetric); } } @@ -1631,13 +1796,15 @@ private void mergeLocalizationResources(final File srcDir, final File destDir) { return; } if (!srcDir.canRead()) { - getLogger().warn("Cannot copy content of directory \"" + srcDir.getAbsolutePath() + "\" to \"" + destDir.getAbsolutePath() + getLogger().warn("Cannot copy content of directory \"" + srcDir.getAbsolutePath() + "\" to \"" + + destDir.getAbsolutePath() + "\". Source directory is not readable. Skipping dir."); return; } destDir.mkdirs(); if (!destDir.exists() || !destDir.canWrite()) { - getLogger().warn("Cannot copy content of directory \"" + srcDir.getAbsolutePath() + "\" to \"" + destDir.getAbsolutePath() + getLogger().warn("Cannot copy content of directory \"" + srcDir.getAbsolutePath() + "\" to \"" + + destDir.getAbsolutePath() + "\". Destination directory cannot be created or is not writable. Skipping dir."); return; } @@ -1653,15 +1820,17 @@ private void mergeLocalizationResources(final File srcDir, final File destDir) { os.write('\n'); } } catch (IOException ioe) { - getLogger().warn("Error merging content of \"" + resource.getAbsolutePath() + "\" to \"" + destFile.getAbsolutePath() + "\" : " + ioe.getLocalizedMessage() - + "; Continuing with other resource files if any."); + getLogger().warn("Error merging content of \"" + resource.getAbsolutePath() + "\" to \"" + + destFile.getAbsolutePath() + "\" : " + ioe.getLocalizedMessage() + + "; Continuing with other resource files if any."); } } } private static void moveFile(final File source, final File dest) throws IOException { if (!source.exists()) { - throw new IOException("Source file \"" + source.getAbsolutePath() + "\" does not exist. Cannot move/rename it to \"" + dest.getAbsolutePath() + "\"."); + throw new IOException("Source file \"" + source.getAbsolutePath() + + "\" does not exist. Cannot move/rename it to \"" + dest.getAbsolutePath() + "\"."); } boolean success = source.renameTo(dest); if (!success) { @@ -1688,7 +1857,7 @@ private File createViewZip(final File view) throws ConfigurationException, IOExc File resourcesDir = new File(view.getParent(), "resources"); if (resourcesDir.exists()) { - for (File propfile : FileUtils.listFiles(resourcesDir, new String[] {"properties"}, false)) { + for (File propfile : FileUtils.listFiles(resourcesDir, new String[] { "properties" }, false)) { ZipEntry propEntry = new ZipEntry("resources/" + propfile.getName()); zipOut.putNextEntry(propEntry); fileCopyFiltering(propfile, "view." + id, zipOut); @@ -1703,7 +1872,7 @@ private File createDashboardZip(final File dashboard) throws IOException { logger.info("Dashboard absolute path: {}", dashboard.getAbsolutePath()); String name = FilenameUtils.removeExtension(dashboard.getName()); logger.info("Dashboard name {}", name); - File dashboardZip = new File(dashboard.getParent(), name + ".zip"); + File dashboardZip = new File(dashboard.getParent(), name + ".zip"); try ( FileOutputStream fos = new FileOutputStream(dashboardZip); ZipOutputStream zipOut = new ZipOutputStream(fos);) { @@ -1718,7 +1887,7 @@ private File createDashboardZip(final File dashboard) throws IOException { File resourcesDir = new File(dashboard.getParent(), "resources"); if (resourcesDir.exists()) { logger.info("Resources directory: {}", resourcesDir.getAbsolutePath()); - for (File propfile : FileUtils.listFiles(resourcesDir, new String[]{"properties"}, false)) { + for (File propfile : FileUtils.listFiles(resourcesDir, new String[] { "properties" }, false)) { ZipEntry propEntry = new ZipEntry("dashboard/resources/" + propfile.getName()); zipOut.putNextEntry(propEntry); fileCopyFiltering(propfile, name, zipOut); @@ -1733,7 +1902,7 @@ private File createReportZip(final File report) throws IOException { logger.info("Report absolute path: {}", report.getAbsolutePath()); String name = FilenameUtils.removeExtension(report.getName()); logger.info("Report name {} ", name); - File reportZip = new File(report.getParent(), name + ".zip"); + File reportZip = new File(report.getParent(), name + ".zip"); try ( FileOutputStream fos = new FileOutputStream(reportZip); ZipOutputStream zipOut = new ZipOutputStream(fos);) { @@ -1748,7 +1917,7 @@ private File createReportZip(final File report) throws IOException { File resourcesDir = new File(report, "resources"); if (resourcesDir.exists()) { logger.info("Resources directory: {}", resourcesDir.getAbsolutePath()); - for (File resource : FileUtils.listFiles(resourcesDir, new String[]{"properties"}, false)) { + for (File resource : FileUtils.listFiles(resourcesDir, new String[] { "properties" }, false)) { ZipEntry propEntry = new ZipEntry("resources/" + resource.getName()); zipOut.putNextEntry(propEntry); fileCopyFiltering(resource, name, zipOut); @@ -1780,16 +1949,17 @@ private String serializeObject(final Object object) { /** * * @param propFile Properties file - * @param prefix Properties prefix - * @param out Output stream + * @param prefix Properties prefix + * @param out Output stream * @throws IOException throws IO exception if input stream not available */ - public static void fileCopyFiltering(final File propFile, final String prefix, final OutputStream out) throws IOException { - Properties filtered = new Properties(); + public static void fileCopyFiltering(final File propFile, final String prefix, final OutputStream out) + throws IOException { + Properties filtered = new Properties(); Properties props = new Properties(); try (InputStream in = new FileInputStream(propFile);) { props.load(in); - props.forEach((key, value) -> { + props.forEach((key, value) -> { if (("" + key).startsWith(prefix)) { filtered.setProperty("" + key, "" + value); } @@ -1803,8 +1973,10 @@ public static void fileCopyFiltering(final File propFile, final String prefix, f * * @param view View file * @return Returns View ID - * @throws ConfigurationException throws configuration exception incase of parsing error - * @throws IOException throws IO exception if input stream not available + * @throws ConfigurationException throws configuration exception incase of + * parsing error + * @throws IOException throws IO exception if input stream not + * available */ public static String getViewId(final File view) throws ConfigurationException, IOException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); @@ -1814,15 +1986,18 @@ public static String getViewId(final File view) throws ConfigurationException, I dBuilder = dbFactory.newDocumentBuilder(); doc = dBuilder.parse(view); } catch (ParserConfigurationException e) { - throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + "\" cannot be parsed as XML file because of serious configuration error " + throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + + "\" cannot be parsed as XML file because of serious configuration error " + e.getLocalizedMessage(), e); } catch (SAXException e) { - throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + "\" has invalid format. It is not a correct XML file. " + throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + + "\" has invalid format. It is not a correct XML file. " + e.getLocalizedMessage(), e); } Element root = doc.getDocumentElement(); if (!"Content".equalsIgnoreCase(root.getNodeName())) { - throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + "\" is not in the expected format. It is a valid XML file, bu the root " + throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + + "\" is not in the expected format. It is a valid XML file, bu the root " + "element is \"" + root.getNodeName() + "\" while the expected one is \"Content\"."); } NodeList views = root.getChildNodes(); @@ -1835,22 +2010,26 @@ public static String getViewId(final File view) throws ConfigurationException, I viewsNode = viewsNode.getNextSibling(); } if (viewsNode == null || !"Views".equalsIgnoreCase(viewsNode.getNodeName())) { - throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + "\" is not in the expected format. First child element under \"Content\" is " - + (viewsNode == null ? "UNKNOWN" : "\"" + viewsNode.getNodeName() + "\"") + ", expected: \"Views\"."); + throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + + "\" is not in the expected format. First child element under \"Content\" is " + + (viewsNode == null ? "UNKNOWN" : "\"" + viewsNode.getNodeName() + "\"") + + ", expected: \"Views\"."); } Node viewDefNode = viewsNode.getFirstChild(); while (viewDefNode != null && "#text".equalsIgnoreCase(viewDefNode.getNodeName())) { viewDefNode = viewDefNode.getNextSibling(); } if (viewDefNode == null || !"ViewDef".equalsIgnoreCase(viewDefNode.getNodeName())) { - throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + "\" has invalid format. Child node under \"Content\" -> \"Views\" is " + throw new ConfigurationException("The view file \"" + view.getAbsolutePath() + + "\" has invalid format. Child node under \"Content\" -> \"Views\" is " + (viewDefNode == null ? "NOT PRESENT" : "\"" + viewDefNode + "\"") + ", expected \"ViewDef\""); } NamedNodeMap attributes = viewDefNode.getAttributes(); Node id = attributes.getNamedItem("id"); if (id == null || id.getNodeValue().trim().length() == 0) { throw new ConfigurationException("The view file \"" + view.getAbsolutePath() - + "\" has invalid format. No XML id attribute available for \"Content\" - > \"Views\" -> " + "\"ViewDef\"."); + + "\" has invalid format. No XML id attribute available for \"Content\" - > \"Views\" -> " + + "\"ViewDef\"."); } return id.getNodeValue().trim(); } diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageContent.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageContent.java similarity index 93% rename from common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageContent.java rename to common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageContent.java index 611a83aba..ff02ec718 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageContent.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageContent.java @@ -12,7 +12,7 @@ * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact.model.vrops; +package com.vmware.pscoe.iac.artifact.aria.operations.store.models; import java.util.List; diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageDescriptor.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageDescriptor.java similarity index 99% rename from common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageDescriptor.java rename to common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageDescriptor.java index bcc11f33b..e12173275 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageDescriptor.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageDescriptor.java @@ -12,7 +12,7 @@ * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact.model.vrops; +package com.vmware.pscoe.iac.artifact.aria.operations.store.models; import java.io.File; import java.util.List; diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageMemberType.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageMemberType.java similarity index 96% rename from common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageMemberType.java rename to common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageMemberType.java index 22da2bbed..abdaf9571 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/VropsPackageMemberType.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/VropsPackageMemberType.java @@ -12,7 +12,7 @@ * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact.model.vrops; +package com.vmware.pscoe.iac.artifact.aria.operations.store.models; /** * VropsPackageMemberType defines the asset types that vROPs package supports. diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/package-info.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/package-info.java similarity index 89% rename from common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/package-info.java rename to common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/package-info.java index 46be1d787..e2c434697 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/model/vrops/package-info.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/aria/operations/store/models/package-info.java @@ -17,4 +17,4 @@ * Package that represents vROPs 8 model. * */ -package com.vmware.pscoe.iac.artifact.model.vrops; +package com.vmware.pscoe.iac.artifact.aria.operations.store.models; diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerFactory.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerFactory.java index b24414336..78734248a 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerFactory.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerFactory.java @@ -14,9 +14,12 @@ */ package com.vmware.pscoe.iac.artifact.cli; -import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; -public class CliManagerFactory { +public final class CliManagerFactory { + + private CliManagerFactory() { + } public static CliManagerVrops getVropsCliManager(ConfigurationVrops config) { return new CliManagerVrops(config); diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerVrops.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerVrops.java index 24c486755..7fae7b8c3 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerVrops.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/cli/CliManagerVrops.java @@ -17,8 +17,7 @@ import java.io.File; import java.util.ArrayList; import java.util.List; -import java.util.UUID;import java.util.function.Function; -import java.util.stream.Collectors; +import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,7 +25,7 @@ import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; -import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; import com.vmware.pscoe.iac.artifact.ssh.SshClient; public class CliManagerVrops implements AutoCloseable { @@ -36,14 +35,14 @@ public class CliManagerVrops implements AutoCloseable { private static final String REPORT = "report"; private static final String FILE = "file"; private static final String METRIC_CONFIG = "reskndmetric"; - private static final String EXPORT = "export"; + private static final String EXPORT = "export"; private static final String IMPORT = "import"; private static final String SHARE = "share"; private static final String UNSHARE = "unshare"; private static final String ACTIVATE = "show"; private static final String DEACTIVATE = "hide"; - private static final String SHARING_DEFAULT_USER= "admin"; + private static final String SHARING_DEFAULT_USER = "admin"; private static final String FORCE = "--force"; private static final String ALL_POLICIES = "--policies all"; @@ -121,8 +120,8 @@ public void cleanup() { public void addViewToImportList(File file) { String remoteFilePath = importRemotePath + UNIX_PATH_SEPARATOR + file.getName(); String command = String.format(VROPS_SSH_COMMAND_1, - escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(VIEW), - escapeShellCharacters(IMPORT), escapeShellCharacters(remoteFilePath), + escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(VIEW), + escapeShellCharacters(IMPORT), escapeShellCharacters(remoteFilePath), escapeShellCharacters(FORCE)); cmdList.add(command); @@ -132,8 +131,8 @@ public void addViewToImportList(File file) { public void addDashboardToImportList(File file) { String remoteFilePath = importRemotePath + UNIX_PATH_SEPARATOR + file.getName(); String command = String.format(VROPS_SSH_COMMAND_2, - escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(DASHBOARD), - escapeShellCharacters(IMPORT), "all", + escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(DASHBOARD), + escapeShellCharacters(IMPORT), "all", escapeShellCharacters(remoteFilePath), escapeShellCharacters(FORCE)); cmdList.add(command); @@ -174,7 +173,7 @@ public void activateDashboard(String dashboard, List resources, boolean if (isGroupResource) { commands.add(String.format(VROPS_SSH_COMMAND_1, escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(DASHBOARD), - escapeShellCharacters(ACTIVATE), "group:"+escapeShellCharacters(resource), + escapeShellCharacters(ACTIVATE), "group:" + escapeShellCharacters(resource), escapeShellCharacters(dashboard))); } else { commands.add(String.format(VROPS_SSH_COMMAND_1, @@ -198,7 +197,7 @@ public void deactivateDashboard(String dashboard, List resources, boolea if (isGroupResource) { commands.add(String.format(VROPS_SSH_COMMAND_1, escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(DASHBOARD), - escapeShellCharacters(DEACTIVATE), "group:"+escapeShellCharacters(resource), + escapeShellCharacters(DEACTIVATE), "group:" + escapeShellCharacters(resource), escapeShellCharacters(dashboard))); } else { commands.add(String.format(VROPS_SSH_COMMAND_1, @@ -221,7 +220,7 @@ public void addReportToImportList(File file) { String remoteFilePath = importRemotePath + UNIX_PATH_SEPARATOR + file.getName(); String command = String.format(VROPS_SSH_COMMAND_1, escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(REPORT), - escapeShellCharacters(IMPORT), escapeShellCharacters(remoteFilePath), + escapeShellCharacters(IMPORT), escapeShellCharacters(remoteFilePath), escapeShellCharacters(FORCE)); cmdList.add(command); @@ -232,7 +231,8 @@ public void addSuperMetricsToImportList(File file) { String remoteFilePath = importRemotePath + UNIX_PATH_SEPARATOR + file.getName(); String command = String.format(VROPS_SSH_COMMAND_3, escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(SUPER_METRIC), - escapeShellCharacters(IMPORT), escapeShellCharacters(remoteFilePath), escapeShellCharacters(FORCE), ALL_POLICIES, CHECK_FALSE); + escapeShellCharacters(IMPORT), escapeShellCharacters(remoteFilePath), escapeShellCharacters(FORCE), + ALL_POLICIES, CHECK_FALSE); this.cmdList.add(command); this.fileList.add(file); @@ -243,11 +243,11 @@ public void addMetricConfigsToImportList(File file) { String command = String.format(VROPS_SSH_COMMAND_4, escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(FILE), - escapeShellCharacters(IMPORT), + escapeShellCharacters(IMPORT), escapeShellCharacters(METRIC_CONFIG), - escapeShellCharacters(remoteFilePath), - escapeShellCharacters(FORCE), - ALL_POLICIES, + escapeShellCharacters(remoteFilePath), + escapeShellCharacters(FORCE), + ALL_POLICIES, CHECK_FALSE); this.cmdList.add(command); @@ -301,8 +301,8 @@ public void exportView(String viewName, File localDir) throws JSchException { public void exportDashboard(String dashboardName, File localDir) throws JSchException { String remoteFilePath = exportRemotePath + UNIX_PATH_SEPARATOR + "dashboards"; String command = String.format(VROPS_SSH_COMMAND_2, - escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(DASHBOARD), - escapeShellCharacters(EXPORT), escapeShellCharacters(config.getVropsDashboardUser()), + escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(DASHBOARD), + escapeShellCharacters(EXPORT), escapeShellCharacters(config.getVropsDashboardUser()), escapeShellCharacters(dashboardName), escapeShellCharacters(remoteFilePath)); logger.info(VROPS_SSH_COMMAND_INFO, command); @@ -320,7 +320,8 @@ public void exportSuperMetric(String superMetricName, File localDir) throws JSch String remoteFilePath = exportRemotePath + UNIX_PATH_SEPARATOR + "supermetrics"; String command = String.format(VROPS_SSH_COMMAND_1, escapeShellCharacters(OPSCLI_PATH), escapeShellCharacters(SUPER_METRIC), - escapeShellCharacters(EXPORT), escapeShellCharacters(superMetricName), escapeShellCharacters(remoteFilePath)); + escapeShellCharacters(EXPORT), escapeShellCharacters(superMetricName), + escapeShellCharacters(remoteFilePath)); logger.info(VROPS_SSH_COMMAND_INFO, command); reconnect(); @@ -351,7 +352,7 @@ public void exportMetricConfig(String metricConfigName, File localDir) throws JS List files = new ArrayList<>(); files.add(remoteFilePath + UNIX_PATH_SEPARATOR + metricConfigName); - + SshClient.copyRemoteToLocal(session, files, localDir); } @@ -382,7 +383,6 @@ public String toSshComand() { return "ssh \'" + getSshUsername() + "@" + config.getHost() + "' -p " + getSshPort(); } - private String escapeShellCharacters(String str) { if (str == null) { return null; @@ -390,7 +390,7 @@ private String escapeShellCharacters(String str) { if (str.indexOf('\'') == -1) { return "'" + str + "'"; } - final char[] special = {'\'', '~', '`', '#', '$', '&', '*', '(', ')', '\\', '|', '[', ']', '{', '}', ';', '"', + final char[] special = { '\'', '~', '`', '#', '$', '&', '*', '(', ')', '\\', '|', '[', ']', '{', '}', ';', '"', '<', '>', '?', '!' }; StringBuilder buffer = new StringBuilder("\""); for (int i = 0; i < str.length(); i++) { diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/RestClientFactory.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/RestClientFactory.java index 48bd4068d..2ed4c4dee 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/RestClientFactory.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/RestClientFactory.java @@ -56,7 +56,10 @@ import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrli; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVro; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVroNg; -import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVropsAuthNInterceptor; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVropsBasicAuthInterceptor; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationCs; public final class RestClientFactory { diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/AbstractRestClientVrli.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/AbstractRestClientVrli.java index acbf00515..3a727db07 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/AbstractRestClientVrli.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/AbstractRestClientVrli.java @@ -19,9 +19,9 @@ import com.vmware.pscoe.iac.artifact.configuration.Configuration; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationException; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrli; -import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; import com.vmware.pscoe.iac.artifact.rest.RestClient; -import com.vmware.pscoe.iac.artifact.rest.RestClientVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVrops; import org.slf4j.Logger; import org.springframework.http.*; import org.springframework.web.client.HttpClientErrorException; @@ -43,7 +43,7 @@ public abstract class AbstractRestClientVrli extends RestClient { protected static final String ALERTS_API = "/alerts"; private static final String OVERWRITE_MODE = "OVERWRITE"; - protected AbstractRestClientVrli (String apiPrefix, ConfigurationVrli configuration, RestTemplate restTemplate) { + protected AbstractRestClientVrli(String apiPrefix, ConfigurationVrli configuration, RestTemplate restTemplate) { this.apiPrefix = apiPrefix; this.restTemplate = restTemplate; this.configuration = configuration; @@ -57,7 +57,8 @@ public String getVersion() { } URI url = getURI(getURIBuilder().setPath(this.apiPrefix + "/version")); - ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, getDefaultHttpEntity(), String.class); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, getDefaultHttpEntity(), + String.class); this.vrliVersion = JsonPath.parse(response.getBody()).read("$.version"); return this.vrliVersion; @@ -77,9 +78,11 @@ public String getContentPack(String contentPackNamespace) { response = restTemplate.exchange(url, HttpMethod.GET, getDefaultHttpEntity(), String.class); } catch (HttpClientErrorException e) { if (HttpStatus.NOT_FOUND.equals(e.getStatusCode())) { - throw new RuntimeException(String.format("Content pack '%s' does not exist: %s", contentPackNamespace, e.getMessage())); + throw new RuntimeException( + String.format("Content pack '%s' does not exist: %s", contentPackNamespace, e.getMessage())); } - throw new RuntimeException(String.format("Error fetching content pack data for content pack '%s': %s", contentPackNamespace, e.getMessage())); + throw new RuntimeException(String.format("Error fetching content pack data for content pack '%s': %s", + contentPackNamespace, e.getMessage())); } // reformat the output JSON to be readable @@ -87,9 +90,11 @@ public String getContentPack(String contentPackNamespace) { try { jsonObject = JsonParser.parseString(response.getBody()).getAsJsonObject(); } catch (JsonSyntaxException e) { - throw new RuntimeException(String.format("Error verifying data of content pack '%s': %s", contentPackNamespace, e.getMessage())); + throw new RuntimeException(String.format("Error verifying data of content pack '%s': %s", + contentPackNamespace, e.getMessage())); } catch (JsonIOException e) { - throw new RuntimeException(String.format("Error reading and verifying data of content pack '%s': %s", contentPackNamespace, e.getMessage())); + throw new RuntimeException(String.format("Error reading and verifying data of content pack '%s': %s", + contentPackNamespace, e.getMessage())); } Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().setLenient().serializeNulls().create(); @@ -99,7 +104,8 @@ public String getContentPack(String contentPackNamespace) { public void importContentPack(String contentPackName, String contentPackJson) { Boolean overwrite = configuration.getPackageImportOverwriteMode().equals(Boolean.TRUE.toString()) || configuration.getPackageImportOverwriteMode().contains(OVERWRITE_MODE); - URI url = getURI(getURIBuilder().setPath(this.apiPrefix + CONTENT_PACKS_API).addParameter("overwrite", overwrite.toString())); + URI url = getURI(getURIBuilder().setPath(this.apiPrefix + CONTENT_PACKS_API).addParameter("overwrite", + overwrite.toString())); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); @@ -108,15 +114,20 @@ public void importContentPack(String contentPackName, String contentPackJson) { restTemplate.exchange(url, HttpMethod.POST, entity, String.class); } catch (HttpClientErrorException e) { if (HttpStatus.CONFLICT.equals(e.getStatusCode())) { - logger.warn("The content pack '{}' already exists on the target system, please uninstall it before importing again.", contentPackName); + logger.warn( + "The content pack '{}' already exists on the target system, please uninstall it before importing again.", + contentPackName); return; } if (HttpStatus.BAD_REQUEST.equals(e.getStatusCode())) { - throw new RuntimeException(String.format("Data validation error of the content pack '%s' to VRLI: %s", contentPackName, e.getMessage())); + throw new RuntimeException(String.format("Data validation error of the content pack '%s' to VRLI: %s", + contentPackName, e.getMessage())); } - throw new RuntimeException(String.format("Error importing content pack '%s' to VRLI: %s", contentPackName, e.getMessage())); + throw new RuntimeException( + String.format("Error importing content pack '%s' to VRLI: %s", contentPackName, e.getMessage())); } catch (RestClientException e) { - throw new RuntimeException(String.format("REST client error during import of content pack '%s' to VRLI: %s", contentPackName, e.getMessage())); + throw new RuntimeException(String.format("REST client error during import of content pack '%s' to VRLI: %s", + contentPackName, e.getMessage())); } } @@ -131,18 +142,23 @@ protected RestClientVrops getVropsRestClient() { vropsConfigProperties.put(Configuration.PORT, configuration.getIntegrationVropsAuthPort()); vropsConfigProperties.put(Configuration.USERNAME, configuration.getIntegrationVropsAuthUser()); vropsConfigProperties.put(Configuration.PASSWORD, configuration.getIntegrationVropsAuthPassword()); - vropsConfigProperties.put(ConfigurationVrli.INTEGRATION_VROPS_AUTH_SOURCE, configuration.getIntegrationVropsAuthSource()); + vropsConfigProperties.put(ConfigurationVrli.INTEGRATION_VROPS_AUTH_SOURCE, + configuration.getIntegrationVropsAuthSource()); vropsConfigProperties.put(ConfigurationVrops.VROPS_DASHBOARD_USER, "admin"); vropsConfigProperties.put(ConfigurationVrops.VROPS_REST_USER, configuration.getIntegrationVropsAuthUser()); - vropsConfigProperties.put(ConfigurationVrops.VROPS_REST_PASSWORD, configuration.getIntegrationVropsAuthPassword()); - vropsConfigProperties.put(ConfigurationVrops.VROPS_REST_AUTH_SOURCE, configuration.getIntegrationVropsAuthSource()); + vropsConfigProperties.put(ConfigurationVrops.VROPS_REST_PASSWORD, + configuration.getIntegrationVropsAuthPassword()); + vropsConfigProperties.put(ConfigurationVrops.VROPS_REST_AUTH_SOURCE, + configuration.getIntegrationVropsAuthSource()); vropsConfigProperties.put(ConfigurationVrops.SSH_PORT, "22"); try { vropsConfiguration = ConfigurationVrops.fromProperties(vropsConfigProperties); } catch (ConfigurationException e) { throw new RuntimeException( - String.format("Unable to update vCOPs integration for alert, vROPs integration configuration failed with message: %s", e.getMessage())); + String.format( + "Unable to update vCOPs integration for alert, vROPs integration configuration failed with message: %s", + e.getMessage())); } return new RestClientVrops(vropsConfiguration, restTemplate); diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV1.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV1.java index f8cd89912..579c1ad17 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV1.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV1.java @@ -22,7 +22,7 @@ import java.util.Optional; import java.util.stream.Collectors; -import com.vmware.pscoe.iac.artifact.rest.RestClientVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVrops; import com.vmware.pscoe.iac.artifact.rest.client.messages.Errors; import org.apache.commons.lang3.StringUtils; import org.slf4j.LoggerFactory; @@ -42,7 +42,7 @@ import com.vmware.pscoe.iac.artifact.rest.model.vrli.v1.AlertDTO; import com.vmware.pscoe.iac.artifact.rest.model.vrli.v1.ContentPackDTO; import com.vmware.pscoe.iac.artifact.rest.model.vrli.v1.ContentPackMetadataListDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.ResourcesDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.ResourcesDTO; public class RestClientVrliV1 extends AbstractRestClientVrli { /** diff --git a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV2.java b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV2.java index 78069afc8..8ba66e831 100644 --- a/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV2.java +++ b/common/artifact-manager/src/main/java/com/vmware/pscoe/iac/artifact/rest/client/vrli/RestClientVrliV2.java @@ -37,12 +37,12 @@ import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrli; -import com.vmware.pscoe.iac.artifact.rest.RestClientVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVrops; import com.vmware.pscoe.iac.artifact.rest.client.messages.Errors; import com.vmware.pscoe.iac.artifact.rest.model.vrli.v2.AlertDTO; import com.vmware.pscoe.iac.artifact.rest.model.vrli.v2.ContentPackDTO; import com.vmware.pscoe.iac.artifact.rest.model.vrli.v2.ContentPackMetadataListDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.ResourcesDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.ResourcesDTO; public class RestClientVrliV2 extends AbstractRestClientVrli { /** diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/rest/RestClientVraNgPrimitiveTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/rest/RestClientVraNgPrimitiveTest.java similarity index 100% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/rest/RestClientVraNgPrimitiveTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/rest/RestClientVraNgPrimitiveTest.java diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgApprovalPolicyStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgApprovalPolicyStoreTest.java similarity index 98% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgApprovalPolicyStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgApprovalPolicyStoreTest.java index 7e3c5c430..b19e66a41 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgApprovalPolicyStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgApprovalPolicyStoreTest.java @@ -14,8 +14,6 @@ */ package com.vmware.pscoe.iac.artifact.aria.automation.store; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; import com.vmware.pscoe.iac.artifact.helpers.AssertionsHelper; @@ -25,8 +23,8 @@ import com.vmware.pscoe.iac.artifact.model.PackageType; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgApprovalPolicy; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgOrganization; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageDescriptor; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPolicy; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPolicy; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.junit.Rule; import org.junit.jupiter.api.AfterEach; @@ -39,9 +37,7 @@ import java.io.File; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.List; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgBlueprintStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgBlueprintStoreTest.java similarity index 85% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgBlueprintStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgBlueprintStoreTest.java index 7b4e36396..0caaac60c 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgBlueprintStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgBlueprintStoreTest.java @@ -22,15 +22,13 @@ import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgBlueprint; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.junit.Rule; -import org.junit.internal.runners.statements.ExpectException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; @@ -50,7 +48,8 @@ import static org.mockito.Mockito.anyString; /** - * NOTE: This does not test duplicate names from one content source, since the Store is not responsible for that kind of logic. + * NOTE: This does not test duplicate names from one content source, since the + * Store is not responsible for that kind of logic. */ public class VraNgBlueprintStoreTest { @@ -100,16 +99,15 @@ void tearDown() { System.out.println("=========================================================="); } - @Test void testExportContentWithNoBlueprints() { - //GIVEN + // GIVEN when(vraNgPackageDescriptor.getBlueprint()).thenReturn(new ArrayList()); - //TEST + // TEST store.exportContent(); - //VERIFY + // VERIFY verify(restClient, never()).getAllBlueprints(); verify(restClient, never()).getBlueprintVersions(anyString()); @@ -118,7 +116,7 @@ void testExportContentWithNoBlueprints() { @Test void testExportContentWithAllBlueprints() { - //GIVEN + // GIVEN List blueprints = new ArrayList<>(); BlueprintMockBuilder mockBuilder = new BlueprintMockBuilder("ngnix"); @@ -127,20 +125,21 @@ void testExportContentWithAllBlueprints() { when(vraNgPackageDescriptor.getBlueprint()).thenReturn(null); when(restClient.getAllBlueprints()).thenReturn(blueprints); - //TEST + // TEST store.exportContent(); - String[] expectedBlueprints = {"ngnix"}; - String[] expectedBlueprintFiles = {"content.yaml", "details.json"}; + String[] expectedBlueprints = { "ngnix" }; + String[] expectedBlueprintFiles = { "content.yaml", "details.json" }; // VERIFY AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedBlueprints); - AssertionsHelper.assertFolderContainsFiles(fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "ngnix"), expectedBlueprintFiles); + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "ngnix"), expectedBlueprintFiles); } @Test void testExportContentWithSpecificBlueprints() { - //GIVEN + // GIVEN List blueprints = new ArrayList<>(); BlueprintMockBuilder ngnixMockBuilder = new BlueprintMockBuilder("ngnix"); BlueprintMockBuilder tomcatMockBuilder = new BlueprintMockBuilder("tomcat"); @@ -154,20 +153,21 @@ void testExportContentWithSpecificBlueprints() { when(vraNgPackageDescriptor.getBlueprint()).thenReturn(blueprintNames); when(restClient.getAllBlueprints()).thenReturn(blueprints); - //TEST + // TEST store.exportContent(); - String[] expectedBlueprints = {"ngnix"}; - String[] expectedBlueprintFiles = {"content.yaml", "details.json"}; + String[] expectedBlueprints = { "ngnix" }; + String[] expectedBlueprintFiles = { "content.yaml", "details.json" }; // VERIFY AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedBlueprints); - AssertionsHelper.assertFolderContainsFiles(fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "ngnix"), expectedBlueprintFiles); + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "ngnix"), expectedBlueprintFiles); } - + @Test void testExportContentWithNonExistingBlueprint() { - //GIVEN + // GIVEN List blueprints = new ArrayList<>(); BlueprintMockBuilder ngnixMockBuilder = new BlueprintMockBuilder("ngnix"); @@ -179,7 +179,7 @@ void testExportContentWithNonExistingBlueprint() { when(vraNgPackageDescriptor.getBlueprint()).thenReturn(blueprintNames); when(restClient.getAllBlueprints()).thenReturn(blueprints); - //TEST + // TEST assertThrows(IllegalStateException.class, () -> store.exportContent()); } @@ -196,8 +196,11 @@ void testImportContentWithDotInName() { fsMocks.blueprintFsMocks().addBlueprint(blueprint); - AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), new String[]{"nginx 8.x test"}); - AssertionsHelper.assertFolderContainsFiles(fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx 8.x test"), new String[]{"content.yaml", "details.json"}); + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), + new String[] { "nginx 8.x test" }); + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx 8.x test"), + new String[] { "content.yaml", "details.json" }); List bluePrintsOnServer = new ArrayList<>(); @@ -225,8 +228,10 @@ void testImportContent() throws IOException, ParseException { fsMocks.blueprintFsMocks().addBlueprint(blueprint); - AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), new String[]{"nginx"}); - AssertionsHelper.assertFolderContainsFiles(fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx"), new String[]{"content.yaml", "details.json"}); + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), new String[] { "nginx" }); + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx"), + new String[] { "content.yaml", "details.json" }); List bluePrintsOnServer = new ArrayList<>(); @@ -254,8 +259,10 @@ void testImportContentWhenDuplicateBlueprintsExistOnServer() throws IOException, fsMocks.blueprintFsMocks().addBlueprint(blueprint); - AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), new String[]{"nginx"}); - AssertionsHelper.assertFolderContainsFiles(fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx"), new String[]{"content.yaml", "details.json"}); + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), new String[] { "nginx" }); + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx"), + new String[] { "content.yaml", "details.json" }); List bluePrintsOnServer = new ArrayList<>(); bluePrintsOnServer.add(blueprint); @@ -286,9 +293,11 @@ void testImportContentForNonExistingBlueprintsInConfiguration() throws IOExcepti VraNgBlueprint blueprint = builder.build(); fsMocks.blueprintFsMocks().addBlueprint(blueprint); - - AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), new String[]{"nginx"}); - AssertionsHelper.assertFolderContainsFiles(fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx"), new String[]{"content.yaml", "details.json"}); + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), new String[] { "nginx" }); + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "nginx"), + new String[] { "content.yaml", "details.json" }); List bluePrintsOnServer = new ArrayList<>(); diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCatalogItemStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCatalogItemStoreTest.java new file mode 100644 index 000000000..b4984f0e9 --- /dev/null +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCatalogItemStoreTest.java @@ -0,0 +1,1026 @@ +/* + * #%L + * artifact-manager + * %% + * Copyright (C) 2023 VMware + * %% + * Build Tools for VMware Aria + * Copyright 2023 VMware, Inc. + * + * This product is licensed to you under the BSD-2 license (the "License"). You may not use this product except in compliance with the BSD-2 License. + * + * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. + * #L% + */ +package com.vmware.pscoe.iac.artifact.aria.automation.store; + +import com.google.gson.JsonArray; + +import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; +import com.vmware.pscoe.iac.artifact.helpers.AssertionsHelper; +import com.vmware.pscoe.iac.artifact.helpers.FsMocks; +import com.vmware.pscoe.iac.artifact.helpers.GeneralMocks; +import com.vmware.pscoe.iac.artifact.helpers.stubs.CatalogItemMockBuilder; +import com.vmware.pscoe.iac.artifact.helpers.stubs.ContentSourceBaseMockBuilder; +import com.vmware.pscoe.iac.artifact.helpers.stubs.CustomFormMockBuilder; +import com.vmware.pscoe.iac.artifact.model.Package; +import com.vmware.pscoe.iac.artifact.model.PackageFactory; +import com.vmware.pscoe.iac.artifact.model.PackageType; +import com.vmware.pscoe.iac.artifact.aria.automation.models.*; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; +import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; + +import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.springframework.http.ResponseEntity; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +/** + * NOTE: This does not test duplicate names from one content source, since the + * Store is not responsible for that kind of logic. + */ +public class VraNgCatalogItemStoreTest { + /** + * Temp Folder. + */ + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + /** + * store. + */ + protected VraNgCatalogItemStore store; + /** + * restClient. + */ + protected RestClientVraNg restClient; + /** + * pkg. + */ + protected Package pkg; + /** + * config. + */ + protected ConfigurationVraNg config; + /** + * vraNgPackageDescriptor. + */ + protected VraNgPackageDescriptor vraNgPackageDescriptor; + /** + * fsMocks. + */ + protected FsMocks fsMocks; + /** + * Example project id. + */ + protected static String PROJECT_ID = "projectId"; + /** + * Mocked source id. + */ + protected static String CONTENT_SOURCE_ID = "mockedSourceId"; + /** + * Mocked catalog item id. + */ + protected static String CATALOG_ITEM_ID = "mockedItemId"; + + /** + * Init method called before each test. + */ + @BeforeEach + void init() { + try { + tempFolder.create(); + } catch (IOException e) { + throw new RuntimeException("Could not create a temp folder"); + } + + fsMocks = new FsMocks(tempFolder.getRoot()); + store = new VraNgCatalogItemStore(); + restClient = Mockito.mock(RestClientVraNg.class); + pkg = PackageFactory.getInstance(PackageType.VRANG, tempFolder.getRoot()); + config = Mockito.mock(ConfigurationVraNg.class); + vraNgPackageDescriptor = Mockito.mock(VraNgPackageDescriptor.class); + + store.init(restClient, pkg, config, vraNgPackageDescriptor); + System.out.println("=========================================================="); + System.out.println("START"); + System.out.println("=========================================================="); + } + + /** + * Cleanup method called after each test. + */ + @AfterEach + void tearDown() { + tempFolder.delete(); + + System.out.println("=========================================================="); + System.out.println("END"); + System.out.println("=========================================================="); + } + + @Test + void testExportContentWithAllCatalogItemsWhenNoItems() { + // GIVEN + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(new ArrayList<>()); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, never()).getContentSource(anyString()); + verify(restClient, never()).getCustomFormByTypeAndSource(anyString(), anyString()); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSource() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + + VraNgCatalogItem catalogItemOne = builderOne.build(); + VraNgCatalogItem catalogItemTwo = builderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(2)).getContentSource(anyString()); + verify(restClient, times(2)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + assertEquals(2, fsMocks.getTempFolderProjectPath().listFiles().length); + + String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json", + "contentSourceNameOne__catalogItemTwo.json" }; + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedFiles); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentButFilteringIsEmpty() { + // GIVEN + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = builderOne.build(); + VraNgCatalogItem catalogItemTwo = builderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(new ArrayList<>()); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, never()).getCatalogItemsForProject(anyString()); + verify(restClient, never()).getProjectId(); + verify(restClient, never()).getContentSource(anyString()); + verify(restClient, never()).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(0, tempFolder.getRoot().listFiles().length); + } + + @Test + void testExportContentWithSomeCatalogItemsWhenItemsArePresentFromOneSource() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); + + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = builderOne.build(); + VraNgCatalogItem catalogItemTwo = builderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(1)).getContentSource(anyString()); + verify(restClient, times(1)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + assertEquals(fsMocks.getTempFolderProjectPath().listFiles().length, 1); + + String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json" }; + + assertArrayEquals(fsMocks.getTempFolderProjectPath().list(), expectedFiles); + } + + @Test + void testExportContentWithSomeCatalogItemsWhenItemNameHasIncorrectFormat() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("wrongFormat"); + + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = builderOne.build(); + VraNgCatalogItem catalogItemTwo = builderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + assertThrows(RuntimeException.class, () -> { + store.exportContent(); + }); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, never()).getContentSource(anyString()); + verify(restClient, never()).getCustomFormByTypeAndSource(anyString(), anyString()); + } + + @Test + void testExportContentWithSomeCatalogItemsWhenContentSourceDoesNotExist() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); + + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = builderOne.build(); + VraNgCatalogItem catalogItemTwo = builderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(null); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + assertThrows(RuntimeException.class, () -> { + store.exportContent(); + }); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(1)).getContentSource(anyString()); + verify(restClient, never()).getCustomFormByTypeAndSource(anyString(), anyString()); + } + + @Test + void testExportContentWithNoNExistingCatalogItems() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__nonExisting"); + + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = builderOne.build(); + VraNgCatalogItem catalogItemTwo = builderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(null); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + assertThrows(IllegalStateException.class, () -> { + store.exportContent(); + }); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceWithForm() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + + String formIdOne = "formIdCatalogItemOne"; + String formIdTwo = "formIdCatalogItemTwo"; + CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); + CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); + VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); + VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = catalogBuilderOne.setCustomFormId(formIdOne).build(); + + CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setCustomFormId(formIdTwo).build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when( + restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)) + .thenReturn(mockedFormOne, mockedFormTwo); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(2)).getContentSource(anyString()); + verify(restClient, times(2)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + + String[] expectedFilesAndFolders = { + "contentSourceNameOne__catalogItemOne.json", + "forms", + "contentSourceNameOne__catalogItemTwo.json" + }; + + String[] expectedFormNames = { + "contentSourceNameOne__catalogItemOne.json", + "contentSourceNameOne__catalogItemOne__FormData.json", + "contentSourceNameOne__catalogItemTwo.json", + "contentSourceNameOne__catalogItemTwo__FormData.json" + }; + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedFilesAndFolders); + + for (File file : fsMocks.getTempFolderProjectPath().listFiles()) { + if (file.getName().equalsIgnoreCase("forms")) { + AssertionsHelper.assertFolderContainsFiles(file, expectedFormNames); + } + } + } + + @SuppressWarnings("unchecked") + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceWithFormAndIcon() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + + String iconIdOne = "iconIdCatalogItemOne"; + String formIdOne = "formIdCatalogItemOne"; + String formIdTwo = "formIdCatalogItemTwo"; + String iconIdTwo = "iconIdCatalogItemTwo"; + Map headers = new HashMap<>(); + headers.put("Content-Type", "image/png"); + + ResponseEntity iconOneResponse = GeneralMocks.mockResponseEntity( + "iconBodyOne".getBytes(), + 200, + headers); + ResponseEntity iconTwoResponse = GeneralMocks.mockResponseEntity( + "iconBodyTwo".getBytes(), + 200, + headers); + + CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); + CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); + VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); + VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = catalogBuilderOne.setIconId(iconIdOne).setIconExt("png") + .setCustomFormId(formIdOne).build(); + + CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setIconId(iconIdTwo).setIconExt("png") + .setCustomFormId(formIdTwo).build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(restClient.downloadIcon(anyString())).thenReturn(iconOneResponse, iconTwoResponse); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when( + restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)) + .thenReturn(mockedFormOne, mockedFormTwo); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(2)).getContentSource(anyString()); + verify(restClient, times(2)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + + String[] expectedFilesAndFolders = { + "contentSourceNameOne__catalogItemOne.json", + "forms", + "icons", + "contentSourceNameOne__catalogItemTwo.json" + }; + + String[] expectedFormNames = { + "contentSourceNameOne__catalogItemOne.json", + "contentSourceNameOne__catalogItemOne__FormData.json", + "contentSourceNameOne__catalogItemTwo.json", + "contentSourceNameOne__catalogItemTwo__FormData.json", + }; + + String[] expectedIconNames = { + "contentSourceNameOne__catalogItemOne.png", + "contentSourceNameOne__catalogItemTwo.png" + }; + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedFilesAndFolders); + + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "forms"), + expectedFormNames); + + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "icons"), + expectedIconNames); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceButIconDoesNotExist() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + + String iconIdOne = "iconIdCatalogItemOne"; + String formIdOne = "formIdCatalogItemOne"; + String formIdTwo = "formIdCatalogItemTwo"; + String iconIdTwo = "iconIdCatalogItemTwo"; + + ResponseEntity iconOneResponse = GeneralMocks.mockResponseEntity( + "iconBodyOne".getBytes(), + 500); + CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); + CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); + VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); + VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = catalogBuilderOne.setIconId(iconIdOne).setIconExt("png") + .setCustomFormId(formIdOne).build(); + + CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setIconId(iconIdTwo).setIconExt("png") + .setCustomFormId(formIdTwo).build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(restClient.downloadIcon(anyString())).thenReturn(iconOneResponse); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when( + restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)) + .thenReturn(mockedFormOne, mockedFormTwo); + + // START TEST + assertThrows(RuntimeException.class, () -> store.exportContent()); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(1)).getContentSource(anyString()); + verify(restClient, times(1)).getCustomFormByTypeAndSource(anyString(), anyString()); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceWithFormAndSameIcon() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + + String iconId = "iconId"; + String formIdOne = "formIdCatalogItemOne"; + String formIdTwo = "formIdCatalogItemTwo"; + Map headers = new HashMap<>(); + headers.put("Content-Type", "image/png"); + + ResponseEntity iconOneResponse = GeneralMocks.mockResponseEntity( + "iconBody".getBytes(), + 200, + headers); + CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); + CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); + VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); + VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = catalogBuilderOne.setIconId(iconId).setIconExt("png") + .setCustomFormId(formIdOne).build(); + + CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); + VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setIconId(iconId).setIconExt("png") + .setCustomFormId(formIdTwo).build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(restClient.downloadIcon(anyString())).thenReturn(iconOneResponse); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when( + restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)) + .thenReturn(mockedFormOne, mockedFormTwo); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(2)).getContentSource(anyString()); + verify(restClient, times(2)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + + String[] expectedFilesAndFolders = { + "contentSourceNameOne__catalogItemOne.json", + "forms", + "icons", + "contentSourceNameOne__catalogItemTwo.json" + }; + + String[] expectedFormNames = { + "contentSourceNameOne__catalogItemOne.json", + "contentSourceNameOne__catalogItemOne__FormData.json", + "contentSourceNameOne__catalogItemTwo.json", + "contentSourceNameOne__catalogItemTwo__FormData.json" + }; + + String[] expectedIconNames = { + "contentSourceNameOne__catalogItemOne.png", + "contentSourceNameOne__catalogItemTwo.png", + }; + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedFilesAndFolders); + + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "forms"), + expectedFormNames); + + AssertionsHelper.assertFolderContainsFiles( + fsMocks.findItemByNameInFolder(fsMocks.getTempFolderProjectPath(), "icons"), + expectedIconNames); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromTwoSources() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = catalogBuilderOne.build(); + + CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameTwo"); + VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(2)).getContentSource(anyString()); + verify(restClient, times(2)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + assertEquals(2, fsMocks.getTempFolderProjectPath().listFiles().length); + + String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json", + "contentSourceNameTwo__catalogItemTwo.json" }; + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedFiles); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromTwoSourcesWithSameName() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = catalogBuilderOne.build(); + + CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameTwo"); + VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(2)).getContentSource(anyString()); + verify(restClient, times(2)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + assertEquals(2, fsMocks.getTempFolderProjectPath().listFiles().length); + + String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json", + "contentSourceNameTwo__catalogItemOne.json" }; + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedFiles); + } + + @Test + void testExportContentWithAllCatalogItemsWhenItemsArePresentFromSameSourceWithSameNames() { + // GIVEN + ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); + + String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); + VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); + List mockedCatalogItems = new ArrayList<>(); + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemOne = catalogBuilderOne.build(); + + CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.build(); + + mockedCatalogItems.add(catalogItemOne); + mockedCatalogItems.add(catalogItemTwo); + + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(null); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getContentSource(CONTENT_SOURCE_ID)).thenReturn(contentSource); + when(contentSource.getType()).thenReturn(VraNgContentSourceType.VRO_WORKFLOW); + when(restClient.getCustomFormByTypeAndSource(contentSourceType, CATALOG_ITEM_ID)).thenReturn(null); + + // START TEST + store.exportContent(); + + // VERIFY + verify(vraNgPackageDescriptor, times(1)).getCatalogItem(); + verify(restClient, times(1)).getCatalogItemsForProject(anyString()); + verify(restClient, times(1)).getProjectId(); + verify(restClient, times(2)).getContentSource(anyString()); + verify(restClient, times(2)).getCustomFormByTypeAndSource(anyString(), anyString()); + assertEquals(1, tempFolder.getRoot().listFiles().length); + assertEquals(fsMocks.getTempFolderProjectPath().listFiles().length, 1); + + // Gets overwritten by the last one + String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json" }; + + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedFiles); + } + + @Test + void testImportContentWithNoIconsOrForms() { + // GIVEN + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItem = catalogBuilderOne.build(); + fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); + + List mockedCatalogItems = new ArrayList<>(); + mockedCatalogItems.add(catalogItem); + + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + + // START TEST + store.importContent(tempFolder.getRoot()); + + // VERIFY + verify(restClient, never()).importCustomForm(any(), anyString()); + verify(restClient, never()).uploadIcon(any()); + } + + @Test + void testImportContentWithAnIconAndNoForms() { + // GIVEN + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + + String iconId = "iconId"; + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").build(); + + Map headers = new HashMap<>(); + headers.put("Location", "/some/path/iconId"); + ResponseEntity response = GeneralMocks.mockResponseEntity("", 201, headers); + + List mockedCatalogItems = new ArrayList<>(); + mockedCatalogItems.add(catalogItem); + + fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemIcon(catalogItem); + when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.uploadIcon(any())).thenReturn(response); + + // START TEST + store.importContent(tempFolder.getRoot()); + + // VERIFY + verify(restClient, never()).importCustomForm(any(), anyString()); + verify(restClient, times(1)).uploadIcon(any()); + } + + @Test + void testImportContentWithAnIconAndForms() { + // GIVEN + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + + String iconId = "iconId"; + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId") + .build(); + + Map headers = new HashMap<>(); + headers.put("Location", "/some/path/iconId"); + ResponseEntity response = GeneralMocks.mockResponseEntity("", 201, headers); + + List mockedCatalogItems = new ArrayList<>(); + mockedCatalogItems.add(catalogItem); + + fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemIcon(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemForm(catalogItem); + when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.uploadIcon(any())).thenReturn(response); + doNothing().when(restClient).importCustomForm(any(), anyString()); + + // START TEST + store.importContent(tempFolder.getRoot()); + + // VERIFY + verify(restClient, times(1)).importCustomForm(any(), anyString()); + verify(restClient, times(1)).uploadIcon(any()); + } + + @Test + void testImportContentWithAnIconAndFormsWithDotInName() { + // GIVEN + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSource. NameOne__catalogItem One.x"); + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + + String iconId = "iconId"; + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItem One.x", + "contentSource. NameOne"); + VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId") + .build(); + + Map headers = new HashMap<>(); + headers.put("Location", "/some/path/iconId"); + ResponseEntity response = GeneralMocks.mockResponseEntity("", 201, headers); + + List mockedCatalogItems = new ArrayList<>(); + mockedCatalogItems.add(catalogItem); + + fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemIcon(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemForm(catalogItem); + when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.uploadIcon(any())).thenReturn(response); + doNothing().when(restClient).importCustomForm(any(), anyString()); + + // START TEST + store.importContent(tempFolder.getRoot()); + + // VERIFY + verify(restClient, times(1)).importCustomForm(any(), anyString()); + verify(restClient, times(1)).uploadIcon(any()); + } + + @Test + void testImportContentWithoutAnIconAndWithForms() { + // GIVEN + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItem = catalogBuilderOne.setCustomFormId("formId").build(); + + List mockedCatalogItems = new ArrayList<>(); + mockedCatalogItems.add(catalogItem); + + fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemForm(catalogItem); + when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + doNothing().when(restClient).importCustomForm(any(), anyString()); + + // START TEST + store.importContent(tempFolder.getRoot()); + + // VERIFY + verify(restClient, times(1)).importCustomForm(any(), anyString()); + } + + @Test + void testImportContentWithAnIconAndFormsWithVraAbove812() { + // GIVEN + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + + String iconId = "iconId"; + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItemType bpCatalogItem = new VraNgCatalogItemType(VraNgContentSourceType.BLUEPRINT, null, null); + VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId") + .setType(bpCatalogItem).build(); + + Map headers = new HashMap<>(); + headers.put("Location", "/some/path/iconId"); + ResponseEntity response = GeneralMocks.mockResponseEntity("", 201, headers); + + List mockedCatalogItems = new ArrayList<>(); + mockedCatalogItems.add(catalogItem); + + fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemIcon(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemForm(catalogItem); + when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.uploadIcon(any())).thenReturn(response); + when(restClient.getIsVraAbove812()).thenReturn(true); + when(restClient.getCatalogItemVersions(catalogItem.getId())).thenReturn(new JsonArray()); + + doNothing().when(restClient).importCustomForm(any(), anyString()); + VraNgCatalogItemStore vra812Store = (VraNgCatalogItemStore812) new VraNgTypeStoreFactory(restClient, pkg, + config, vraNgPackageDescriptor) + .getStoreForType(VraNgPackageContent.ContentType.CATALOG_ITEM); + + // START TEST + vra812Store.importContent(tempFolder.getRoot()); + + // VERIFY + verify(restClient, times(1)).importCustomForm(any(), anyString()); + verify(restClient, times(1)).uploadIcon(any()); + } + + @Test + void testImportContentWithAnIconAndFormsWithVraBelow812() { + // GIVEN + List mockCatalogItemNames = new ArrayList<>(); + mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); + when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); + + String iconId = "iconId"; + CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); + VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId") + .build(); + + Map headers = new HashMap<>(); + headers.put("Location", "/some/path/iconId"); + ResponseEntity response = GeneralMocks.mockResponseEntity("", 201, headers); + + List mockedCatalogItems = new ArrayList<>(); + mockedCatalogItems.add(catalogItem); + + fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemIcon(catalogItem); + fsMocks.catalogItemFsMocks().addCatalogItemForm(catalogItem); + when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); + when(restClient.getProjectId()).thenReturn(PROJECT_ID); + when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + when(restClient.uploadIcon(any())).thenReturn(response); + when(restClient.getIsVraAbove812()).thenReturn(false); + + doNothing().when(restClient).importCustomForm(any(), anyString()); + + // START TEST + store.importContent(tempFolder.getRoot()); + + // VERIFY + verify(restClient, times(1)).importCustomForm(any(), anyString()); + verify(restClient, times(1)).uploadIcon(any()); + } +} diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgContentSharingPolicyStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgContentSharingPolicyStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgContentSharingPolicyStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgContentSharingPolicyStoreTest.java index 9eaf11652..7a3ed632d 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgContentSharingPolicyStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgContentSharingPolicyStoreTest.java @@ -26,12 +26,12 @@ import java.io.File; import java.io.IOException; import java.nio.file.Paths; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.models.*; import org.junit.Rule; import org.junit.jupiter.api.AfterEach; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgContentSourceStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgContentSourceStoreTest.java new file mode 100644 index 000000000..255bed7a8 --- /dev/null +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgContentSourceStoreTest.java @@ -0,0 +1,169 @@ +/* + * #%L + * artifact-manager + * %% + * Copyright (C) 2023 VMware + * %% + * Build Tools for VMware Aria + * Copyright 2023 VMware, Inc. + * + * This product is licensed to you under the BSD-2 license (the "License"). You may not use this product except in compliance with the BSD-2 License. + * + * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. + * #L% + */ +package com.vmware.pscoe.iac.artifact.aria.automation.store; + +import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; +import com.vmware.pscoe.iac.artifact.helpers.AssertionsHelper; +import com.vmware.pscoe.iac.artifact.helpers.FsMocks; +import com.vmware.pscoe.iac.artifact.helpers.stubs.ContentSourceBaseMockBuilder; +import com.vmware.pscoe.iac.artifact.model.Package; +import com.vmware.pscoe.iac.artifact.model.PackageFactory; +import com.vmware.pscoe.iac.artifact.model.PackageType; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; +import com.vmware.pscoe.iac.artifact.aria.automation.models.*; +import com.vmware.pscoe.iac.artifact.rest.RestClient; +import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; + +import org.junit.Rule; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +public class VraNgContentSourceStoreTest { + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + protected static String PROJECT_ID = "projectId"; + protected VraNgContentSourceStore store; + protected RestClientVraNg restClient; + protected Package pkg; + protected ConfigurationVraNg config; + protected VraNgPackageDescriptor vraNgPackageDescriptor; + protected FsMocks fsMocks; + + @BeforeEach + void init() { + try { + tempFolder.create(); + } catch (IOException e) { + throw new RuntimeException("Could not create a temp folder"); + } + + fsMocks = new FsMocks(tempFolder.getRoot()); + store = new VraNgContentSourceStore(); + restClient = Mockito.mock(RestClientVraNg.class); + pkg = PackageFactory.getInstance(PackageType.VRANG, tempFolder.getRoot()); + config = Mockito.mock(ConfigurationVraNg.class); + vraNgPackageDescriptor = Mockito.mock(VraNgPackageDescriptor.class); + + store.init(restClient, pkg, config, vraNgPackageDescriptor); + System.out.println("=========================================================="); + System.out.println("START"); + System.out.println("=========================================================="); + } + + @AfterEach + void tearDown() { + tempFolder.delete(); + + System.out.println("=========================================================="); + System.out.println("END"); + System.out.println("=========================================================="); + } + + @Test + void testExportContentWithNoContentSource() { + // GIVEN + ArrayList data = new ArrayList<>(); + data.add("nothing"); + + List mockedCatalogItems = new ArrayList<>(); + ContentSourceBaseMockBuilder builderOne = new ContentSourceBaseMockBuilder(); + VraNgContentSourceBase contentSourceOne = builderOne.setName("thing1").build(); + ContentSourceBaseMockBuilder builderTwo = new ContentSourceBaseMockBuilder(); + VraNgContentSourceBase contentSourceTwo = builderOne.setName("thing2").build(); + mockedCatalogItems.add(contentSourceOne); + mockedCatalogItems.add(contentSourceTwo); + + when(vraNgPackageDescriptor.getContentSource()).thenReturn(data); + when(restClient.getContentSourcesForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); + // TEST + assertThrows(IllegalStateException.class, () -> store.exportContent()); + + // VERIFY + verify(restClient, never()).getContentSourcesForProject(anyString()); + + assertEquals(0, tempFolder.getRoot().listFiles().length); + } + + @Test + void testExportContentThatDoesNotExistOnTheServer() { + // GIVEN + when(vraNgPackageDescriptor.getContentSource()).thenReturn(new ArrayList()); + + // TEST + store.exportContent(); + + // VERIFY + verify(restClient, never()).getContentSourcesForProject(anyString()); + + assertEquals(0, tempFolder.getRoot().listFiles().length); + } + + @Test + void testExportContentWithNullValue() { + + when(vraNgPackageDescriptor.getContentSource()).thenReturn(null); + // TEST + assertDoesNotThrow(() -> store.exportContent()); + + } + + // TODO not easy to implement the test because the VraNgContentSourceBase is too + // complext to be mocked. VraNgContentSourceBase is casted dynamically to other + // classes + // @Test + // void testExportContentWithAllContentSources() { + // //GIVEN + // when( restClient.getProjectId()).thenReturn("mockedProjectId"); + // VraNgContentSourceStore store1 = new VraNgContentSourceStore(); + // store1.init( restClient, pkg, config, vraNgPackageDescriptor ); + + // List contentSources = new ArrayList<>(); + // ContentSourceBaseMockBuilder builder = new ContentSourceBaseMockBuilder(); + + // contentSources.add( builder.setName("mockContentSource1").build()); + + // when( vraNgPackageDescriptor.getContentSource()).thenReturn(null); + // when( restClient.getContentSourcesForProject("mockedProjectId")).thenReturn( + // contentSources ); + + // //TEST + // store1.exportContent(); + + // String[] expectedContentSources = { "mockContentSource1.json" }; + + // // VERIFY + // verify(restClient, times(1)).getContentSourcesForProject("mockedProjectId"); + // AssertionsHelper.assertFolderContainsFiles( + // fsMocks.getTempFolderProjectPath(), expectedContentSources ); + // } + + // @Test + // void testExportContentWithSpecificContentSources() {} + +} diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCustomFormTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCustomFormTest.java similarity index 100% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCustomFormTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCustomFormTest.java diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCustomResourceStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCustomResourceStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCustomResourceStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCustomResourceStoreTest.java index dfccddebc..522950654 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCustomResourceStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgCustomResourceStoreTest.java @@ -23,8 +23,6 @@ import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgOrganization; import com.google.gson.*; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; import org.mockito.ArgumentCaptor; import org.springframework.http.HttpStatus; import org.springframework.web.client.HttpClientErrorException; @@ -42,7 +40,7 @@ import com.vmware.pscoe.iac.artifact.model.PackageType; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgCustomResource; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgIntegration; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.apache.commons.io.FileUtils; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgDay2ActionsPolicyStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgDay2ActionsPolicyStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgDay2ActionsPolicyStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgDay2ActionsPolicyStoreTest.java index 7cc66d2b2..8200691cf 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgDay2ActionsPolicyStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgDay2ActionsPolicyStoreTest.java @@ -21,6 +21,7 @@ import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.junit.Rule; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgDeploymentLimitPolicyStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgDeploymentLimitPolicyStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgDeploymentLimitPolicyStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgDeploymentLimitPolicyStoreTest.java index 945a40f9c..e87a73a1b 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgDeploymentLimitPolicyStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgDeploymentLimitPolicyStoreTest.java @@ -21,6 +21,7 @@ import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.junit.Rule; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgEntitlementStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgEntitlementStoreTest.java similarity index 60% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgEntitlementStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgEntitlementStoreTest.java index ecd2c9596..5f7ce1015 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgEntitlementStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgEntitlementStoreTest.java @@ -21,6 +21,7 @@ import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.models.*; import com.vmware.pscoe.iac.artifact.rest.RestClient; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; @@ -41,82 +42,81 @@ public class VraNgEntitlementStoreTest { @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); + public TemporaryFolder tempFolder = new TemporaryFolder(); - protected VraNgEntitlementStore store; - protected RestClientVraNg restClient; - protected Package pkg; - protected ConfigurationVraNg config; - protected VraNgPackageDescriptor vraNgPackageDescriptor; - protected FsMocks fsMocks; + protected VraNgEntitlementStore store; + protected RestClientVraNg restClient; + protected Package pkg; + protected ConfigurationVraNg config; + protected VraNgPackageDescriptor vraNgPackageDescriptor; + protected FsMocks fsMocks; @BeforeEach void init() { try { tempFolder.create(); - } - catch ( IOException e ) { - throw new RuntimeException( "Could not create a temp folder" ); + } catch (IOException e) { + throw new RuntimeException("Could not create a temp folder"); } - fsMocks = new FsMocks( tempFolder.getRoot() ); - store = new VraNgEntitlementStore(); - restClient = Mockito.mock( RestClientVraNg.class ); - pkg = PackageFactory.getInstance( PackageType.VRANG, tempFolder.getRoot() ); - config = Mockito.mock( ConfigurationVraNg.class ); - vraNgPackageDescriptor = Mockito.mock( VraNgPackageDescriptor.class ); - - store.init( restClient, pkg, config, vraNgPackageDescriptor ); - System.out.println( "==========================================================" ); - System.out.println( "START" ); - System.out.println( "==========================================================" ); + fsMocks = new FsMocks(tempFolder.getRoot()); + store = new VraNgEntitlementStore(); + restClient = Mockito.mock(RestClientVraNg.class); + pkg = PackageFactory.getInstance(PackageType.VRANG, tempFolder.getRoot()); + config = Mockito.mock(ConfigurationVraNg.class); + vraNgPackageDescriptor = Mockito.mock(VraNgPackageDescriptor.class); + + store.init(restClient, pkg, config, vraNgPackageDescriptor); + System.out.println("=========================================================="); + System.out.println("START"); + System.out.println("=========================================================="); } @AfterEach void tearDown() { tempFolder.delete(); - System.out.println( "==========================================================" ); - System.out.println( "END" ); - System.out.println( "==========================================================" ); + System.out.println("=========================================================="); + System.out.println("END"); + System.out.println("=========================================================="); } @Test void testExportContentWithNoEntitlements() { - //GIVEN - when( vraNgPackageDescriptor.getCatalogEntitlement() ).thenReturn(new ArrayList()); + // GIVEN + when(vraNgPackageDescriptor.getCatalogEntitlement()).thenReturn(new ArrayList()); - //TEST + // TEST store.exportContent(); - //VERIFY - verify( restClient, never() ).getAllCatalogEntitlements(); - assertEquals( 0, tempFolder.getRoot().listFiles().length ); + // VERIFY + verify(restClient, never()).getAllCatalogEntitlements(); + assertEquals(0, tempFolder.getRoot().listFiles().length); } @Test void testExportContentWithAllEntitlements() { - //GIVEN + // GIVEN when(vraNgPackageDescriptor.getCatalogEntitlement()).thenReturn(null); List entitlements = new ArrayList<>(); CatalogEntitlementMockBuilder builder = new CatalogEntitlementMockBuilder("entitlement1"); entitlements.add(builder.build()); - when( restClient.getAllCatalogEntitlements() ).thenReturn( entitlements ); + when(restClient.getAllCatalogEntitlements()).thenReturn(entitlements); - //TEST + // TEST store.exportContent(); - String[] expectedEntitlementsFile = { "entitlement1.yaml" }; + String[] expectedEntitlementsFile = { "entitlement1.yaml" }; - //VERIFY - verify( restClient, times(1) ).getAllCatalogEntitlements(); - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedEntitlementsFile ); + // VERIFY + verify(restClient, times(1)).getAllCatalogEntitlements(); + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedEntitlementsFile); } @Test void testExportContentWithSpecificEntitlements() { - //GIVEN + // GIVEN List entitlements = new ArrayList<>(); CatalogEntitlementMockBuilder builder1 = new CatalogEntitlementMockBuilder("entitlement1"); CatalogEntitlementMockBuilder builder2 = new CatalogEntitlementMockBuilder("entitlement2"); @@ -127,21 +127,21 @@ void testExportContentWithSpecificEntitlements() { List entitlementsNames = new ArrayList<>(); entitlementsNames.add("entitlement1"); - when( vraNgPackageDescriptor.getCatalogEntitlement() ).thenReturn(entitlementsNames); + when(vraNgPackageDescriptor.getCatalogEntitlement()).thenReturn(entitlementsNames); - //TEST + // TEST store.exportContent(); - String[] expectedEntitlementsFile = { "entitlement1.yaml" }; + String[] expectedEntitlementsFile = { "entitlement1.yaml" }; - //VERIFY - verify( restClient, times(1) ).getAllCatalogEntitlements(); - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedEntitlementsFile ); + // VERIFY + verify(restClient, times(1)).getAllCatalogEntitlements(); + AssertionsHelper.assertFolderContainsFiles(fsMocks.getTempFolderProjectPath(), expectedEntitlementsFile); } @Test void testImportContentExcludingFromConfiguration() { - //GIVEN + // GIVEN CatalogEntitlementMockBuilder builder1 = new CatalogEntitlementMockBuilder("entitlement1"); CatalogEntitlementMockBuilder builder2 = new CatalogEntitlementMockBuilder("entitlement2"); @@ -150,18 +150,18 @@ void testImportContentExcludingFromConfiguration() { List entitlementsNames = new ArrayList<>(); entitlementsNames.add("entitlement"); - when( vraNgPackageDescriptor.getCatalogEntitlement() ).thenReturn(entitlementsNames); + when(vraNgPackageDescriptor.getCatalogEntitlement()).thenReturn(entitlementsNames); - //TEST + // TEST store.importContent(tempFolder.getRoot()); - //VERIFY - verify( restClient, times(0) ).createCatalogEntitlement(any(), any()); + // VERIFY + verify(restClient, times(0)).createCatalogEntitlement(any(), any()); } @Test void testExportContentWithNoExistingEntitlement() { - //GIVEN + // GIVEN List entitlements = new ArrayList<>(); CatalogEntitlementMockBuilder builder1 = new CatalogEntitlementMockBuilder("entitlement1"); CatalogEntitlementMockBuilder builder2 = new CatalogEntitlementMockBuilder("entitlement2"); @@ -172,12 +172,12 @@ void testExportContentWithNoExistingEntitlement() { List entitlementsNames = new ArrayList<>(); entitlementsNames.add("noting"); - when( vraNgPackageDescriptor.getCatalogEntitlement() ).thenReturn(entitlementsNames); + when(vraNgPackageDescriptor.getCatalogEntitlement()).thenReturn(entitlementsNames); - //TEST + // TEST assertThrows(IllegalStateException.class, () -> store.exportContent()); - //VERIFY - verify( restClient, times(1)).getAllCatalogEntitlements(); + // VERIFY + verify(restClient, times(1)).getAllCatalogEntitlements(); } } diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgLeasePolicyStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgLeasePolicyStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgLeasePolicyStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgLeasePolicyStoreTest.java index 78c2cf3a5..6ab9b911a 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgLeasePolicyStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgLeasePolicyStoreTest.java @@ -21,6 +21,7 @@ import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.junit.Rule; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgPropertyGroupStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgPropertyGroupStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgPropertyGroupStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgPropertyGroupStoreTest.java index 96a11db8c..1d9eb4593 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgPropertyGroupStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgPropertyGroupStoreTest.java @@ -22,7 +22,7 @@ import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgOrganization; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPropertyGroup; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.junit.Rule; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgReleaseManagerTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgReleaseManagerTest.java similarity index 100% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgReleaseManagerTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgReleaseManagerTest.java diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgResourceActionStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgResourceActionStoreTest.java similarity index 98% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgResourceActionStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgResourceActionStoreTest.java index df8258eda..5b0312dc3 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgResourceActionStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgResourceActionStoreTest.java @@ -21,7 +21,7 @@ import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgResourceAction; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgResourceQuotaPolicyStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgResourceQuotaPolicyStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgResourceQuotaPolicyStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgResourceQuotaPolicyStoreTest.java index 433d4bff4..da2837a49 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgResourceQuotaPolicyStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgResourceQuotaPolicyStoreTest.java @@ -21,6 +21,7 @@ import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.models.*; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; import org.junit.Rule; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgSubscriptionStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgSubscriptionStoreTest.java similarity index 99% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgSubscriptionStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgSubscriptionStoreTest.java index 16fbaa9ad..6961d6a19 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgSubscriptionStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/store/VraNgSubscriptionStoreTest.java @@ -53,7 +53,7 @@ import com.vmware.pscoe.iac.artifact.model.PackageType; import com.vmware.pscoe.iac.artifact.model.abx.AbxAction; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgOrganization; -import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.automation.store.models.VraNgPackageDescriptor; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgProject; import com.vmware.pscoe.iac.artifact.aria.automation.models.VraNgSubscription; import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/utils/VraNgProjectUtilTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/utils/VraNgProjectUtilTest.java similarity index 100% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/utils/VraNgProjectUtilTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/utils/VraNgProjectUtilTest.java diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/utils/package-info.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/utils/package-info.java similarity index 100% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/utils/package-info.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/automation/utils/package-info.java diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/configuration/ConfigurationVropsTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/operations/configuration/ConfigurationVropsTest.java similarity index 94% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/configuration/ConfigurationVropsTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/operations/configuration/ConfigurationVropsTest.java index 1a1dbded1..0003ffce0 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/configuration/ConfigurationVropsTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/operations/configuration/ConfigurationVropsTest.java @@ -12,11 +12,14 @@ * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact.configuration; +package com.vmware.pscoe.iac.artifact.aria.operations.configuration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; + +import com.vmware.pscoe.iac.artifact.configuration.ConfigurationException; + import java.net.UnknownHostException; import java.util.Properties; import static org.junit.jupiter.api.Assertions.assertSame; @@ -62,7 +65,6 @@ public void testValidateShouldNotBeNullHost() throws Exception { assertSame(configurationVrops.getHost(), "localhost"); } - @Test public void testValidateShouldNotBeNullVropDashboardUser() throws Exception { this.configurationVrops.validate(true); diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/store/vrops/VropsPackageStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/operations/store/VropsPackageStoreTest.java similarity index 87% rename from common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/store/vrops/VropsPackageStoreTest.java rename to common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/operations/store/VropsPackageStoreTest.java index ec89b777c..47331b62d 100644 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/store/vrops/VropsPackageStoreTest.java +++ b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/operations/store/VropsPackageStoreTest.java @@ -12,13 +12,12 @@ * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. * #L% */ -package com.vmware.pscoe.iac.artifact.store.vrops; +package com.vmware.pscoe.iac.artifact.aria.operations.store; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.any; import java.io.File; @@ -35,20 +34,19 @@ import com.jcraft.jsch.JSchException; import com.vmware.pscoe.iac.artifact.PackageMocked; -import com.vmware.pscoe.iac.artifact.VropsPackageStore; import com.vmware.pscoe.iac.artifact.cli.CliManagerVrops; import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; -import com.vmware.pscoe.iac.artifact.model.vrops.VropsPackageDescriptor; -import com.vmware.pscoe.iac.artifact.model.vrops.VropsPackageMemberType; -import com.vmware.pscoe.iac.artifact.rest.RestClientVrops; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.AuthGroupDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.AuthUserDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.PolicyDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.ReportDefinitionDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.SupermetricDTO; -import com.vmware.pscoe.iac.artifact.rest.model.vrops.ViewDefinitionDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.store.models.VropsPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.operations.store.models.VropsPackageMemberType; +import com.vmware.pscoe.iac.artifact.aria.operations.rest.RestClientVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.models.AuthGroupDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.AuthUserDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.PolicyDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.ReportDefinitionDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.SupermetricDTO; +import com.vmware.pscoe.iac.artifact.aria.operations.models.ViewDefinitionDTO; public class VropsPackageStoreTest { private static String VROPS_VERSION_8_17 = "8.17.0"; @@ -174,20 +172,27 @@ private void importVropsPackage(String vropsVersion) throws Exception { Mockito.doReturn(vropsVersion).when(restClientMock).getVersion(); Mockito.doReturn(allGroups).when(restClientMock).findAllAuthGroups(); Mockito.doReturn(allUsers).when(restClientMock).findAllAuthUsers(); - Mockito.doReturn(allGroups).when(restClientMock).findAuthGroupsByNames(Arrays.asList(new String[] { existingGroup })); - Mockito.doReturn(allUsers).when(restClientMock).findAuthUsersByNames(Arrays.asList(new String[] { existingUser })); - - Mockito.doNothing().when(restClientMock).importDefinitionsInVrops(new HashMap<>(), VropsPackageMemberType.ALERT_DEFINITION, new HashMap<>()); - Mockito.doNothing().when(restClientMock).importDefinitionsInVrops(new HashMap<>(), VropsPackageMemberType.SYMPTOM_DEFINITION, new HashMap<>()); - Mockito.doNothing().when(restClientMock).importDefinitionsInVrops(new HashMap<>(), VropsPackageMemberType.RECOMMENDATION, new HashMap<>()); - Mockito.doNothing().when(restClientMock).importCustomGroupInVrops(testCustomGroupName, testCustomGroupPayload, new HashMap<>()); + Mockito.doReturn(allGroups).when(restClientMock) + .findAuthGroupsByNames(Arrays.asList(new String[] { existingGroup })); + Mockito.doReturn(allUsers).when(restClientMock) + .findAuthUsersByNames(Arrays.asList(new String[] { existingUser })); + + Mockito.doNothing().when(restClientMock).importDefinitionsInVrops(new HashMap<>(), + VropsPackageMemberType.ALERT_DEFINITION, new HashMap<>()); + Mockito.doNothing().when(restClientMock).importDefinitionsInVrops(new HashMap<>(), + VropsPackageMemberType.SYMPTOM_DEFINITION, new HashMap<>()); + Mockito.doNothing().when(restClientMock).importDefinitionsInVrops(new HashMap<>(), + VropsPackageMemberType.RECOMMENDATION, new HashMap<>()); + Mockito.doNothing().when(restClientMock).importCustomGroupInVrops(testCustomGroupName, testCustomGroupPayload, + new HashMap<>()); Mockito.doNothing().when(restClientMock).setDefaultPolicy(defaultPolicy); Mockito.doNothing().when(restClientMock).setPolicyPriorities(Arrays.asList(new String[] { policyId })); Mockito.doNothing().when(restClientMock).importPolicyFromZip(any(), Mockito.isA(File.class), anyBoolean()); VropsPackageStore store = new VropsPackageStore(cliMock, restClientMock, tempFolder.newFolder()); - File packageZip = PackageMocked.createSamplePackageZip(tempFolder.newFolder(), "ViewName", "viewid123", existingDashboard, "AlertDefinitions"); + File packageZip = PackageMocked.createSamplePackageZip(tempFolder.newFolder(), "ViewName", "viewid123", + existingDashboard, "AlertDefinitions"); Package vropsPkg = PackageFactory.getInstance(PackageType.VROPS, packageZip); List packages = new ArrayList<>(); packages.add(vropsPkg); diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCatalogItemStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCatalogItemStoreTest.java deleted file mode 100644 index c2c87646b..000000000 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgCatalogItemStoreTest.java +++ /dev/null @@ -1,1013 +0,0 @@ -/* - * #%L - * artifact-manager - * %% - * Copyright (C) 2023 VMware - * %% - * Build Tools for VMware Aria - * Copyright 2023 VMware, Inc. - * - * This product is licensed to you under the BSD-2 license (the "License"). You may not use this product except in compliance with the BSD-2 License. - * - * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. - * #L% - */ -package com.vmware.pscoe.iac.artifact.aria.automation.store; - -import com.google.gson.JsonArray; - -import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; -import com.vmware.pscoe.iac.artifact.helpers.AssertionsHelper; -import com.vmware.pscoe.iac.artifact.helpers.FsMocks; -import com.vmware.pscoe.iac.artifact.helpers.GeneralMocks; -import com.vmware.pscoe.iac.artifact.helpers.stubs.CatalogItemMockBuilder; -import com.vmware.pscoe.iac.artifact.helpers.stubs.ContentSourceBaseMockBuilder; -import com.vmware.pscoe.iac.artifact.helpers.stubs.CustomFormMockBuilder; -import com.vmware.pscoe.iac.artifact.model.Package; -import com.vmware.pscoe.iac.artifact.model.PackageFactory; -import com.vmware.pscoe.iac.artifact.model.PackageType; -import com.vmware.pscoe.iac.artifact.aria.automation.models.*; -import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; -import org.junit.Rule; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.rules.TemporaryFolder; -import org.mockito.Mockito; -import org.springframework.http.ResponseEntity; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -/** - * NOTE: This does not test duplicate names from one content source, since the Store is not responsible for that kind of logic. - */ -public class VraNgCatalogItemStoreTest { - /** - * Temp Folder. - */ - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - /** - * store. - */ - protected VraNgCatalogItemStore store; - /** - * restClient. - */ - protected RestClientVraNg restClient; - /** - * pkg. - */ - protected Package pkg; - /** - * config. - */ - protected ConfigurationVraNg config; - /** - * vraNgPackageDescriptor. - */ - protected VraNgPackageDescriptor vraNgPackageDescriptor; - /** - * fsMocks. - */ - protected FsMocks fsMocks; - /** - * Example project id. - */ - protected static String PROJECT_ID = "projectId"; - /** - * Mocked source id. - */ - protected static String CONTENT_SOURCE_ID = "mockedSourceId"; - /** - * Mocked catalog item id. - */ - protected static String CATALOG_ITEM_ID = "mockedItemId"; - - /** - * Init method called before each test. - */ - @BeforeEach - void init() { - try { - tempFolder.create(); - } - catch ( IOException e ) { - throw new RuntimeException( "Could not create a temp folder" ); - } - - fsMocks = new FsMocks( tempFolder.getRoot() ); - store = new VraNgCatalogItemStore(); - restClient = Mockito.mock( RestClientVraNg.class ); - pkg = PackageFactory.getInstance( PackageType.VRANG, tempFolder.getRoot() ); - config = Mockito.mock( ConfigurationVraNg.class ); - vraNgPackageDescriptor = Mockito.mock( VraNgPackageDescriptor.class ); - - store.init( restClient, pkg, config, vraNgPackageDescriptor ); - System.out.println( "==========================================================" ); - System.out.println( "START" ); - System.out.println( "==========================================================" ); - } - - /** - * Cleanup method called after each test. - */ - @AfterEach - void tearDown() { - tempFolder.delete(); - - System.out.println( "==========================================================" ); - System.out.println( "END" ); - System.out.println( "==========================================================" ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenNoItems() { - // GIVEN - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( new ArrayList<>() ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, never() ).getContentSource( anyString() ); - verify( restClient, never() ).getCustomFormByTypeAndSource( anyString(), anyString() ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSource() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder( "catalogItemTwo", "contentSourceNameOne" ); - - VraNgCatalogItem catalogItemOne = builderOne.build(); - VraNgCatalogItem catalogItemTwo = builderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 2 ) ).getContentSource( anyString() ); - verify( restClient, times( 2 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - assertEquals( 2, fsMocks.getTempFolderProjectPath().listFiles().length ); - - String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json", "contentSourceNameOne__catalogItemTwo.json" }; - - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedFiles ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentButFilteringIsEmpty() { - // GIVEN - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder( "catalogItemTwo", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = builderOne.build(); - VraNgCatalogItem catalogItemTwo = builderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( new ArrayList<>() ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, never() ).getCatalogItemsForProject( anyString() ); - verify( restClient, never() ).getProjectId(); - verify( restClient, never() ).getContentSource( anyString() ); - verify( restClient, never() ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 0, tempFolder.getRoot().listFiles().length ); - } - - @Test - void testExportContentWithSomeCatalogItemsWhenItemsArePresentFromOneSource() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add( "contentSourceNameOne__catalogItemOne" ); - - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder( "catalogItemTwo", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = builderOne.build(); - VraNgCatalogItem catalogItemTwo = builderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( mockCatalogItemNames ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 1 ) ).getContentSource( anyString() ); - verify( restClient, times( 1 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - assertEquals( fsMocks.getTempFolderProjectPath().listFiles().length, 1 ); - - String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json" }; - - assertArrayEquals( fsMocks.getTempFolderProjectPath().list(), expectedFiles ); - } - - @Test - void testExportContentWithSomeCatalogItemsWhenItemNameHasIncorrectFormat() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add( "wrongFormat" ); - - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder( "catalogItemTwo", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = builderOne.build(); - VraNgCatalogItem catalogItemTwo = builderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( mockCatalogItemNames ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - - // START TEST - assertThrows( RuntimeException.class, () -> { store.exportContent(); } ); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, never() ).getContentSource( anyString() ); - verify( restClient, never() ).getCustomFormByTypeAndSource( anyString(), anyString() ); - } - - @Test - void testExportContentWithSomeCatalogItemsWhenContentSourceDoesNotExist() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add( "contentSourceNameOne__catalogItemOne" ); - - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder( "catalogItemTwo", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = builderOne.build(); - VraNgCatalogItem catalogItemTwo = builderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( mockCatalogItemNames ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( null ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - - // START TEST - assertThrows( RuntimeException.class, () -> { store.exportContent(); } ); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 1 ) ).getContentSource( anyString() ); - verify( restClient, never() ).getCustomFormByTypeAndSource( anyString(), anyString() ); - } - @Test - void testExportContentWithNoNExistingCatalogItems() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add( "contentSourceNameOne__nonExisting" ); - - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder builderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - CatalogItemMockBuilder builderTwo = new CatalogItemMockBuilder( "catalogItemTwo", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = builderOne.build(); - VraNgCatalogItem catalogItemTwo = builderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( mockCatalogItemNames ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( null ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - // START TEST - assertThrows( IllegalStateException.class, () -> { store.exportContent(); } ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceWithForm() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - - String formIdOne = "formIdCatalogItemOne"; - String formIdTwo = "formIdCatalogItemTwo"; - CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); - CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); - VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); - VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = catalogBuilderOne.setCustomFormId( formIdOne ).build(); - - CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); - VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setCustomFormId( formIdTwo ).build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( - restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) - ).thenReturn( mockedFormOne, mockedFormTwo ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 2 ) ).getContentSource( anyString() ); - verify( restClient, times( 2 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - - String[] expectedFilesAndFolders = { - "contentSourceNameOne__catalogItemOne.json", - "forms", - "contentSourceNameOne__catalogItemTwo.json" - }; - - String[] expectedFormNames = { - "contentSourceNameOne__catalogItemOne.json", - "contentSourceNameOne__catalogItemOne__FormData.json", - "contentSourceNameOne__catalogItemTwo.json", - "contentSourceNameOne__catalogItemTwo__FormData.json" - }; - - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedFilesAndFolders ); - - for ( File file: fsMocks.getTempFolderProjectPath().listFiles() ) { - if ( file.getName().equalsIgnoreCase( "forms" ) ){ - AssertionsHelper.assertFolderContainsFiles( file, expectedFormNames ); - } - } - } - - @SuppressWarnings("unchecked") - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceWithFormAndIcon() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - - String iconIdOne = "iconIdCatalogItemOne"; - String formIdOne = "formIdCatalogItemOne"; - String formIdTwo = "formIdCatalogItemTwo"; - String iconIdTwo = "iconIdCatalogItemTwo"; - Map headers = new HashMap<>(); - headers.put( "Content-Type", "image/png" ); - - ResponseEntity iconOneResponse = GeneralMocks.mockResponseEntity( - "iconBodyOne".getBytes(), - 200, - headers - ); - ResponseEntity iconTwoResponse = GeneralMocks.mockResponseEntity( - "iconBodyTwo".getBytes(), - 200, - headers - ); - - CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); - CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); - VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); - VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); - VraNgCatalogItem catalogItemOne = catalogBuilderOne.setIconId(iconIdOne).setIconExt("png").setCustomFormId(formIdOne).build(); - - CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); - VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setIconId(iconIdTwo).setIconExt("png").setCustomFormId(formIdTwo).build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( restClient.downloadIcon( anyString() ) ).thenReturn( iconOneResponse, iconTwoResponse ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( - restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) - ).thenReturn( mockedFormOne, mockedFormTwo ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 2 ) ).getContentSource( anyString() ); - verify( restClient, times( 2 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - - String[] expectedFilesAndFolders = { - "contentSourceNameOne__catalogItemOne.json", - "forms", - "icons", - "contentSourceNameOne__catalogItemTwo.json" - }; - - String[] expectedFormNames = { - "contentSourceNameOne__catalogItemOne.json", - "contentSourceNameOne__catalogItemOne__FormData.json", - "contentSourceNameOne__catalogItemTwo.json", - "contentSourceNameOne__catalogItemTwo__FormData.json", - }; - - String[] expectedIconNames = { - "contentSourceNameOne__catalogItemOne.png", - "contentSourceNameOne__catalogItemTwo.png" - }; - - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedFilesAndFolders ); - - AssertionsHelper.assertFolderContainsFiles( - fsMocks.findItemByNameInFolder( fsMocks.getTempFolderProjectPath(), "forms" ), - expectedFormNames - ); - - AssertionsHelper.assertFolderContainsFiles( - fsMocks.findItemByNameInFolder( fsMocks.getTempFolderProjectPath(), "icons" ), - expectedIconNames - ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceButIconDoesNotExist() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - - String iconIdOne = "iconIdCatalogItemOne"; - String formIdOne = "formIdCatalogItemOne"; - String formIdTwo = "formIdCatalogItemTwo"; - String iconIdTwo = "iconIdCatalogItemTwo"; - - ResponseEntity iconOneResponse = GeneralMocks.mockResponseEntity( - "iconBodyOne".getBytes(), - 500 - ); - CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); - CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); - VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); - VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); - VraNgCatalogItem catalogItemOne = catalogBuilderOne.setIconId(iconIdOne).setIconExt("png").setCustomFormId(formIdOne).build(); - - CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); - VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setIconId(iconIdTwo).setIconExt("png").setCustomFormId(formIdTwo).build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( restClient.downloadIcon( anyString() ) ).thenReturn( iconOneResponse ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( - restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) - ).thenReturn( mockedFormOne, mockedFormTwo ); - - // START TEST - assertThrows( RuntimeException.class, () -> store.exportContent() ); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 1 ) ).getContentSource( anyString() ); - verify( restClient, times( 1 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromOneSourceWithFormAndSameIcon() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - - String iconId = "iconId"; - String formIdOne = "formIdCatalogItemOne"; - String formIdTwo = "formIdCatalogItemTwo"; - Map headers = new HashMap<>(); - headers.put( "Content-Type", "image/png" ); - - ResponseEntity iconOneResponse = GeneralMocks.mockResponseEntity( - "iconBody".getBytes(), - 200, - headers - ); - CustomFormMockBuilder builderOne = new CustomFormMockBuilder("nameOne"); - CustomFormMockBuilder builderTwo = new CustomFormMockBuilder("nameTwo"); - VraNgCustomForm mockedFormOne = builderOne.setId(formIdOne).build(); - VraNgCustomForm mockedFormTwo = builderTwo.setId(formIdTwo).build(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); - VraNgCatalogItem catalogItemOne = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId(formIdOne).build(); - - CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameOne"); - VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.setIconId(iconId).setIconExt("png").setCustomFormId(formIdTwo).build(); - - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( restClient.downloadIcon( anyString() ) ).thenReturn( iconOneResponse ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( - restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) - ).thenReturn( mockedFormOne, mockedFormTwo ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 2 ) ).getContentSource( anyString() ); - verify( restClient, times( 2 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - - String[] expectedFilesAndFolders = { - "contentSourceNameOne__catalogItemOne.json", - "forms", - "icons", - "contentSourceNameOne__catalogItemTwo.json" - }; - - String[] expectedFormNames = { - "contentSourceNameOne__catalogItemOne.json", - "contentSourceNameOne__catalogItemOne__FormData.json", - "contentSourceNameOne__catalogItemTwo.json", - "contentSourceNameOne__catalogItemTwo__FormData.json" - }; - - String[] expectedIconNames = { - "contentSourceNameOne__catalogItemOne.png", - "contentSourceNameOne__catalogItemTwo.png", - }; - - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedFilesAndFolders ); - - AssertionsHelper.assertFolderContainsFiles( - fsMocks.findItemByNameInFolder( fsMocks.getTempFolderProjectPath(), "forms" ), - expectedFormNames - ); - - AssertionsHelper.assertFolderContainsFiles( - fsMocks.findItemByNameInFolder( fsMocks.getTempFolderProjectPath(), "icons" ), - expectedIconNames - ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromTwoSources() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = catalogBuilderOne.build(); - - CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemTwo", "contentSourceNameTwo"); - VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 2 ) ).getContentSource( anyString() ); - verify( restClient, times( 2 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - assertEquals( 2, fsMocks.getTempFolderProjectPath().listFiles().length ); - - String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json", "contentSourceNameTwo__catalogItemTwo.json" }; - - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedFiles ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromTwoSourcesWithSameName() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = catalogBuilderOne.build(); - - CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameTwo"); - VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 2 ) ).getContentSource( anyString() ); - verify( restClient, times( 2 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - assertEquals( 2, fsMocks.getTempFolderProjectPath().listFiles().length ); - - String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json", "contentSourceNameTwo__catalogItemOne.json" }; - - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedFiles ); - } - - @Test - void testExportContentWithAllCatalogItemsWhenItemsArePresentFromSameSourceWithSameNames() { - // GIVEN - ContentSourceBaseMockBuilder contentSourceBuilder = new ContentSourceBaseMockBuilder(); - - String contentSourceType = VraNgContentSourceType.VRO_WORKFLOW.toString(); - VraNgContentSourceBase contentSource = spy(contentSourceBuilder.setTypeId(contentSourceType).build()); - List mockedCatalogItems = new ArrayList<>(); - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItemOne = catalogBuilderOne.build(); - - CatalogItemMockBuilder catalogBuilderTwo = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); - VraNgCatalogItem catalogItemTwo = catalogBuilderTwo.build(); - - mockedCatalogItems.add( catalogItemOne ); - mockedCatalogItems.add( catalogItemTwo ); - - when( vraNgPackageDescriptor.getCatalogItem() ).thenReturn( null ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getContentSource( CONTENT_SOURCE_ID ) ).thenReturn( contentSource ); - when( contentSource.getType() ).thenReturn( VraNgContentSourceType.VRO_WORKFLOW ); - when( restClient.getCustomFormByTypeAndSource( contentSourceType, CATALOG_ITEM_ID ) ).thenReturn( null ); - - // START TEST - store.exportContent(); - - // VERIFY - verify( vraNgPackageDescriptor, times( 1 ) ).getCatalogItem(); - verify( restClient, times( 1 ) ).getCatalogItemsForProject( anyString() ); - verify( restClient, times( 1 ) ).getProjectId(); - verify( restClient, times( 2 ) ).getContentSource( anyString() ); - verify( restClient, times( 2 ) ).getCustomFormByTypeAndSource( anyString(), anyString() ); - assertEquals( 1, tempFolder.getRoot().listFiles().length ); - assertEquals( fsMocks.getTempFolderProjectPath().listFiles().length, 1 ); - - // Gets overwritten by the last one - String[] expectedFiles = { "contentSourceNameOne__catalogItemOne.json" }; - - AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedFiles ); - } - - @Test - void testImportContentWithNoIconsOrForms() { - // GIVEN - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItem = catalogBuilderOne.build(); - fsMocks.catalogItemFsMocks().addCatalogItem( catalogItem ); - - List mockedCatalogItems = new ArrayList<>(); - mockedCatalogItems.add( catalogItem ); - - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - - // START TEST - store.importContent( tempFolder.getRoot() ); - - // VERIFY - verify( restClient, never() ).importCustomForm( any(), anyString() ); - verify( restClient, never() ).uploadIcon( any() ); - } - - - @Test - void testImportContentWithAnIconAndNoForms() { - // GIVEN - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); - when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); - - String iconId = "iconId"; - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").build(); - - Map headers = new HashMap<>(); - headers.put( "Location", "/some/path/iconId" ); - ResponseEntity response = GeneralMocks.mockResponseEntity( "", 201, headers ); - - List mockedCatalogItems = new ArrayList<>(); - mockedCatalogItems.add( catalogItem ); - - fsMocks.catalogItemFsMocks().addCatalogItem( catalogItem ); - fsMocks.catalogItemFsMocks().addCatalogItemIcon( catalogItem ); - when( restClient.getCatalogItemByBlueprintName( anyString() ) ).thenReturn( catalogItem ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.uploadIcon( any() ) ).thenReturn( response ); - - // START TEST - store.importContent( tempFolder.getRoot() ); - - // VERIFY - verify( restClient, never() ).importCustomForm( any(), anyString() ); - verify( restClient, times( 1 ) ).uploadIcon( any() ); - } - - @Test - void testImportContentWithAnIconAndForms() { - // GIVEN - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); - when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); - - String iconId = "iconId"; - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId").build(); - - Map headers = new HashMap<>(); - headers.put( "Location", "/some/path/iconId" ); - ResponseEntity response = GeneralMocks.mockResponseEntity( "", 201, headers ); - - List mockedCatalogItems = new ArrayList<>(); - mockedCatalogItems.add( catalogItem ); - - fsMocks.catalogItemFsMocks().addCatalogItem( catalogItem ); - fsMocks.catalogItemFsMocks().addCatalogItemIcon( catalogItem ); - fsMocks.catalogItemFsMocks().addCatalogItemForm( catalogItem ); - when( restClient.getCatalogItemByBlueprintName( anyString() ) ).thenReturn( catalogItem ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.uploadIcon( any() ) ).thenReturn( response ); - doNothing().when( restClient ).importCustomForm( any(), anyString() ); - - // START TEST - store.importContent( tempFolder.getRoot() ); - - // VERIFY - verify( restClient, times( 1 ) ).importCustomForm( any(), anyString() ); - verify( restClient, times( 1 ) ).uploadIcon( any() ); - } - - @Test - void testImportContentWithAnIconAndFormsWithDotInName() { - // GIVEN - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add("contentSource. NameOne__catalogItem One.x"); - when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); - - String iconId = "iconId"; - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItem One.x", "contentSource. NameOne" ); - VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId").build(); - - Map headers = new HashMap<>(); - headers.put( "Location", "/some/path/iconId" ); - ResponseEntity response = GeneralMocks.mockResponseEntity( "", 201, headers ); - - List mockedCatalogItems = new ArrayList<>(); - mockedCatalogItems.add( catalogItem ); - - fsMocks.catalogItemFsMocks().addCatalogItem( catalogItem ); - fsMocks.catalogItemFsMocks().addCatalogItemIcon( catalogItem ); - fsMocks.catalogItemFsMocks().addCatalogItemForm( catalogItem ); - when( restClient.getCatalogItemByBlueprintName( anyString() ) ).thenReturn( catalogItem ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - when( restClient.uploadIcon( any() ) ).thenReturn( response ); - doNothing().when( restClient ).importCustomForm( any(), anyString() ); - - // START TEST - store.importContent( tempFolder.getRoot() ); - - // VERIFY - verify( restClient, times( 1 ) ).importCustomForm( any(), anyString() ); - verify( restClient, times( 1 ) ).uploadIcon( any() ); - } - - @Test - void testImportContentWithoutAnIconAndWithForms() { - // GIVEN - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); - when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); - - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder( "catalogItemOne", "contentSourceNameOne" ); - VraNgCatalogItem catalogItem = catalogBuilderOne.setCustomFormId("formId").build(); - - List mockedCatalogItems = new ArrayList<>(); - mockedCatalogItems.add( catalogItem ); - - fsMocks.catalogItemFsMocks().addCatalogItem( catalogItem ); - fsMocks.catalogItemFsMocks().addCatalogItemForm( catalogItem ); - when( restClient.getCatalogItemByBlueprintName( anyString() ) ).thenReturn( catalogItem ); - when( restClient.getProjectId() ).thenReturn( PROJECT_ID ); - when( restClient.getCatalogItemsForProject( PROJECT_ID ) ).thenReturn( mockedCatalogItems ); - doNothing().when( restClient ).importCustomForm( any(), anyString() ); - - // START TEST - store.importContent( tempFolder.getRoot() ); - - // VERIFY - verify( restClient, times( 1 ) ).importCustomForm( any(), anyString() ); - } - - @Test - void testImportContentWithAnIconAndFormsWithVraAbove812() { - // GIVEN - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); - when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); - - String iconId = "iconId"; - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); - VraNgCatalogItemType bpCatalogItem = new VraNgCatalogItemType(VraNgContentSourceType.BLUEPRINT, null, null); - VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId").setType(bpCatalogItem).build(); - - Map headers = new HashMap<>(); - headers.put("Location", "/some/path/iconId"); - ResponseEntity response = GeneralMocks.mockResponseEntity("", 201, headers); - - List mockedCatalogItems = new ArrayList<>(); - mockedCatalogItems.add(catalogItem); - - fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); - fsMocks.catalogItemFsMocks().addCatalogItemIcon(catalogItem); - fsMocks.catalogItemFsMocks().addCatalogItemForm(catalogItem); - when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); - when(restClient.getProjectId()).thenReturn(PROJECT_ID); - when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); - when(restClient.uploadIcon(any())).thenReturn(response); - when(restClient.getIsVraAbove812()).thenReturn(true); - when(restClient.getCatalogItemVersions(catalogItem.getId())).thenReturn(new JsonArray()); - - doNothing().when(restClient).importCustomForm(any(), anyString()); - VraNgCatalogItemStore vra812Store = (VraNgCatalogItemStore812) new VraNgTypeStoreFactory(restClient, pkg, config, vraNgPackageDescriptor) - .getStoreForType(VraNgPackageContent.ContentType.CATALOG_ITEM); - - // START TEST - vra812Store.importContent(tempFolder.getRoot()); - - // VERIFY - verify(restClient, times(1)).importCustomForm(any(), anyString()); - verify(restClient, times(1)).uploadIcon(any()); - } - - @Test - void testImportContentWithAnIconAndFormsWithVraBelow812() { - // GIVEN - List mockCatalogItemNames = new ArrayList<>(); - mockCatalogItemNames.add("contentSourceNameOne__catalogItemOne"); - when(vraNgPackageDescriptor.getCatalogItem()).thenReturn(mockCatalogItemNames); - - String iconId = "iconId"; - CatalogItemMockBuilder catalogBuilderOne = new CatalogItemMockBuilder("catalogItemOne", "contentSourceNameOne"); - VraNgCatalogItem catalogItem = catalogBuilderOne.setIconId(iconId).setIconExt("png").setCustomFormId("formId").build(); - - Map headers = new HashMap<>(); - headers.put("Location", "/some/path/iconId"); - ResponseEntity response = GeneralMocks.mockResponseEntity("", 201, headers); - - List mockedCatalogItems = new ArrayList<>(); - mockedCatalogItems.add(catalogItem); - - fsMocks.catalogItemFsMocks().addCatalogItem(catalogItem); - fsMocks.catalogItemFsMocks().addCatalogItemIcon(catalogItem); - fsMocks.catalogItemFsMocks().addCatalogItemForm(catalogItem); - when(restClient.getCatalogItemByBlueprintName(anyString())).thenReturn(catalogItem); - when(restClient.getProjectId()).thenReturn(PROJECT_ID); - when(restClient.getCatalogItemsForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); - when(restClient.uploadIcon(any())).thenReturn(response); - when(restClient.getIsVraAbove812()).thenReturn(false); - - doNothing().when(restClient).importCustomForm(any(), anyString()); - - // START TEST - store.importContent(tempFolder.getRoot()); - - // VERIFY - verify(restClient, times(1)).importCustomForm(any(), anyString()); - verify(restClient, times(1)).uploadIcon(any()); - } -} diff --git a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgContentSourceStoreTest.java b/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgContentSourceStoreTest.java deleted file mode 100644 index bbff3702d..000000000 --- a/common/artifact-manager/src/test/java/com/vmware/pscoe/iac/artifact/aria/store/VraNgContentSourceStoreTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * #%L - * artifact-manager - * %% - * Copyright (C) 2023 VMware - * %% - * Build Tools for VMware Aria - * Copyright 2023 VMware, Inc. - * - * This product is licensed to you under the BSD-2 license (the "License"). You may not use this product except in compliance with the BSD-2 License. - * - * This product may include a number of subcomponents with separate copyright notices and license terms. Your use of these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE file. - * #L% - */ -package com.vmware.pscoe.iac.artifact.aria.automation.store; - -import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; -import com.vmware.pscoe.iac.artifact.helpers.AssertionsHelper; -import com.vmware.pscoe.iac.artifact.helpers.FsMocks; -import com.vmware.pscoe.iac.artifact.helpers.stubs.ContentSourceBaseMockBuilder; -import com.vmware.pscoe.iac.artifact.model.Package; -import com.vmware.pscoe.iac.artifact.model.PackageFactory; -import com.vmware.pscoe.iac.artifact.model.PackageType; -import com.vmware.pscoe.iac.artifact.aria.automation.models.*; -import com.vmware.pscoe.iac.artifact.rest.RestClient; -import com.vmware.pscoe.iac.artifact.aria.automation.rest.RestClientVraNg; - -import org.junit.Rule; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.rules.TemporaryFolder; -import org.mockito.Mockito; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.Mockito.*; - -public class VraNgContentSourceStoreTest{ - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - protected static String PROJECT_ID = "projectId"; - protected VraNgContentSourceStore store; - protected RestClientVraNg restClient; - protected Package pkg; - protected ConfigurationVraNg config; - protected VraNgPackageDescriptor vraNgPackageDescriptor; - protected FsMocks fsMocks; - - @BeforeEach - void init() { - try { - tempFolder.create(); - } - catch ( IOException e ) { - throw new RuntimeException( "Could not create a temp folder" ); - } - - fsMocks = new FsMocks( tempFolder.getRoot() ); - store = new VraNgContentSourceStore(); - restClient = Mockito.mock( RestClientVraNg.class ); - pkg = PackageFactory.getInstance( PackageType.VRANG, tempFolder.getRoot() ); - config = Mockito.mock( ConfigurationVraNg.class ); - vraNgPackageDescriptor = Mockito.mock( VraNgPackageDescriptor.class ); - - store.init( restClient, pkg, config, vraNgPackageDescriptor ); - System.out.println( "==========================================================" ); - System.out.println( "START" ); - System.out.println( "==========================================================" ); - } - - @AfterEach - void tearDown() { - tempFolder.delete(); - - System.out.println( "==========================================================" ); - System.out.println( "END" ); - System.out.println( "==========================================================" ); - } - - - @Test - void testExportContentWithNoContentSource() { - //GIVEN - ArrayList data = new ArrayList<>(); - data.add("nothing"); - - List mockedCatalogItems = new ArrayList<>(); - ContentSourceBaseMockBuilder builderOne = new ContentSourceBaseMockBuilder(); - VraNgContentSourceBase contentSourceOne = builderOne.setName("thing1").build(); - ContentSourceBaseMockBuilder builderTwo = new ContentSourceBaseMockBuilder(); - VraNgContentSourceBase contentSourceTwo = builderOne.setName("thing2").build(); - mockedCatalogItems.add( contentSourceOne ); - mockedCatalogItems.add( contentSourceTwo ); - - when( vraNgPackageDescriptor.getContentSource()).thenReturn(data); - when(restClient.getContentSourcesForProject(PROJECT_ID)).thenReturn(mockedCatalogItems); - //TEST - assertThrows(IllegalStateException.class, () -> store.exportContent()); - - //VERIFY - verify( restClient, never() ).getContentSourcesForProject(anyString()); - - assertEquals( 0, tempFolder.getRoot().listFiles().length ); - } - - @Test - void testExportContentThatDoesNotExistOnTheServer() { - //GIVEN - when( vraNgPackageDescriptor.getContentSource()).thenReturn(new ArrayList()); - - //TEST - store.exportContent(); - - //VERIFY - verify( restClient, never() ).getContentSourcesForProject(anyString()); - - assertEquals( 0, tempFolder.getRoot().listFiles().length ); - } - - @Test - void testExportContentWithNullValue() { - - when( vraNgPackageDescriptor.getContentSource()).thenReturn(null); - //TEST - assertDoesNotThrow(() -> store.exportContent()); - - } - - //TODO not easy to implement the test because the VraNgContentSourceBase is too complext to be mocked. VraNgContentSourceBase is casted dynamically to other classes - // @Test - // void testExportContentWithAllContentSources() { - // //GIVEN - // when( restClient.getProjectId()).thenReturn("mockedProjectId"); - // VraNgContentSourceStore store1 = new VraNgContentSourceStore(); - // store1.init( restClient, pkg, config, vraNgPackageDescriptor ); - - // List contentSources = new ArrayList<>(); - // ContentSourceBaseMockBuilder builder = new ContentSourceBaseMockBuilder(); - - // contentSources.add( builder.setName("mockContentSource1").build()); - - // when( vraNgPackageDescriptor.getContentSource()).thenReturn(null); - // when( restClient.getContentSourcesForProject("mockedProjectId")).thenReturn( contentSources ); - - // //TEST - // store1.exportContent(); - - // String[] expectedContentSources = { "mockContentSource1.json" }; - - // // VERIFY - // verify(restClient, times(1)).getContentSourcesForProject("mockedProjectId"); - // AssertionsHelper.assertFolderContainsFiles( fsMocks.getTempFolderProjectPath(), expectedContentSources ); - // } - - // @Test - // void testExportContentWithSpecificContentSources() {} - - -} diff --git a/docs/versions/latest/Release.md b/docs/versions/latest/Release.md index ad31c6df2..74baff259 100644 --- a/docs/versions/latest/Release.md +++ b/docs/versions/latest/Release.md @@ -122,7 +122,11 @@ The question is updated: ### *Moved Aria Automation components to own folder* -This is jut an internal restructuring effort, no functionality was changed. +This is just an internal restructuring effort, no functionality was changed. + +### *Moved Aria Operations components to own folder* + +This is just an internal restructuring effort, no functionality was changed. ## Upgrade procedure diff --git a/maven/plugins/common/src/main/java/com/vmware/pscoe/maven/plugins/AbstractIacMojo.java b/maven/plugins/common/src/main/java/com/vmware/pscoe/maven/plugins/AbstractIacMojo.java index 2cae76698..25cb10f6b 100644 --- a/maven/plugins/common/src/main/java/com/vmware/pscoe/maven/plugins/AbstractIacMojo.java +++ b/maven/plugins/common/src/main/java/com/vmware/pscoe/maven/plugins/AbstractIacMojo.java @@ -16,6 +16,7 @@ import com.vmware.pscoe.iac.artifact.configuration.*; import com.vmware.pscoe.iac.artifact.aria.automation.configuration.ConfigurationVraNg; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; import com.vmware.pscoe.iac.artifact.model.PackageType; import com.vmware.pscoe.iac.artifact.rest.RestClientFactory; import com.vmware.pscoe.iac.artifact.rest.RestClientVro; diff --git a/maven/plugins/vrops/src/main/java/com/vmware/pscoe/maven/plugins/PackageMojo.java b/maven/plugins/vrops/src/main/java/com/vmware/pscoe/maven/plugins/PackageMojo.java index a3810001c..efb8e6dcd 100644 --- a/maven/plugins/vrops/src/main/java/com/vmware/pscoe/maven/plugins/PackageMojo.java +++ b/maven/plugins/vrops/src/main/java/com/vmware/pscoe/maven/plugins/PackageMojo.java @@ -34,12 +34,12 @@ import org.apache.maven.project.MavenProject; import com.vmware.pscoe.iac.artifact.PackageManager; -import com.vmware.pscoe.iac.artifact.VropsPackageStore; +import com.vmware.pscoe.iac.artifact.aria.operations.store.VropsPackageStore; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationException; import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType; -import com.vmware.pscoe.iac.artifact.model.vrops.VropsPackageDescriptor; +import com.vmware.pscoe.iac.artifact.aria.operations.store.models.VropsPackageDescriptor; import edu.emory.mathcs.backport.java.util.Arrays; diff --git a/package-installer/src/main/java/com/vmware/pscoe/iac/installer/Installer.java b/package-installer/src/main/java/com/vmware/pscoe/iac/installer/Installer.java index 091ed176e..f6b98b562 100644 --- a/package-installer/src/main/java/com/vmware/pscoe/iac/installer/Installer.java +++ b/package-installer/src/main/java/com/vmware/pscoe/iac/installer/Installer.java @@ -63,7 +63,7 @@ import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrli; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVro; import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVroNg; -import com.vmware.pscoe.iac.artifact.configuration.ConfigurationVrops; +import com.vmware.pscoe.iac.artifact.aria.operations.configuration.ConfigurationVrops; import com.vmware.pscoe.iac.artifact.model.Package; import com.vmware.pscoe.iac.artifact.model.PackageFactory; import com.vmware.pscoe.iac.artifact.model.PackageType;