Search in sources :

Example 11 with BlackDuckProperties

use of com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties in project hub-alert by blackducksoftware.

the class BlackDuckGlobalFieldModelTestAction method testConfig.

@Override
public MessageResult testConfig(String configId, FieldModel fieldModel, FieldUtility registeredFieldValues) throws IntegrationException {
    Slf4jIntLogger intLogger = new Slf4jIntLogger(logger);
    String apiToken = registeredFieldValues.getStringOrEmpty(BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY);
    String url = registeredFieldValues.getStringOrEmpty(BlackDuckDescriptor.KEY_BLACKDUCK_URL);
    String timeout = registeredFieldValues.getStringOrEmpty(BlackDuckDescriptor.KEY_BLACKDUCK_TIMEOUT);
    Long parsedConfigurationId = ProviderProperties.UNKNOWN_CONFIG_ID;
    if (StringUtils.isNotBlank(configId)) {
        try {
            parsedConfigurationId = Long.valueOf(configId);
        } catch (NumberFormatException ex) {
            throw new AlertException("Configuration id not valid.");
        }
    }
    BlackDuckProperties blackDuckProperties = blackDuckPropertiesFactory.createProperties(parsedConfigurationId, registeredFieldValues);
    BlackDuckServerConfigBuilder blackDuckServerConfigBuilder = blackDuckProperties.createServerConfigBuilderWithoutAuthentication(intLogger, NumberUtils.toInt(timeout, 300));
    blackDuckServerConfigBuilder.setApiToken(apiToken);
    blackDuckServerConfigBuilder.setUrl(url);
    validateBlackDuckConfiguration(blackDuckServerConfigBuilder);
    BlackDuckServerConfig blackDuckServerConfig = blackDuckServerConfigBuilder.build();
    ConnectionResult connectionResult = blackDuckServerConfig.attemptConnection(intLogger);
    if (connectionResult.isFailure()) {
        String failureMessage = connectionResult.getFailureMessage().orElse("");
        Exception errorException = connectionResult.getException().orElse(null);
        if (RestConstants.UNAUTHORIZED_401 == connectionResult.getHttpStatusCode()) {
            throw AlertFieldException.singleFieldError(String.format("Invalid credential(s) for: %s. %s", url, failureMessage), BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY, "This API Key isn't valid, try a different one.");
        } else if (connectionResult.getHttpStatusCode() > 0) {
            // TODO why are we throwing a non-alert exception?
            HttpUrl connectionUrl = new HttpUrl(url);
            throw new IntegrationRestException(HttpMethod.GET, connectionUrl, connectionResult.getHttpStatusCode(), String.format("Could not connect to: %s", url), failureMessage, errorException);
        }
        throw new AlertException(String.format("Could not connect to: %s. %s", url, failureMessage), errorException);
    }
    BlackDuckApiTokenValidator blackDuckAPITokenValidator = new BlackDuckApiTokenValidator(blackDuckProperties);
    if (!blackDuckAPITokenValidator.isApiTokenValid()) {
        throw AlertFieldException.singleFieldError(BlackDuckDescriptor.KEY_BLACKDUCK_API_KEY, "User permission failed. Cannot read notifications from Black Duck.");
    }
    return new MessageResult("Successfully connected to BlackDuck server.");
}
Also used : IntegrationRestException(com.synopsys.integration.rest.exception.IntegrationRestException) BlackDuckServerConfigBuilder(com.synopsys.integration.blackduck.configuration.BlackDuckServerConfigBuilder) BlackDuckProperties(com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties) MessageResult(com.synopsys.integration.alert.common.message.model.MessageResult) AlertFieldException(com.synopsys.integration.alert.common.exception.AlertFieldException) IntegrationException(com.synopsys.integration.exception.IntegrationException) AlertException(com.synopsys.integration.alert.api.common.model.exception.AlertException) IntegrationRestException(com.synopsys.integration.rest.exception.IntegrationRestException) HttpUrl(com.synopsys.integration.rest.HttpUrl) BlackDuckServerConfig(com.synopsys.integration.blackduck.configuration.BlackDuckServerConfig) Slf4jIntLogger(com.synopsys.integration.log.Slf4jIntLogger) ConnectionResult(com.synopsys.integration.rest.client.ConnectionResult) AlertException(com.synopsys.integration.alert.api.common.model.exception.AlertException) BlackDuckApiTokenValidator(com.synopsys.integration.alert.provider.blackduck.validator.BlackDuckApiTokenValidator)

