Search in sources :

Example 1 with Model

use of org.springframework.ui.Model in project spring-framework by spring-projects.

the class ModelAttributeMethodArgumentResolver method resolveArgument.

@Override
public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {
    ResolvableType type = ResolvableType.forMethodParameter(parameter);
    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(type.resolve());
    ResolvableType valueType = (adapter != null ? type.getGeneric(0) : type);
    Assert.state(adapter == null || !adapter.isMultiValue(), getClass().getSimpleName() + " doesn't support multi-value reactive type wrapper: " + parameter.getGenericParameterType());
    String name = getAttributeName(valueType, parameter);
    Mono<?> valueMono = getAttributeMono(name, valueType, context.getModel());
    Map<String, Object> model = context.getModel().asMap();
    MonoProcessor<BindingResult> bindingResultMono = MonoProcessor.create();
    model.put(BindingResult.MODEL_KEY_PREFIX + name, bindingResultMono);
    return valueMono.then(value -> {
        WebExchangeDataBinder binder = context.createDataBinder(exchange, value, name);
        return binder.bind(exchange).doOnError(bindingResultMono::onError).doOnSuccess(aVoid -> {
            validateIfApplicable(binder, parameter);
            BindingResult errors = binder.getBindingResult();
            model.put(BindingResult.MODEL_KEY_PREFIX + name, errors);
            model.put(name, value);
            bindingResultMono.onNext(errors);
        }).then(Mono.fromCallable(() -> {
            BindingResult errors = binder.getBindingResult();
            if (adapter != null) {
                return adapter.fromPublisher(errors.hasErrors() ? Mono.error(new WebExchangeBindException(parameter, errors)) : valueMono);
            } else {
                if (errors.hasErrors() && !hasErrorsArgument(parameter)) {
                    throw new WebExchangeBindException(parameter, errors);
                }
                return value;
            }
        }));
    });
}
Also used : ReactiveAdapter(org.springframework.core.ReactiveAdapter) Errors(org.springframework.validation.Errors) Validated(org.springframework.validation.annotation.Validated) ClassUtils(org.springframework.util.ClassUtils) AnnotationUtils(org.springframework.core.annotation.AnnotationUtils) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) MonoProcessor(reactor.core.publisher.MonoProcessor) Mono(reactor.core.publisher.Mono) BindingResult(org.springframework.validation.BindingResult) BindingContext(org.springframework.web.reactive.BindingContext) HandlerMethodArgumentResolver(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolver) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HandlerMethodArgumentResolverSupport(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport) Model(org.springframework.ui.Model) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) Annotation(java.lang.annotation.Annotation) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) BeanUtils(org.springframework.beans.BeanUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) BindingResult(org.springframework.validation.BindingResult) ResolvableType(org.springframework.core.ResolvableType) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 2 with Model

use of org.springframework.ui.Model in project spring-framework by spring-projects.

the class ViewResolutionResultHandler method resolveAsyncAttributes.

private Mono<Void> resolveAsyncAttributes(Map<String, Object> model) {
    List<String> names = new ArrayList<>();
    List<Mono<?>> valueMonos = new ArrayList<>();
    for (Map.Entry<String, ?> entry : model.entrySet()) {
        ReactiveAdapter adapter = getAdapterRegistry().getAdapter(null, entry.getValue());
        if (adapter != null) {
            names.add(entry.getKey());
            if (adapter.isMultiValue()) {
                Flux<Object> value = Flux.from(adapter.toPublisher(entry.getValue()));
                valueMonos.add(value.collectList().defaultIfEmpty(Collections.emptyList()));
            } else {
                Mono<Object> value = Mono.from(adapter.toPublisher(entry.getValue()));
                valueMonos.add(value.defaultIfEmpty(NO_VALUE));
            }
        }
    }
    if (names.isEmpty()) {
        return Mono.empty();
    }
    return Mono.when(valueMonos, values -> {
        for (int i = 0; i < values.length; i++) {
            if (values[i] != NO_VALUE) {
                model.put(names.get(i), values[i]);
            } else {
                model.remove(names.get(i));
            }
        }
        return NO_VALUE;
    }).then();
}
Also used : HttpRequestPathHelper(org.springframework.web.server.support.HttpRequestPathHelper) Ordered(org.springframework.core.Ordered) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) BindingResult(org.springframework.validation.BindingResult) BindingContext(org.springframework.web.reactive.BindingContext) HandlerResultHandlerSupport(org.springframework.web.reactive.result.HandlerResultHandlerSupport) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Model(org.springframework.ui.Model) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) Locale(java.util.Locale) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) HandlerResultHandler(org.springframework.web.reactive.HandlerResultHandler) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) ReactiveAdapter(org.springframework.core.ReactiveAdapter) ClassUtils(org.springframework.util.ClassUtils) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) Mono(reactor.core.publisher.Mono) NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) Collectors(java.util.stream.Collectors) HandlerResult(org.springframework.web.reactive.HandlerResult) Flux(reactor.core.publisher.Flux) List(java.util.List) Collections(java.util.Collections) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator) BeanUtils(org.springframework.beans.BeanUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) Mono(reactor.core.publisher.Mono) ArrayList(java.util.ArrayList) Map(java.util.Map) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 3 with Model

