Search in sources :

Example 6 with Valid

use of javax.validation.Valid in project keywhiz by square.

the class SecretResource method modifySecretGroups.

/**
   * Modify the groups a secret is assigned to
   *
   * @excludeParams automationClient
   * @param name Secret series name
   * @param request JSON request to modify groups
   *
   * @responseMessage 201 Group membership changed
   * @responseMessage 404 Secret series not found
   */
@Timed
@ExceptionMetered
@PUT
@Path("{name}/groups")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
public Iterable<String> modifySecretGroups(@Auth AutomationClient automationClient, @PathParam("name") String name, @Valid ModifyGroupsRequestV2 request) {
    // TODO: Use latest version instead of non-versioned
    Secret secret = secretController.getSecretByName(name).orElseThrow(NotFoundException::new);
    String user = automationClient.getName();
    long secretId = secret.getId();
    Set<String> oldGroups = aclDAO.getGroupsFor(secret).stream().map(Group::getName).collect(toSet());
    Set<String> groupsToAdd = Sets.difference(request.addGroups(), oldGroups);
    Set<String> groupsToRemove = Sets.intersection(request.removeGroups(), oldGroups);
    // TODO: should optimize AclDAO to use names and return only name column
    groupsToGroupIds(groupsToAdd).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAO.findAndAllowAccess(secretId, groupId, auditLog, user, new HashMap<>())));
    groupsToGroupIds(groupsToRemove).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAO.findAndRevokeAccess(secretId, groupId, auditLog, user, new HashMap<>())));
    return aclDAO.getGroupsFor(secret).stream().map(Group::getName).collect(toSet());
}
Also used : Secret(keywhiz.api.model.Secret) SanitizedSecret(keywhiz.api.model.SanitizedSecret) Secret(keywhiz.api.model.Secret) Produces(javax.ws.rs.Produces) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) Valid(javax.validation.Valid) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) ContentCryptographer(keywhiz.service.crypto.ContentCryptographer) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) Group(keywhiz.api.model.Group) SecretVersion(keywhiz.api.model.SecretVersion) CreateSecretRequestV2(keywhiz.api.automation.v2.CreateSecretRequestV2) HOURS(java.time.temporal.ChronoUnit.HOURS) Set(java.util.Set) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) Base64(java.util.Base64) List(java.util.List) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) SecretDAOFactory(keywhiz.service.daos.SecretDAO.SecretDAOFactory) SecretContent(keywhiz.api.model.SecretContent) PathParam(javax.ws.rs.PathParam) SecretDetailResponseV2(keywhiz.api.automation.v2.SecretDetailResponseV2) AclDAO(keywhiz.service.daos.AclDAO) SanitizedSecretWithGroups(keywhiz.api.model.SanitizedSecretWithGroups) GET(javax.ws.rs.GET) Auth(io.dropwizard.auth.Auth) PartialUpdateSecretRequestV2(keywhiz.api.automation.v2.PartialUpdateSecretRequestV2) HashMap(java.util.HashMap) SecretSeriesDAO(keywhiz.service.daos.SecretSeriesDAO) Inject(javax.inject.Inject) AutomationClient(keywhiz.api.model.AutomationClient) ImmutableList(com.google.common.collect.ImmutableList) SecretDAO(keywhiz.service.daos.SecretDAO) SecretBuilder(keywhiz.service.daos.SecretController.SecretBuilder) AuditLog(keywhiz.log.AuditLog) DataAccessException(org.jooq.exception.DataAccessException) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) SecretSeriesDAOFactory(keywhiz.service.daos.SecretSeriesDAO.SecretSeriesDAOFactory) Readonly(keywhiz.service.config.Readonly) UTF_8(java.nio.charset.StandardCharsets.UTF_8) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) SetSecretVersionRequestV2(keywhiz.api.automation.v2.SetSecretVersionRequestV2) SecretController(keywhiz.service.daos.SecretController) EventTag(keywhiz.log.EventTag) Collectors.toList(java.util.stream.Collectors.toList) CreateOrUpdateSecretRequestV2(keywhiz.api.automation.v2.CreateOrUpdateSecretRequestV2) SecretSeriesAndContent(keywhiz.api.model.SecretSeriesAndContent) PUT(javax.ws.rs.PUT) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) PUT(javax.ws.rs.PUT)