Example 12 with BlackDuckProperties

use of com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties in project hub-alert by blackducksoftware.

the class BlackDuckDataSyncTask method runProviderTask.

@Override
public void runProviderTask() {
    try {
        BlackDuckProperties providerProperties = getProviderProperties();
        Optional<BlackDuckHttpClient> optionalBlackDuckHttpClient = providerProperties.createBlackDuckHttpClientAndLogErrors(logger);
        if (optionalBlackDuckHttpClient.isPresent()) {
            BlackDuckHttpClient blackDuckHttpClient = optionalBlackDuckHttpClient.get();
            BlackDuckServicesFactory blackDuckServicesFactory = providerProperties.createBlackDuckServicesFactory(blackDuckHttpClient, new Slf4jIntLogger(logger));
            ProjectUsersService projectUsersService = blackDuckServicesFactory.createProjectUsersService();
            BlackDuckApiClient blackDuckApiClient = blackDuckServicesFactory.getBlackDuckApiClient();
            ApiDiscovery apiDiscovery = blackDuckServicesFactory.getApiDiscovery();
            List<ProjectView> projectViews = blackDuckApiClient.getAllResponses(apiDiscovery.metaProjectsLink());
            Map<ProjectView, ProviderProject> blackDuckToAlertProjects = mapBlackDuckProjectsToAlertProjects(projectViews, blackDuckApiClient);
            Map<ProviderProject, Set<String>> projectToEmailAddresses = getEmailsPerProject(blackDuckToAlertProjects, projectUsersService);
            Set<String> allRelevantBlackDuckUsers = getAllActiveBlackDuckUserEmailAddresses(blackDuckApiClient, apiDiscovery);
            blackDuckDataAccessor.updateProjectAndUserData(providerProperties.getConfigId(), projectToEmailAddresses, allRelevantBlackDuckUsers);
        } else {
            logger.error("Missing BlackDuck global configuration.");
        }
    } catch (IntegrationException | AlertRuntimeException e) {
        logger.error(String.format("Could not retrieve the current data from the BlackDuck server: %s", e.getMessage()), e);
    }
}
Also used : ProjectUsersService(com.synopsys.integration.blackduck.service.dataservice.ProjectUsersService) BlackDuckProperties(com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties) Set(java.util.Set) IntegrationException(com.synopsys.integration.exception.IntegrationException) BlackDuckHttpClient(com.synopsys.integration.blackduck.http.client.BlackDuckHttpClient) BlackDuckApiClient(com.synopsys.integration.blackduck.service.BlackDuckApiClient) BlackDuckServicesFactory(com.synopsys.integration.blackduck.service.BlackDuckServicesFactory) Slf4jIntLogger(com.synopsys.integration.log.Slf4jIntLogger) ApiDiscovery(com.synopsys.integration.blackduck.api.generated.discovery.ApiDiscovery) AlertRuntimeException(com.synopsys.integration.alert.api.common.model.exception.AlertRuntimeException) ProjectView(com.synopsys.integration.blackduck.api.generated.view.ProjectView) ProviderProject(com.synopsys.integration.alert.common.persistence.model.ProviderProject)

Example 13 with BlackDuckProperties

use of com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties in project hub-alert by blackducksoftware.

the class PolicyNotificationFilterCustomFunctionAction method createBlackDuckServicesFactory.