use of org.springframework.ui.Model in project spring-framework by spring-projects.

the class ViewResolutionResultHandler method addBindingResult.

private void addBindingResult(BindingContext context, ServerWebExchange exchange) {
    Map<String, Object> model = context.getModel().asMap();
    model.keySet().stream().filter(name -> isBindingCandidate(name, model.get(name))).filter(name -> !model.containsKey(BindingResult.MODEL_KEY_PREFIX + name)).forEach(name -> {
        WebExchangeDataBinder binder = context.createDataBinder(exchange, model.get(name), name);
        model.put(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
    });
}
Also used : HttpRequestPathHelper(org.springframework.web.server.support.HttpRequestPathHelper) Ordered(org.springframework.core.Ordered) RequestedContentTypeResolver(org.springframework.web.reactive.accept.RequestedContentTypeResolver) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) BindingResult(org.springframework.validation.BindingResult) BindingContext(org.springframework.web.reactive.BindingContext) HandlerResultHandlerSupport(org.springframework.web.reactive.result.HandlerResultHandlerSupport) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Model(org.springframework.ui.Model) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) Locale(java.util.Locale) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) HandlerResultHandler(org.springframework.web.reactive.HandlerResultHandler) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) ReactiveAdapter(org.springframework.core.ReactiveAdapter) ClassUtils(org.springframework.util.ClassUtils) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) Mono(reactor.core.publisher.Mono) NotAcceptableStatusException(org.springframework.web.server.NotAcceptableStatusException) Collectors(java.util.stream.Collectors) HandlerResult(org.springframework.web.reactive.HandlerResult) Flux(reactor.core.publisher.Flux) List(java.util.List) Collections(java.util.Collections) AnnotationAwareOrderComparator(org.springframework.core.annotation.AnnotationAwareOrderComparator) BeanUtils(org.springframework.beans.BeanUtils) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder)

Example 4 with Model

use of org.springframework.ui.Model in project spring-framework by spring-projects.

the class ControllerAdviceTests method modelAttributeAdvice.

@Test
public void modelAttributeAdvice() throws Exception {
    ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
    RequestMappingHandlerAdapter adapter = createAdapter(context);
    TestController controller = context.getBean(TestController.class);
    Model model = handle(adapter, controller, "handle").getModel();
    assertEquals(2, model.asMap().size());
    assertEquals("lAttr1", model.asMap().get("attr1"));
    assertEquals("gAttr2", model.asMap().get("attr2"));
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) AnnotationConfigApplicationContext(org.springframework.context.annotation.AnnotationConfigApplicationContext) Model(org.springframework.ui.Model) Test(org.junit.Test)

Example 5 with Model

use of org.springframework.ui.Model in project goci by EBISPOT.

the class AssociationController method editAssociation.