Example 7 with Valid

use of javax.validation.Valid in project goci by EBISPOT.

the class AssociationController method addStandardSnps.

// Add new standard association/snp information to a study
@RequestMapping(value = "/studies/{studyId}/associations/add_standard", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String addStandardSnps(@ModelAttribute("form") @Valid SnpAssociationStandardMultiForm snpAssociationStandardMultiForm, BindingResult bindingResult, @PathVariable Long studyId, Model model, @RequestParam(required = true) String measurementType, HttpServletRequest request) throws EnsemblMappingException {
    Study study = studyRepository.findOne(studyId);
    model.addAttribute("study", study);
    model.addAttribute("measurementType", measurementType);
    // Binding vs Validator issue. File: messages.properties
    if (bindingResult.hasErrors()) {
        model.addAttribute("form", snpAssociationStandardMultiForm);
        return "add_standard_snp_association";
    }
    // Check for errors in form that would prevent saving an association
    List<AssociationValidationView> rowErrors = associationOperationsService.checkSnpAssociationFormErrors(snpAssociationStandardMultiForm, measurementType);
    if (!rowErrors.isEmpty()) {
        model.addAttribute("errors", rowErrors);
        model.addAttribute("form", snpAssociationStandardMultiForm);
        model.addAttribute("criticalErrorsFound", true);
        return "add_standard_snp_association";
    } else {
        // Create an association object from details in returned form
        Association newAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationStandardMultiForm);
        // Save and validate form
        String eRelease = ensemblRestTemplateService.getRelease();
        Collection<AssociationValidationView> errors = null;
        try {
            errors = associationOperationsService.saveAssociationCreatedFromForm(study, newAssociation, currentUserDetailsService.getUserFromRequest(request), eRelease);
        } catch (EnsemblMappingException e) {
            return "ensembl_mapping_failure";
        }
        // Determine if we have any errors rather than warnings
        long errorCount = errors.stream().filter(validationError -> !validationError.getWarning()).count();
        if (errorCount > 0) {
            model.addAttribute("errors", errors);
            model.addAttribute("form", snpAssociationStandardMultiForm);
            model.addAttribute("criticalErrorsFound", true);
            return "add_standard_snp_association";
        } else {
            return "redirect:/associations/" + newAssociation.getId();
        }
    }
}
Also used : FileUploadException(uk.ac.ebi.spot.goci.curation.exception.FileUploadException) java.util(java.util) SnpAssociationTableView(uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView) LoggerFactory(org.slf4j.LoggerFactory) SnpAssociationInteractionForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm) Autowired(org.springframework.beans.factory.annotation.Autowired) SimpleDateFormat(java.text.SimpleDateFormat) BindingResult(org.springframework.validation.BindingResult) Controller(org.springframework.stereotype.Controller) SnpAssociationStandardMultiForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm) EfoTraitRepository(uk.ac.ebi.spot.goci.repository.EfoTraitRepository) Value(org.springframework.beans.factory.annotation.Value) Valid(javax.validation.Valid) Model(org.springframework.ui.Model) uk.ac.ebi.spot.goci.curation.service(uk.ac.ebi.spot.goci.curation.service) HttpServletRequest(javax.servlet.http.HttpServletRequest) uk.ac.ebi.spot.goci.model(uk.ac.ebi.spot.goci.model) Qualifier(org.springframework.beans.factory.annotation.Qualifier) StudyRepository(uk.ac.ebi.spot.goci.repository.StudyRepository) Sort(org.springframework.data.domain.Sort) EnsemblRestTemplateService(uk.ac.ebi.spot.goci.service.EnsemblRestTemplateService) DateFormat(java.text.DateFormat) RedirectAttributes(org.springframework.web.servlet.mvc.support.RedirectAttributes) DataIntegrityException(uk.ac.ebi.spot.goci.curation.exception.DataIntegrityException) Logger(org.slf4j.Logger) AssociationRepository(uk.ac.ebi.spot.goci.repository.AssociationRepository) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) SnpAssociationForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm) EnsemblMappingException(uk.ac.ebi.spot.goci.exception.EnsemblMappingException) SheetProcessingException(uk.ac.ebi.spot.goci.exception.SheetProcessingException) IOException(java.io.IOException) SnpFormColumn(uk.ac.ebi.spot.goci.curation.model.SnpFormColumn) AssociationUploadErrorView(uk.ac.ebi.spot.goci.curation.model.AssociationUploadErrorView) FileNotFoundException(java.io.FileNotFoundException) MapCatalogService(uk.ac.ebi.spot.goci.service.MapCatalogService) GetRequest(com.mashape.unirest.request.GetRequest) SnpFormRow(uk.ac.ebi.spot.goci.curation.model.SnpFormRow) WebDataBinder(org.springframework.web.bind.WebDataBinder) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) LastViewedAssociation(uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation) MultipartFile(org.springframework.web.multipart.MultipartFile) AssociationValidationView(uk.ac.ebi.spot.goci.curation.model.AssociationValidationView) MappingDetails(uk.ac.ebi.spot.goci.curation.model.MappingDetails) LastViewedAssociation(uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation) AssociationValidationView(uk.ac.ebi.spot.goci.curation.model.AssociationValidationView) EnsemblMappingException(uk.ac.ebi.spot.goci.exception.EnsemblMappingException)