private Optional<BlackDuckServicesFactory> createBlackDuckServicesFactory(FieldModel fieldModel) throws IntegrationException {
    Optional<BlackDuckProperties> optionalBlackDuckProperties = createBlackDuckProperties(fieldModel);
    if (optionalBlackDuckProperties.isPresent()) {
        BlackDuckProperties blackDuckProperties = optionalBlackDuckProperties.get();
        BlackDuckHttpClient blackDuckHttpClient = blackDuckProperties.createBlackDuckHttpClient(logger);
        BlackDuckServicesFactory blackDuckServicesFactory = blackDuckProperties.createBlackDuckServicesFactory(blackDuckHttpClient, logger);
        return Optional.of(blackDuckServicesFactory);
    }
    return Optional.empty();
}
Also used : BlackDuckProperties(com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties) BlackDuckHttpClient(com.synopsys.integration.blackduck.http.client.BlackDuckHttpClient) BlackDuckServicesFactory(com.synopsys.integration.blackduck.service.BlackDuckServicesFactory)

Example 14 with BlackDuckProperties

use of com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties in project hub-alert by blackducksoftware.

the class BlackDuckGlobalApiActionTest method runApiActionTest.

private void runApiActionTest(ThrowingBiFunction<BlackDuckGlobalApiAction, FieldModel, FieldModel, AlertException> apiAction) throws AlertException {
    TaskManager taskManager = new TaskManager();
    BlackDuckProperties properties = Mockito.mock(BlackDuckProperties.class);
    Mockito.when(properties.isConfigEnabled()).thenReturn(true);
    FieldModel fieldModel = Mockito.mock(FieldModel.class);
    Mockito.when(fieldModel.getId()).thenReturn("1");
    Mockito.when(fieldModel.getFieldValue(Mockito.eq(ProviderDescriptor.KEY_PROVIDER_CONFIG_ENABLED))).thenReturn(Optional.of("true"));
    String providerConfigName = "Test Provider Config";
    Mockito.when(fieldModel.getFieldValue(Mockito.eq(ProviderDescriptor.KEY_PROVIDER_CONFIG_NAME))).thenReturn(Optional.of(providerConfigName));
    BlackDuckAccumulator blackDuckAccumulator = Mockito.mock(BlackDuckAccumulator.class);
    Mockito.when(blackDuckAccumulator.getTaskName()).thenReturn("accumulator-task");
    Mockito.when(blackDuckAccumulator.getFormatedNextRunTime()).thenReturn(Optional.of("SOON"));
    BlackDuckDataSyncTask blackDuckDataSyncTask = Mockito.mock(BlackDuckDataSyncTask.class);
    Mockito.when(blackDuckDataSyncTask.getTaskName()).thenReturn("data-sync-task");
    Mockito.when(blackDuckDataSyncTask.getFormatedNextRunTime()).thenReturn(Optional.of("SOON"));
    ConfigurationModel configurationModel = Mockito.mock(ConfigurationModel.class);
    Long providerConfigId = -1L;
    Mockito.when(configurationModel.getConfigurationId()).thenReturn(providerConfigId);
    Mockito.when(configurationModel.getDescriptorId()).thenReturn(providerConfigId);
    ConfigurationFieldModel configurationFieldModel = ConfigurationFieldModel.create(ProviderDescriptor.KEY_PROVIDER_CONFIG_ENABLED);
    configurationFieldModel.setFieldValue("true");
    Mockito.when(configurationModel.getField(ProviderDescriptor.KEY_PROVIDER_CONFIG_ENABLED)).thenReturn(Optional.of(configurationFieldModel));
    ConfigurationModelConfigurationAccessor configurationModelConfigurationAccessor = Mockito.mock(ConfigurationModelConfigurationAccessor.class);
    Mockito.when(configurationModelConfigurationAccessor.getProviderConfigurationByName(Mockito.anyString())).thenReturn(Optional.of(configurationModel));
    Mockito.when(configurationModelConfigurationAccessor.getConfigurationsByDescriptorKeyAndContext(Mockito.any(BlackDuckProviderKey.class), Mockito.eq(ConfigContextEnum.DISTRIBUTION))).thenReturn(List.of());
    BlackDuckProviderKey blackDuckProviderKey = new BlackDuckProviderKey();
    StatefulProvider statefulProvider = Mockito.mock(StatefulProvider.class);
    BlackDuckProvider blackDuckProvider = Mockito.mock(BlackDuckProvider.class);
    Mockito.when(blackDuckProvider.validate(configurationModel)).thenReturn(true);
    Mockito.when(blackDuckProvider.createStatefulProvider(configurationModel)).thenReturn(statefulProvider);
    Mockito.when(statefulProvider.getKey()).thenReturn(blackDuckProviderKey);
    Mockito.when(statefulProvider.getConfigId()).thenReturn(providerConfigId);
    Mockito.when(statefulProvider.isConfigEnabled()).thenReturn(true);
    Mockito.when(statefulProvider.getConfigName()).thenReturn(providerConfigName);
    Mockito.when(statefulProvider.getProperties()).thenReturn(properties);
    Mockito.when(statefulProvider.getTasks()).thenReturn(List.of(blackDuckAccumulator, blackDuckDataSyncTask));
    BlackDuckPropertiesFactory propertiesFactory = Mockito.mock(BlackDuckPropertiesFactory.class);
    Mockito.when(propertiesFactory.createProperties((ConfigurationModel) Mockito.any())).thenReturn(properties);
    ProviderDataAccessor providerDataAccessor = Mockito.mock(ProviderDataAccessor.class);
    ConfigurationFieldModelConverter fieldModelConverter = Mockito.mock(ConfigurationFieldModelConverter.class);
    Mockito.when(fieldModelConverter.convertToConfigurationModel(Mockito.any())).thenReturn(configurationModel);
    BlackDuckCacheHttpClientCache blackDuckCacheHttpClientCache = Mockito.mock(BlackDuckCacheHttpClientCache.class);
    ProviderSchedulingManager providerLifecycleManager = new ProviderSchedulingManager(List.of(blackDuckProvider), taskManager, null);
    BlackDuckGlobalApiAction blackDuckGlobalApiAction = new BlackDuckGlobalApiAction(blackDuckProvider, providerLifecycleManager, providerDataAccessor, configurationModelConfigurationAccessor, blackDuckCacheHttpClientCache);
    Optional<String> initialAccumulatorNextRunTime = taskManager.getNextRunTime(blackDuckAccumulator.getTaskName());
    Optional<String> initialSyncNextRunTime = taskManager.getNextRunTime(blackDuckDataSyncTask.getTaskName());
    assertTrue(initialAccumulatorNextRunTime.isEmpty());
    assertTrue(initialSyncNextRunTime.isEmpty());
    apiAction.apply(blackDuckGlobalApiAction, fieldModel);
    Optional<String> accumulatorNextRunTime = taskManager.getNextRunTime(blackDuckAccumulator.getTaskName());
    Optional<String> syncNextRunTime = taskManager.getNextRunTime(blackDuckDataSyncTask.getTaskName());
    assertTrue(accumulatorNextRunTime.isPresent(), "The accumulator task next run time was not present");
    assertTrue(syncNextRunTime.isPresent(), "The sync task next run time was not present");
}
Also used : ConfigurationModel(com.synopsys.integration.alert.common.persistence.model.ConfigurationModel) BlackDuckProviderKey(com.synopsys.integration.alert.descriptor.api.BlackDuckProviderKey) BlackDuckProperties(com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties) BlackDuckCacheHttpClientCache(com.synopsys.integration.alert.provider.blackduck.BlackDuckCacheHttpClientCache) ProviderSchedulingManager(com.synopsys.integration.alert.api.provider.lifecycle.ProviderSchedulingManager) BlackDuckPropertiesFactory(com.synopsys.integration.alert.provider.blackduck.factory.BlackDuckPropertiesFactory) BlackDuckDataSyncTask(com.synopsys.integration.alert.provider.blackduck.task.BlackDuckDataSyncTask) ConfigurationModelConfigurationAccessor(com.synopsys.integration.alert.common.persistence.accessor.ConfigurationModelConfigurationAccessor) ConfigurationFieldModelConverter(com.synopsys.integration.alert.common.persistence.util.ConfigurationFieldModelConverter) BlackDuckAccumulator(com.synopsys.integration.alert.provider.blackduck.task.accumulator.BlackDuckAccumulator) TaskManager(com.synopsys.integration.alert.api.task.TaskManager) ConfigurationFieldModel(com.synopsys.integration.alert.common.persistence.model.ConfigurationFieldModel) ProviderDataAccessor(com.synopsys.integration.alert.common.persistence.accessor.ProviderDataAccessor) ConfigurationFieldModel(com.synopsys.integration.alert.common.persistence.model.ConfigurationFieldModel) FieldModel(com.synopsys.integration.alert.common.rest.model.FieldModel) BlackDuckProvider(com.synopsys.integration.alert.provider.blackduck.BlackDuckProvider) StatefulProvider(com.synopsys.integration.alert.api.provider.state.StatefulProvider)

