Search in sources :

Example 1 with ValidationException

use of eu.einfracentral.exception.ValidationException in project resource-catalogue by madgeek-arc.

the class ProviderManager method validateEmailsAndPhoneNumbers.

public void validateEmailsAndPhoneNumbers(ProviderBundle providerBundle) {
    EmailValidator validator = EmailValidator.getInstance();
    Pattern pattern = Pattern.compile("^(\\+\\d{1,3}( )?)?((\\(\\d{3}\\))|\\d{3})[- .]?\\d{3}[- .]?\\d{4}$");
    // main contact email
    String mainContactEmail = providerBundle.getProvider().getMainContact().getEmail();
    if (!validator.isValid(mainContactEmail)) {
        throw new ValidationException(String.format("Email [%s] is not valid. Found in field Main Contact Email", mainContactEmail));
    }
    // main contact phone
    if (providerBundle.getProvider().getMainContact().getPhone() != null && !providerBundle.getProvider().getMainContact().getPhone().equals("")) {
        String mainContactPhone = providerBundle.getProvider().getMainContact().getPhone();
        Matcher mainContactPhoneMatcher = pattern.matcher(mainContactPhone);
        try {
            assertTrue(mainContactPhoneMatcher.matches());
        } catch (AssertionError e) {
            throw new ValidationException(String.format("The phone you provided [%s] is not valid. Found in field Main Contact Phone", mainContactPhone));
        }
    }
    // public contact
    for (ProviderPublicContact providerPublicContact : providerBundle.getProvider().getPublicContacts()) {
        // public contact email
        if (providerPublicContact.getEmail() != null && !providerPublicContact.getEmail().equals("")) {
            String publicContactEmail = providerPublicContact.getEmail();
            if (!validator.isValid(publicContactEmail)) {
                throw new ValidationException(String.format("Email [%s] is not valid. Found in field Public Contact Email", publicContactEmail));
            }
        }
        // public contact phone
        if (providerPublicContact.getPhone() != null && !providerPublicContact.getPhone().equals("")) {
            String publicContactPhone = providerPublicContact.getPhone();
            Matcher publicContactPhoneMatcher = pattern.matcher(publicContactPhone);
            try {
                assertTrue(publicContactPhoneMatcher.matches());
            } catch (AssertionError e) {
                throw new ValidationException(String.format("The phone you provided [%s] is not valid. Found in field Public Contact Phone", publicContactPhone));
            }
        }
    }
    // user email
    for (User user : providerBundle.getProvider().getUsers()) {
        if (user.getEmail() != null && !user.getEmail().equals("")) {
            String userEmail = user.getEmail();
            if (!validator.isValid(userEmail)) {
                throw new ValidationException(String.format("Email [%s] is not valid. Found in field User Email", userEmail));
            }
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) EmailValidator(org.apache.commons.validator.routines.EmailValidator) ValidationException(eu.einfracentral.exception.ValidationException) Matcher(java.util.regex.Matcher)

Example 2 with ValidationException

use of eu.einfracentral.exception.ValidationException in project resource-catalogue by madgeek-arc.

the class VocabularyCurationManager method validate.

public VocabularyCuration validate(VocabularyCuration vocabularyCuration, Authentication auth) {
    // check if vocabulary already exists
    FacetFilter ff = new FacetFilter();
    ff.setQuantity(maxQuantity);
    List<Vocabulary> allVocs = vocabularyService.getAll(ff, null).getResults();
    List<String> allVocsIds = new ArrayList<>();
    for (Vocabulary vocabulary : allVocs) {
        allVocsIds.add(vocabulary.getName());
    }
    if (allVocsIds.contains(vocabularyCuration.getEntryValueName())) {
        throw new ValidationException("Vocabulary with name " + vocabularyCuration.getEntryValueName() + " already exists.");
    }
    // check if vocabularyCuration already exists in "pending"
    List<VocabularyCuration> allVocabularyCurations = getAll(ff, auth).getResults();
    for (VocabularyCuration vocCuration : allVocabularyCurations) {
        if (vocCuration.getEntryValueName().equalsIgnoreCase(vocabularyCuration.getEntryValueName()) && vocCuration.getVocabulary().equalsIgnoreCase(vocabularyCuration.getVocabulary()) && vocCuration.getStatus().equals(VocabularyCuration.Status.PENDING.getKey())) {
            vocabularyCuration.setVocabularyEntryRequests(updateVocabularyRequestsList(vocCuration, vocabularyCuration));
            vocabularyCuration.setId(vocCuration.getId());
        }
    }
    // validate vocabulary
    List<String> possibleValues = new ArrayList<>();
    for (Vocabulary.Type vocab : Vocabulary.Type.values()) {
        possibleValues.add(vocab.getKey().toLowerCase());
    }
    String voc = vocabularyCuration.getVocabulary();
    if (!possibleValues.contains(voc.toLowerCase())) {
        throw new ValidationException("Vocabulary " + voc + "' does not exist.");
    }
    // check if parent exists
    List<Vocabulary> specificVocs;
    List<String> specificVocsIds = new ArrayList<>();
    switch(vocabularyCuration.getVocabulary()) {
        case "CATEGORY":
            if (vocabularyCuration.getParent() == null || vocabularyCuration.getParent().equals("")) {
                throw new ValidationException("Vocabulary " + vocabularyCuration.getVocabulary() + " cannot have an empty parent.");
            } else {
                specificVocs = vocabularyService.getByType(Vocabulary.Type.SUPERCATEGORY);
                for (Vocabulary vocabulary : specificVocs) {
                    specificVocsIds.add(vocabulary.getId());
                }
                if (!specificVocsIds.contains(vocabularyCuration.getParent())) {
                    throw new ValidationException("Parent vocabulary " + vocabularyCuration.getParent() + " does not exist.");
                }
            }
            break;
        case "SUBCATEGORY":
            if (vocabularyCuration.getParent() == null || vocabularyCuration.getParent().equals("")) {
                throw new ValidationException("Vocabulary " + vocabularyCuration.getVocabulary() + " cannot have an empty parent.");
            } else {
                specificVocs = vocabularyService.getByType(Vocabulary.Type.CATEGORY);
                for (Vocabulary vocabulary : specificVocs) {
                    specificVocsIds.add(vocabulary.getId());
                }
                if (!specificVocsIds.contains(vocabularyCuration.getParent())) {
                    throw new ValidationException("Parent vocabulary " + vocabularyCuration.getParent() + " does not exist.");
                }
            }
            break;
        case "PROVIDER MERIL SCIENTIFIC SUBDOMAIN":
            if (vocabularyCuration.getParent() == null || vocabularyCuration.getParent().equals("")) {
                throw new ValidationException("Vocabulary " + vocabularyCuration.getVocabulary() + " cannot have an empty parent.");
            } else {
                specificVocs = vocabularyService.getByType(Vocabulary.Type.PROVIDER_MERIL_SCIENTIFIC_DOMAIN);
                for (Vocabulary vocabulary : specificVocs) {
                    specificVocsIds.add(vocabulary.getId());
                }
                if (!specificVocsIds.contains(vocabularyCuration.getParent())) {
                    throw new ValidationException("Parent vocabulary " + vocabularyCuration.getParent() + " does not exist.");
                }
            }
            break;
        case "SCIENTIFIC SUBDOMAIN":
            if (vocabularyCuration.getParent() == null || vocabularyCuration.getParent().equals("")) {
                throw new ValidationException("Vocabulary " + vocabularyCuration.getVocabulary() + " cannot have an empty parent.");
            } else {
                specificVocs = vocabularyService.getByType(Vocabulary.Type.SCIENTIFIC_DOMAIN);
                for (Vocabulary vocabulary : specificVocs) {
                    specificVocsIds.add(vocabulary.getId());
                }
                if (!specificVocsIds.contains(vocabularyCuration.getParent())) {
                    throw new ValidationException("Parent vocabulary " + vocabularyCuration.getParent() + " does not exist.");
                }
            }
            break;
        default:
            vocabularyCuration.setParent(null);
    }
    // validate resourceType/vocabulary combo
    String resourceType = vocabularyCuration.getVocabularyEntryRequests().get(0).getResourceType();
    if (resourceType.equalsIgnoreCase("provider")) {
        if (!vocabularyCuration.getVocabulary().equalsIgnoreCase(Vocabulary.Type.SCIENTIFIC_DOMAIN.getKey()) && !vocabularyCuration.getVocabulary().equalsIgnoreCase(Vocabulary.Type.SCIENTIFIC_SUBDOMAIN.getKey()) && !vocabularyCuration.getVocabulary().equalsIgnoreCase(Vocabulary.Type.COUNTRY.getKey())) {
            if (!StringUtils.containsIgnoreCase(vocabularyCuration.getVocabulary(), "provider")) {
                throw new ValidationException("Resource Type " + resourceType.toLowerCase() + " can't have as a Vocabulary the value " + vocabularyCuration.getVocabulary());
            }
        }
    } else if (resourceType.equalsIgnoreCase("resource") || resourceType.equalsIgnoreCase("service")) {
        if (StringUtils.containsIgnoreCase(vocabularyCuration.getVocabulary(), "provider")) {
            throw new ValidationException("Resource Type " + resourceType.toLowerCase() + " can't have as a Vocabulary the value " + vocabularyCuration.getVocabulary());
        }
    } else {
        throw new ValidationException("The resourceType you submitted is not supported. Possible resourceType values are 'provider', 'resource'");
    }
    // validate if providerId/resourceId exists
    FacetFilter facetFilter = new FacetFilter();
    facetFilter.setQuantity(maxQuantity);
    List<ProviderBundle> allProviders = providerService.getAll(facetFilter, auth).getResults();
    List<InfraService> allResources = infraServiceService.getAll(facetFilter, auth).getResults();
    List<String> providerIds = new ArrayList<>();
    List<String> resourceIds = new ArrayList<>();
    for (ProviderBundle provider : allProviders) {
        providerIds.add(provider.getId());
    }
    for (InfraService resource : allResources) {
        resourceIds.add(resource.getId());
    }
    String providerId = vocabularyCuration.getVocabularyEntryRequests().get(0).getProviderId();
    String resourceId = vocabularyCuration.getVocabularyEntryRequests().get(0).getResourceId();
    if (providerId != null && !providerIds.contains(providerId)) {
        throw new ValidationException("Provider with id " + vocabularyCuration.getVocabularyEntryRequests().get(0).getProviderId() + " does not exist.");
    }
    if (resourceId != null && !resourceIds.contains(resourceId)) {
        throw new ValidationException("Resource with id " + vocabularyCuration.getVocabularyEntryRequests().get(0).getProviderId() + " does not exist.");
    }
    return vocabularyCuration;
}
Also used : ValidationException(eu.einfracentral.exception.ValidationException) FacetFilter(eu.openminted.registry.core.domain.FacetFilter)

Example 3 with ValidationException

use of eu.einfracentral.exception.ValidationException in project resource-catalogue by madgeek-arc.

the class EventManager method setFavourite.

@Override
@CacheEvict(value = { CACHE_EVENTS, CACHE_SERVICE_EVENTS }, allEntries = true)
public Event setFavourite(String serviceId, Float value, Authentication authentication) throws ResourceNotFoundException {
    if (!infraServiceService.exists(new SearchService.KeyValue("infra_service_id", serviceId))) {
        throw new ResourceNotFoundException("infra_service", serviceId);
    }
    if (value != 1 && value != 0) {
        throw new ValidationException("Values of Favoring range between 0 - Unfavorite and 1 - Favorite");
    }
    List<Event> events = getEvents(Event.UserActionType.FAVOURITE.getKey(), serviceId, authentication);
    Event event;
    if (!events.isEmpty() && sameDay(events.get(0).getInstant())) {
        event = events.get(0);
        delete(event);
        logger.debug("Deleting previous FAVORITE Event '{}' because it happened more than once in the same day.", event);
    }
    event = new Event();
    event.setService(serviceId);
    event.setUser(AuthenticationInfo.getSub(authentication));
    event.setType(Event.UserActionType.FAVOURITE.getKey());
    event.setValue(value);
    // remove auth
    event = add(event, authentication);
    logger.debug("Adding a new FAVORITE Event: {}", event);
    return event;
}
Also used : ValidationException(eu.einfracentral.exception.ValidationException) Event(eu.einfracentral.domain.Event) ResourceNotFoundException(eu.openminted.registry.core.exception.ResourceNotFoundException) CacheEvict(org.springframework.cache.annotation.CacheEvict)

Example 4 with ValidationException

use of eu.einfracentral.exception.ValidationException in project resource-catalogue by madgeek-arc.

the class EventManager method setRating.

@Override
@CacheEvict(value = { CACHE_EVENTS, CACHE_SERVICE_EVENTS }, allEntries = true)
public Event setRating(String serviceId, Float value, Authentication authentication) throws ResourceNotFoundException, NumberParseException {
    if (!infraServiceService.exists(new SearchService.KeyValue("infra_service_id", serviceId))) {
        throw new ResourceNotFoundException("infra_service", serviceId);
    }
    if (value <= 0 || value > 5) {
        throw new ValidationException("Values of Rating range between 0 and 5");
    }
    List<Event> events = getEvents(Event.UserActionType.RATING.getKey(), serviceId, authentication);
    Event event;
    if (!events.isEmpty() && sameDay(events.get(0).getInstant())) {
        event = events.get(0);
        event.setValue(value);
        event = update(event, authentication);
        logger.debug("Updating RATING Event: {}", event);
    // 
    } else {
        event = new Event();
        event.setService(serviceId);
        event.setUser(AuthenticationInfo.getSub(authentication));
        event.setType(Event.UserActionType.RATING.getKey());
        event.setValue(value);
        // remove auth
        event = add(event, authentication);
        logger.debug("Adding a new RATING Event: {}", event);
    }
    return event;
}
Also used : ValidationException(eu.einfracentral.exception.ValidationException) Event(eu.einfracentral.domain.Event) ResourceNotFoundException(eu.openminted.registry.core.exception.ResourceNotFoundException) CacheEvict(org.springframework.cache.annotation.CacheEvict)

Example 5 with ValidationException

use of eu.einfracentral.exception.ValidationException in project resource-catalogue by madgeek-arc.

the class PendingProviderManager method add.

@Override
@CacheEvict(value = CACHE_PROVIDERS, allEntries = true)
public ProviderBundle add(ProviderBundle providerBundle, Authentication auth) {
    providerBundle.setId(idCreator.createProviderId(providerBundle.getProvider()));
    // Check if there is a Provider with the specific id
    FacetFilter ff = new FacetFilter();
    ff.setQuantity(1000);
    List<ProviderBundle> providerList = providerManager.getAll(ff, auth).getResults();
    for (ProviderBundle existingProvider : providerList) {
        if (providerBundle.getProvider().getId().equals(existingProvider.getProvider().getId())) {
            throw new ValidationException("Provider with the specific id already exists. Please refactor your 'abbreviation' field.");
        }
    }
    logger.trace("User '{}' is attempting to add a new Pending Provider: {}", auth, providerBundle);
    providerBundle.setMetadata(Metadata.updateMetadata(providerBundle.getMetadata(), User.of(auth).getFullName(), User.of(auth).getEmail()));
    LoggingInfo loggingInfo = LoggingInfo.createLoggingInfoEntry(User.of(auth).getEmail(), User.of(auth).getFullName(), securityService.getRoleName(auth), LoggingInfo.Types.DRAFT.getKey(), LoggingInfo.ActionType.CREATED.getKey());
    List<LoggingInfo> loggingInfoList = new ArrayList<>();
    loggingInfoList.add(loggingInfo);
    providerBundle.setLoggingInfo(loggingInfoList);
    super.add(providerBundle, auth);
    return providerBundle;
}
Also used : ValidationException(eu.einfracentral.exception.ValidationException) FacetFilter(eu.openminted.registry.core.domain.FacetFilter) ArrayList(java.util.ArrayList) CacheEvict(org.springframework.cache.annotation.CacheEvict)

Aggregations

ValidationException (eu.einfracentral.exception.ValidationException)13 FacetFilter (eu.openminted.registry.core.domain.FacetFilter)4 CacheEvict (org.springframework.cache.annotation.CacheEvict)4 Event (eu.einfracentral.domain.Event)2 ResourceNotFoundException (eu.openminted.registry.core.exception.ResourceNotFoundException)2 ArrayList (java.util.ArrayList)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 EmailValidator (org.apache.commons.validator.routines.EmailValidator)2 FieldValidation (eu.einfracentral.annotation.FieldValidation)1 InfraService (eu.einfracentral.domain.InfraService)1 ResourceException (eu.einfracentral.exception.ResourceException)1 ResourceNotFoundException (eu.einfracentral.exception.ResourceNotFoundException)1 EventService (eu.einfracentral.registry.service.EventService)1 InfraServiceService (eu.einfracentral.registry.service.InfraServiceService)1 ProviderService (eu.einfracentral.registry.service.ProviderService)1 VocabularyService (eu.einfracentral.registry.service.VocabularyService)1 AnalyticsService (eu.einfracentral.service.AnalyticsService)1 SecurityService (eu.einfracentral.service.SecurityService)1 SynchronizerService (eu.einfracentral.service.SynchronizerService)1