Example 8 with Valid

use of javax.validation.Valid in project goci by EBISPOT.

the class AssociationController method addSnpInteraction.

@RequestMapping(value = "/studies/{studyId}/associations/add_interaction", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public String addSnpInteraction(@ModelAttribute("form") @Valid SnpAssociationInteractionForm snpAssociationInteractionForm, BindingResult bindingResult, @PathVariable Long studyId, Model model, @RequestParam(required = true) String measurementType, HttpServletRequest request) throws EnsemblMappingException {
    Study study = studyRepository.findOne(studyId);
    model.addAttribute("study", study);
    model.addAttribute("measurementType", measurementType);
    // Binding vs Validator issue. File: messages.properties
    if (bindingResult.hasErrors()) {
        model.addAttribute("form", snpAssociationInteractionForm);
        return "add_snp_interaction_association";
    }
    // Check for errors in form that would prevent saving an association
    List<AssociationValidationView> colErrors = associationOperationsService.checkSnpAssociationInteractionFormErrors(snpAssociationInteractionForm, measurementType);
    if (!colErrors.isEmpty()) {
        model.addAttribute("errors", colErrors);
        model.addAttribute("form", snpAssociationInteractionForm);
        model.addAttribute("criticalErrorsFound", true);
        return "add_snp_interaction_association";
    } else {
        // Create an association object from details in returned form
        Association newAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
        // Save and validate form
        Collection<AssociationValidationView> errors = null;
        String eRelease = ensemblRestTemplateService.getRelease();
        try {
            errors = associationOperationsService.saveAssociationCreatedFromForm(study, newAssociation, currentUserDetailsService.getUserFromRequest(request), eRelease);
        } catch (EnsemblMappingException e) {
            return "ensembl_mapping_failure";
        }
        // Determine if we have any errors rather than warnings
        long errorCount = errors.stream().filter(validationError -> !validationError.getWarning()).count();
        if (errorCount > 0) {
            model.addAttribute("errors", errors);
            model.addAttribute("form", snpAssociationInteractionForm);
            model.addAttribute("criticalErrorsFound", true);
            return "add_snp_interaction_association";
        } else {
            return "redirect:/associations/" + newAssociation.getId();
        }
    }
}
Also used : FileUploadException(uk.ac.ebi.spot.goci.curation.exception.FileUploadException) java.util(java.util) SnpAssociationTableView(uk.ac.ebi.spot.goci.curation.model.SnpAssociationTableView) LoggerFactory(org.slf4j.LoggerFactory) SnpAssociationInteractionForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationInteractionForm) Autowired(org.springframework.beans.factory.annotation.Autowired) SimpleDateFormat(java.text.SimpleDateFormat) BindingResult(org.springframework.validation.BindingResult) Controller(org.springframework.stereotype.Controller) SnpAssociationStandardMultiForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationStandardMultiForm) EfoTraitRepository(uk.ac.ebi.spot.goci.repository.EfoTraitRepository) Value(org.springframework.beans.factory.annotation.Value) Valid(javax.validation.Valid) Model(org.springframework.ui.Model) uk.ac.ebi.spot.goci.curation.service(uk.ac.ebi.spot.goci.curation.service) HttpServletRequest(javax.servlet.http.HttpServletRequest) uk.ac.ebi.spot.goci.model(uk.ac.ebi.spot.goci.model) Qualifier(org.springframework.beans.factory.annotation.Qualifier) StudyRepository(uk.ac.ebi.spot.goci.repository.StudyRepository) Sort(org.springframework.data.domain.Sort) EnsemblRestTemplateService(uk.ac.ebi.spot.goci.service.EnsemblRestTemplateService) DateFormat(java.text.DateFormat) RedirectAttributes(org.springframework.web.servlet.mvc.support.RedirectAttributes) DataIntegrityException(uk.ac.ebi.spot.goci.curation.exception.DataIntegrityException) Logger(org.slf4j.Logger) AssociationRepository(uk.ac.ebi.spot.goci.repository.AssociationRepository) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) SnpAssociationForm(uk.ac.ebi.spot.goci.curation.model.SnpAssociationForm) EnsemblMappingException(uk.ac.ebi.spot.goci.exception.EnsemblMappingException) SheetProcessingException(uk.ac.ebi.spot.goci.exception.SheetProcessingException) IOException(java.io.IOException) SnpFormColumn(uk.ac.ebi.spot.goci.curation.model.SnpFormColumn) AssociationUploadErrorView(uk.ac.ebi.spot.goci.curation.model.AssociationUploadErrorView) FileNotFoundException(java.io.FileNotFoundException) MapCatalogService(uk.ac.ebi.spot.goci.service.MapCatalogService) GetRequest(com.mashape.unirest.request.GetRequest) SnpFormRow(uk.ac.ebi.spot.goci.curation.model.SnpFormRow) WebDataBinder(org.springframework.web.bind.WebDataBinder) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) LastViewedAssociation(uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation) MultipartFile(org.springframework.web.multipart.MultipartFile) AssociationValidationView(uk.ac.ebi.spot.goci.curation.model.AssociationValidationView) MappingDetails(uk.ac.ebi.spot.goci.curation.model.MappingDetails) LastViewedAssociation(uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation) AssociationValidationView(uk.ac.ebi.spot.goci.curation.model.AssociationValidationView) EnsemblMappingException(uk.ac.ebi.spot.goci.exception.EnsemblMappingException)