Example 15 with BlackDuckProperties

use of com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties in project hub-alert by blackducksoftware.

the class BlackDuckProjectSyncTaskTest method testRun.

@Test
public void testRun() throws Exception {
    MockProviderDataAccessor providerDataAccessor = new MockProviderDataAccessor();
    ApiDiscovery apiDiscovery = new ApiDiscovery(new HttpUrl("https://someblackduckserver"));
    BlackDuckApiClient blackDuckApiClient = Mockito.mock(BlackDuckApiClient.class);
    ProjectUsersService projectUsersService = Mockito.mock(ProjectUsersService.class);
    BlackDuckServicesFactory blackDuckServicesFactory = Mockito.mock(BlackDuckServicesFactory.class);
    Mockito.when(blackDuckServicesFactory.getBlackDuckApiClient()).thenReturn(blackDuckApiClient);
    Mockito.when(blackDuckServicesFactory.createProjectUsersService()).thenReturn(projectUsersService);
    Mockito.when(blackDuckServicesFactory.getApiDiscovery()).thenReturn(apiDiscovery);
    Long providerConfigId = 1000L;
    BlackDuckProperties blackDuckProperties = Mockito.mock(BlackDuckProperties.class);
    Mockito.when(blackDuckProperties.getConfigId()).thenReturn(providerConfigId);
    Mockito.when(blackDuckProperties.createBlackDuckHttpClientAndLogErrors(Mockito.any())).thenReturn(Optional.of(Mockito.mock(BlackDuckHttpClient.class)));
    Mockito.when(blackDuckProperties.createBlackDuckServicesFactory(Mockito.any(), Mockito.any())).thenReturn(blackDuckServicesFactory);
    ProjectView projectView = createProjectView("project", "description1", "https://projectUrl1");
    ProjectView projectView2 = createProjectView("project2", "description2", "https://projectUrl2");
    ProjectView projectView3 = createProjectView("project3", "description3", "https://projectUrl3");
    Mockito.when(blackDuckApiClient.getAllResponses(Mockito.eq(apiDiscovery.metaProjectsLink()))).thenReturn(List.of(projectView, projectView2, projectView3));
    Mockito.doReturn(null).when(blackDuckApiClient).getResponse(Mockito.any(BlackDuckRequest.class));
    String email1 = "user1@email.com";
    String email2 = "user2@email.com";
    String email3 = "user3@email.com";
    String email4 = "user4@email.com";
    UserView user1 = createUserView(email1, true);
    UserView user2 = createUserView(email2, true);
    UserView user3 = createUserView(email3, true);
    UserView user4 = createUserView(email4, true);
    Mockito.when(blackDuckApiClient.getAllResponses(Mockito.eq(apiDiscovery.metaUsersLink()))).thenReturn(List.of(user1, user2, user3, user4));
    Mockito.when(projectUsersService.getAllActiveUsersForProject(ArgumentMatchers.same(projectView))).thenReturn(new HashSet<>(List.of(user2, user4)));
    Mockito.when(projectUsersService.getAllActiveUsersForProject(ArgumentMatchers.same(projectView2))).thenReturn(new HashSet<>(List.of(user3)));
    Mockito.when(projectUsersService.getAllActiveUsersForProject(ArgumentMatchers.same(projectView3))).thenReturn(new HashSet<>(List.of(user1, user2, user3)));
    Mockito.doNothing().when(projectUsersService).addUserToProject(Mockito.any(), Mockito.any(UserView.class));
    BlackDuckDataSyncTask projectSyncTask = new BlackDuckDataSyncTask(new BlackDuckProviderKey(), null, providerDataAccessor, blackDuckProperties);
    projectSyncTask.run();
    assertEquals(3, providerDataAccessor.getProjectsByProviderConfigId(providerConfigId).size());
    Mockito.when(blackDuckApiClient.getAllResponses(Mockito.eq(apiDiscovery.metaProjectsLink()))).thenReturn(List.of(projectView, projectView2));
    Mockito.when(projectUsersService.getAllActiveUsersForProject(ArgumentMatchers.same(projectView))).thenReturn(new HashSet<>(List.of(user2, user4)));
    Mockito.when(projectUsersService.getAllActiveUsersForProject(ArgumentMatchers.same(projectView2))).thenReturn(new HashSet<>(List.of(user3)));
    Mockito.when(blackDuckApiClient.getAllResponses(ArgumentMatchers.same(projectView2.metaUsersLink()))).thenReturn(List.of());
    projectSyncTask = new BlackDuckDataSyncTask(new BlackDuckProviderKey(), null, providerDataAccessor, blackDuckProperties);
    projectSyncTask.run();
    assertEquals(2, providerDataAccessor.getProjectsByProviderConfigId(providerConfigId).size());
}
Also used : ProjectUsersService(com.synopsys.integration.blackduck.service.dataservice.ProjectUsersService) BlackDuckProviderKey(com.synopsys.integration.alert.descriptor.api.BlackDuckProviderKey) BlackDuckProperties(com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties) BlackDuckApiClient(com.synopsys.integration.blackduck.service.BlackDuckApiClient) UserView(com.synopsys.integration.blackduck.api.generated.view.UserView) BlackDuckServicesFactory(com.synopsys.integration.blackduck.service.BlackDuckServicesFactory) HttpUrl(com.synopsys.integration.rest.HttpUrl) MockProviderDataAccessor(com.synopsys.integration.alert.provider.blackduck.MockProviderDataAccessor) ApiDiscovery(com.synopsys.integration.blackduck.api.generated.discovery.ApiDiscovery) BlackDuckRequest(com.synopsys.integration.blackduck.service.request.BlackDuckRequest) ProjectView(com.synopsys.integration.blackduck.api.generated.view.ProjectView) Test(org.junit.jupiter.api.Test)