//Edit existing association
// We tried to remap if the snp or genes changed.
// TODO : implement something for SNP:SNP iteration. Actually we remap.
@RequestMapping(value = "/associations/{associationId}", produces = MediaType.TEXT_HTML_VALUE, method = RequestMethod.POST)
public // TODO COULD REFACTOR TO JUST USE SUPERCLASS AS METHOD PARAMETER
String editAssociation(@ModelAttribute SnpAssociationStandardMultiForm snpAssociationStandardMultiForm, @ModelAttribute SnpAssociationInteractionForm snpAssociationInteractionForm, @PathVariable Long associationId, @RequestParam(value = "associationtype", required = true) String associationType, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes) throws EnsemblMappingException {
    // Establish study and association we are editing
    Collection<String> previousAuthorReportedGenes = new HashSet<>();
    Collection<String> authorReportedGenes = new HashSet<>();
    Collection<String> previousSnps = new HashSet<>();
    Collection<String> snps = new HashSet<>();
    String isToRemapping = "yes";
    Association associationToEdit = associationRepository.findOne(associationId);
    Long studyId = associationToEdit.getStudy().getId();
    Study study = studyRepository.findOne(studyId);
    model.addAttribute("study", study);
    AssociationReport oldAssociationReport = associationToEdit.getAssociationReport();
    previousAuthorReportedGenes = associationOperationsService.getGenesIds(associationToEdit.getLoci());
    previousSnps = associationOperationsService.getSpnsName(associationToEdit.getSnps());
    // Determine if association is an OR or BETA type
    String measurementType = associationOperationsService.determineIfAssociationIsOrType(associationToEdit);
    model.addAttribute("measurementType", measurementType);
    // Validate returned form depending on association type
    List<AssociationValidationView> criticalErrors = new ArrayList<>();
    if (associationType.equalsIgnoreCase("interaction")) {
        criticalErrors = associationOperationsService.checkSnpAssociationInteractionFormErrors(snpAssociationInteractionForm, measurementType);
    } else {
        criticalErrors = associationOperationsService.checkSnpAssociationFormErrors(snpAssociationStandardMultiForm, measurementType);
    }
    // If errors found then return the edit form with all information entered by curator preserved
    if (!criticalErrors.isEmpty()) {
        // Get mapping details
        model.addAttribute("mappingDetails", associationOperationsService.createMappingDetails(associationToEdit));
        // Return any association errors
        model.addAttribute("errors", criticalErrors);
        model.addAttribute("criticalErrorsFound", true);
        if (associationType.equalsIgnoreCase("interaction")) {
            model.addAttribute("form", snpAssociationInteractionForm);
            return "edit_snp_interaction_association";
        } else {
            model.addAttribute("form", snpAssociationStandardMultiForm);
            // Determine view
            if (associationToEdit.getMultiSnpHaplotype()) {
                return "edit_multi_snp_association";
            } else {
                return "edit_standard_snp_association";
            }
        }
    } else {
        //Create association
        Association editedAssociation;
        // Request parameter determines how to process form and also which form to process
        if (associationType.equalsIgnoreCase("interaction")) {
            editedAssociation = snpInteractionAssociationService.createAssociation(snpAssociationInteractionForm);
        } else {
            editedAssociation = singleSnpMultiSnpAssociationService.createAssociation(snpAssociationStandardMultiForm);
            // New snps to compare with the previousSnps.
            Collection<SnpFormRow> newSnpsList = snpAssociationStandardMultiForm.getSnpFormRows();
            if (newSnpsList != null && !newSnpsList.isEmpty()) {
                for (SnpFormRow snp : newSnpsList) {
                    snps.add(snp.getSnp());
                }
            }
        }
        authorReportedGenes = associationOperationsService.getGenesIds(editedAssociation.getLoci());
        if (oldAssociationReport != null) {
            if ((previousAuthorReportedGenes.size() == authorReportedGenes.size()) && (snps.size() == snps.size())) {
                //check the values
                if ((authorReportedGenes.equals(previousAuthorReportedGenes)) && (snps.equals(previousSnps))) {
                    editedAssociation.setLastMappingDate(associationToEdit.getLastMappingDate());
                    editedAssociation.setLastMappingPerformedBy(associationToEdit.getLastMappingPerformedBy());
                    editedAssociation.setAssociationReport(oldAssociationReport);
                    isToRemapping = "no";
                }
            }
        }
        if ((oldAssociationReport != null) && (isToRemapping.compareTo("yes") == 0)) {
            associationOperationsService.deleteAssocationReport(associationToEdit.getAssociationReport().getId());
        }
        // Save and validate form
        String eRelease = ensemblRestTemplateService.getRelease();
        Collection<AssociationValidationView> errors = associationOperationsService.saveEditedAssociationFromForm(study, editedAssociation, associationId, currentUserDetailsService.getUserFromRequest(request), eRelease);
        // Determine if we have any errors rather than warnings
        long errorCount = errors.stream().filter(validationError -> !validationError.getWarning()).count();
        if (errorCount > 0) {
            // Get mapping details for association we're editing
            model.addAttribute("mappingDetails", associationOperationsService.createMappingDetails(associationToEdit));
            model.addAttribute("errors", errors);
            model.addAttribute("criticalErrorsFound", true);
            if (associationType.equalsIgnoreCase("interaction")) {
                model.addAttribute("form", snpAssociationInteractionForm);
                return "edit_snp_interaction_association";
            } else {
                model.addAttribute("form", snpAssociationStandardMultiForm);
                // Determine view
                if (associationToEdit.getMultiSnpHaplotype()) {
                    return "edit_multi_snp_association";
                } else {
                    return "edit_standard_snp_association";
                }
            }
        } else {
            redirectAttributes.addFlashAttribute("isToRemapping", isToRemapping);
            return "redirect:/associations/" + associationId;
        }
    }
}
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) AssociationValidationView(uk.ac.ebi.spot.goci.curation.model.AssociationValidationView) LastViewedAssociation(uk.ac.ebi.spot.goci.curation.model.LastViewedAssociation) SnpFormRow(uk.ac.ebi.spot.goci.curation.model.SnpFormRow)

Aggregations

Model (org.springframework.ui.Model)38 ExtendedModelMap (org.springframework.ui.ExtendedModelMap)24 HttpServletResponse (javax.servlet.http.HttpServletResponse)15 BindingResult (org.springframework.validation.BindingResult)15 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 CreateUserCommand (org.asqatasun.webapp.command.CreateUserCommand)10 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)9 MediaType (org.springframework.http.MediaType)8 IOException (java.io.IOException)6 Map (java.util.Map)6 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 Autowired (org.springframework.beans.factory.annotation.Autowired)6 WebDataBinder (org.springframework.web.bind.WebDataBinder)6 GetRequest (com.mashape.unirest.request.GetRequest)5 FileNotFoundException (java.io.FileNotFoundException)5 DateFormat (java.text.DateFormat)5 SimpleDateFormat (java.text.SimpleDateFormat)5 java.util (java.util)5 Valid (javax.validation.Valid)5