Example 9 with Valid

use of javax.validation.Valid in project ocvn by devgateway.

the class TenderPriceByTypeYearController method tenderPriceByAllBidSelectionMethods.

@ApiOperation(value = "Same as /api/tenderPriceByBidSelectionMethod, but it always returns " + "all bidSelectionMethods (it adds the missing bid selection methods with zero totals")
@RequestMapping(value = "/api/tenderPriceByAllBidSelectionMethods", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json")
public List<DBObject> tenderPriceByAllBidSelectionMethods(@ModelAttribute @Valid final YearFilterPagingRequest filter) {
    List<DBObject> tenderPriceByBidSelectionMethod = tenderPriceByBidSelectionMethod(filter);
    // create a treeset ordered by procurment method details key
    Collection<DBObject> ret = new TreeSet<>((DBObject o1, DBObject o2) -> o1.get(Keys.PROCUREMENT_METHOD_DETAILS).toString().compareTo(o2.get(Keys.PROCUREMENT_METHOD_DETAILS).toString()));
    // add them all to sorted set
    for (DBObject o : tenderPriceByBidSelectionMethod) {
        if (o.containsField(Keys.PROCUREMENT_METHOD_DETAILS) && o.get(Keys.PROCUREMENT_METHOD_DETAILS) != null) {
            ret.add(o);
        } else {
            o.put(Keys.PROCUREMENT_METHOD_DETAILS, UNSPECIFIED);
            ret.add(o);
        }
    }
    // get all the non null bid selection methods
    Set<Object> bidSelectionMethods = bidSelectionMethodSearchController.bidSelectionMethods().stream().filter(e -> e.get(Fields.UNDERSCORE_ID) != null).map(e -> e.get(Fields.UNDERSCORE_ID)).collect(Collectors.toCollection(LinkedHashSet::new));
    bidSelectionMethods.add(UNSPECIFIED);
    // remove elements that already are in the result
    bidSelectionMethods.removeAll(ret.stream().map(e -> e.get(Keys.PROCUREMENT_METHOD_DETAILS)).collect(Collectors.toSet()));
    // add the missing procurementmethoddetails with zero amounts
    bidSelectionMethods.forEach(e -> {
        DBObject obj = new BasicDBObject(Keys.PROCUREMENT_METHOD_DETAILS, e.toString());
        obj.put(Keys.TOTAL_TENDER_AMOUNT, BigDecimal.ZERO);
        ret.add(obj);
    });
    return new ArrayList<>(ret);
}
Also used : YearFilterPagingRequest(org.devgateway.ocds.web.rest.controller.request.YearFilterPagingRequest) Aggregation.group(org.springframework.data.mongodb.core.aggregation.Aggregation.group) Aggregation.newAggregation(org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation) Cacheable(org.springframework.cache.annotation.Cacheable) Aggregation.sort(org.springframework.data.mongodb.core.aggregation.Aggregation.sort) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Aggregation.match(org.springframework.data.mongodb.core.aggregation.Aggregation.match) Fields(org.springframework.data.mongodb.core.aggregation.Fields) MongoConstants(org.devgateway.ocds.persistence.mongo.constants.MongoConstants) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) BigDecimal(java.math.BigDecimal) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) DBObject(com.mongodb.DBObject) Direction(org.springframework.data.domain.Sort.Direction) LinkedHashSet(java.util.LinkedHashSet) Criteria.where(org.springframework.data.mongodb.core.query.Criteria.where) Collection(java.util.Collection) BasicDBObject(com.mongodb.BasicDBObject) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Set(java.util.Set) BidSelectionMethodSearchController(org.devgateway.ocds.web.rest.controller.selector.BidSelectionMethodSearchController) AggregationResults(org.springframework.data.mongodb.core.aggregation.AggregationResults) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) List(java.util.List) Aggregation.project(org.springframework.data.mongodb.core.aggregation.Aggregation.project) CacheConfig(org.springframework.cache.annotation.CacheConfig) CustomProjectionOperation(org.devgateway.toolkit.persistence.mongo.aggregate.CustomProjectionOperation) BasicDBObject(com.mongodb.BasicDBObject) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

Valid (javax.validation.Valid)9 Logger (org.slf4j.Logger)8 LoggerFactory (org.slf4j.LoggerFactory)8 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)5 Timed (com.codahale.metrics.annotation.Timed)5 Set (java.util.Set)5 DELETE (javax.ws.rs.DELETE)5 GET (javax.ws.rs.GET)5 POST (javax.ws.rs.POST)5 PUT (javax.ws.rs.PUT)5 Path (javax.ws.rs.Path)5 PathParam (javax.ws.rs.PathParam)5 Produces (javax.ws.rs.Produces)5 APPLICATION_JSON (javax.ws.rs.core.MediaType.APPLICATION_JSON)5 Response (javax.ws.rs.core.Response)5 Sets (com.google.common.collect.Sets)4 Auth (io.dropwizard.auth.Auth)4 String.format (java.lang.String.format)4 Instant (java.time.Instant)4 HashMap (java.util.HashMap)4