Aggregations

BlackDuckProperties (com.synopsys.integration.alert.provider.blackduck.BlackDuckProperties)25 Test (org.junit.jupiter.api.Test)15 BlackDuckSystemValidator (com.synopsys.integration.alert.provider.blackduck.validator.BlackDuckSystemValidator)9 StatefulProvider (com.synopsys.integration.alert.api.provider.state.StatefulProvider)7 DefaultSystemMessageAccessor (com.synopsys.integration.alert.database.system.DefaultSystemMessageAccessor)7 BlackDuckProvider (com.synopsys.integration.alert.provider.blackduck.BlackDuckProvider)7 ProxyManager (com.synopsys.integration.alert.common.rest.proxy.ProxyManager)6 BlackDuckServerConfig (com.synopsys.integration.blackduck.configuration.BlackDuckServerConfig)5 IntegrationException (com.synopsys.integration.exception.IntegrationException)5 ConfigurationModelConfigurationAccessor (com.synopsys.integration.alert.common.persistence.accessor.ConfigurationModelConfigurationAccessor)4 IntLogger (com.synopsys.integration.log.IntLogger)4 AlertException (com.synopsys.integration.alert.api.common.model.exception.AlertException)3 ProviderTaskPropertiesAccessor (com.synopsys.integration.alert.common.persistence.accessor.ProviderTaskPropertiesAccessor)3 ConfigurationModel (com.synopsys.integration.alert.common.persistence.model.ConfigurationModel)3 BlackDuckHttpClient (com.synopsys.integration.blackduck.http.client.BlackDuckHttpClient)3 BlackDuckServicesFactory (com.synopsys.integration.blackduck.service.BlackDuckServicesFactory)3 Slf4jIntLogger (com.synopsys.integration.log.Slf4jIntLogger)3 Gson (com.google.gson.Gson)2 SystemMessageSeverity (com.synopsys.integration.alert.common.enumeration.SystemMessageSeverity)2 SystemMessageType (com.synopsys.integration.alert.common.enumeration.SystemMessageType)2