org.springframework.context.support.DefaultMessageSourceResolvable Java Examples

The following examples show how to use org.springframework.context.support.DefaultMessageSourceResolvable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UserController.java    From tutorials with MIT License 6 votes vote down vote up
@PostMapping("/user")
@ResponseBody
public ResponseEntity<Object> saveUser(@Valid User user, BindingResult result, Model model) {
    if (result.hasErrors()) {
        final List<String> errors = result.getAllErrors().stream()
          .map(DefaultMessageSourceResolvable::getDefaultMessage)
          .collect(Collectors.toList());

        return new ResponseEntity<>(errors, HttpStatus.OK);
    } else {
        if (users.stream().anyMatch(it -> user.getEmail().equals(it.getEmail()))) {
            return new ResponseEntity<>(Collections.singletonList("Email already exists!"), HttpStatus.CONFLICT);
        } else {
            users.add(user);
            return new ResponseEntity<>(HttpStatus.CREATED);
        }
    }
}
 
Example #2
Source File: MessageTagTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void messageTagWithMessageSourceResolvable() throws JspException {
	PageContext pc = createPageContext();
	final StringBuffer message = new StringBuffer();
	MessageTag tag = new MessageTag() {
		@Override
		protected void writeMessage(String msg) {
			message.append(msg);
		}
	};
	tag.setPageContext(pc);
	tag.setMessage(new DefaultMessageSourceResolvable("test"));
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
	assertEquals("Correct message", "test message", message.toString());
}
 
Example #3
Source File: EventApiV2Controller.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@GetMapping("event/{eventName}/code/{code}")
public ResponseEntity<Void> handleCode(@PathVariable("eventName") String eventName, @PathVariable("code") String code, ServletWebRequest request) {
    String trimmedCode = StringUtils.trimToNull(code);
    Map<String, String> queryStrings = new HashMap<>();

    Function<Pair<Optional<String>, BindingResult>, Optional<String>> handleErrors = (res) -> {
        if (res.getRight().hasErrors()) {
            queryStrings.put("errors", res.getRight().getAllErrors().stream().map(DefaultMessageSourceResolvable::getCode).collect(Collectors.joining(",")));
        }
        return res.getLeft();
    };

    var url = promoCodeRequestManager.createReservationFromPromoCode(eventName, trimmedCode, queryStrings::put, handleErrors, request).map(reservationId ->
        UriComponentsBuilder.fromPath("/event/{eventShortName}/reservation/{reservationId}/book")
            .build(Map.of("eventShortName", eventName, "reservationId", reservationId))
            .toString())
        .orElseGet(() -> {
                var backToEvent = UriComponentsBuilder.fromPath("/event/{eventShortName}");
                queryStrings.forEach(backToEvent::queryParam);
                return backToEvent.build(Map.of("eventShortName", eventName)).toString();
            }
        );
    return ResponseEntity.status(HttpStatus.MOVED_PERMANENTLY).header(HttpHeaders.LOCATION, url).build();
}
 
Example #4
Source File: MessageTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void messageTagWithMessageSourceResolvable() throws JspException {
	PageContext pc = createPageContext();
	final StringBuffer message = new StringBuffer();
	MessageTag tag = new MessageTag() {
		@Override
		protected void writeMessage(String msg) {
			message.append(msg);
		}
	};
	tag.setPageContext(pc);
	tag.setMessage(new DefaultMessageSourceResolvable("test"));
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
	assertEquals("Correct message", "test message", message.toString());
}
 
Example #5
Source File: MessageTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	assertEquals("test message", rc.getMessage("test"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null));
	assertEquals("test message", rc.getMessage("test", "default"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", new String[] {"arg1", "arg2"}, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", Arrays.asList(new String[] {"arg1", "arg2"}), "default"));
	assertEquals("default", rc.getMessage("testa", "default"));
	assertEquals("default", rc.getMessage("testa", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"test"});
	assertEquals("test message", rc.getMessage(resolvable));
}
 
Example #6
Source File: ThemeTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
	assertEquals("theme test message", rc.getThemeMessage("themetest"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null));
	assertEquals("theme test message", rc.getThemeMessage("themetest", "default"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default"));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", new String[] {"arg1"}));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"})));
	assertEquals("default", rc.getThemeMessage("themetesta", "default"));
	assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"});
	assertEquals("theme test message", rc.getThemeMessage(resolvable));
}
 
Example #7
Source File: AbstractRestExceptionHandler.java    From kaif with Apache License 2.0 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
    HttpHeaders headers,
    HttpStatus status,
    WebRequest request) {

  //TODO detail i18n and missing parameter name
  final String detail = ex.getBindingResult()
      .getAllErrors()
      .stream()
      .map(DefaultMessageSourceResolvable::getDefaultMessage)
      .collect(joining(", "));
  final E errorResponse = createErrorResponse(status,
      i18n(request, "rest-error.MethodArgumentNotValidException", detail));
  logException(ex, errorResponse, request);
  return new ResponseEntity<>(errorResponse, status);
}
 
Example #8
Source File: MessageTagTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	assertEquals("test message", rc.getMessage("test"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null));
	assertEquals("test message", rc.getMessage("test", "default"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", new String[] {"arg1", "arg2"}, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", Arrays.asList(new String[] {"arg1", "arg2"}), "default"));
	assertEquals("default", rc.getMessage("testa", "default"));
	assertEquals("default", rc.getMessage("testa", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"test"});
	assertEquals("test message", rc.getMessage(resolvable));
}
 
Example #9
Source File: MessageTagTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void messageTagWithMessageSourceResolvable() throws JspException {
	PageContext pc = createPageContext();
	final StringBuffer message = new StringBuffer();
	MessageTag tag = new MessageTag() {
		@Override
		protected void writeMessage(String msg) {
			message.append(msg);
		}
	};
	tag.setPageContext(pc);
	tag.setMessage(new DefaultMessageSourceResolvable("test"));
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertEquals("Correct doEndTag return value", Tag.EVAL_PAGE, tag.doEndTag());
	assertEquals("Correct message", "test message", message.toString());
}
 
Example #10
Source File: SpringValidatorAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return FieldError arguments for a validation error on the given field.
 * Invoked for each violated constraint.
 * <p>The default implementation returns a first argument indicating the field name
 * (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
 * Afterwards, it adds all actual constraint annotation attributes (i.e. excluding
 * "message", "groups" and "payload") in alphabetical order of their attribute names.
 * <p>Can be overridden to e.g. add further attributes from the constraint descriptor.
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @param descriptor the JSR-303 constraint descriptor
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 * @see org.springframework.validation.DefaultBindingErrorProcessor#getArgumentsForBindError
 */
protected Object[] getArgumentsForConstraint(String objectName, String field, ConstraintDescriptor<?> descriptor) {
	List<Object> arguments = new LinkedList<Object>();
	String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
	arguments.add(new DefaultMessageSourceResolvable(codes, field));
	// Using a TreeMap for alphabetical ordering of attribute names
	Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
	for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
		String attributeName = entry.getKey();
		Object attributeValue = entry.getValue();
		if (!internalAnnotationAttributes.contains(attributeName)) {
			attributesToExpose.put(attributeName, attributeValue);
		}
	}
	arguments.addAll(attributesToExpose.values());
	return arguments.toArray(new Object[arguments.size()]);
}
 
Example #11
Source File: ThemeTagTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
	assertEquals("theme test message", rc.getThemeMessage("themetest"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null));
	assertEquals("theme test message", rc.getThemeMessage("themetest", "default"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default"));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", new String[] {"arg1"}));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"})));
	assertEquals("default", rc.getThemeMessage("themetesta", "default"));
	assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"});
	assertEquals("theme test message", rc.getThemeMessage(resolvable));
}
 
Example #12
Source File: InvalidAttributeValueException.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @param attribute the attribute for which the exception occurred.
 * @param expectedTypeKey a resolvable message source key for the expetected value type.
 */
public InvalidAttributeValueException(Attribute attribute, String expectedTypeKey) {
  super(ERROR_CODE);
  this.attribute = requireNonNull(attribute);
  requireNonNull(expectedTypeKey);
  this.expectedType = new DefaultMessageSourceResolvable(expectedTypeKey);
}
 
Example #13
Source File: JseLocalValidatorFactoryBeanTest.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
@Test
public void 意図したサフィックスが付与されたArgumentsが生成される() {
    Object[] args = validator.getArgumentsForConstraint("profile", "name", descriptor);
    assertThat(args, is(notNullValue()));
    assertThat(args.length, is(1));
    assertThat(args[0], is(instanceOf(DefaultMessageSourceResolvable.class)));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes().length, is(4));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[0], is("profile.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[1], is("profileCriteria.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[2], is("profileSelection.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[3], is("name"));
    
    args = validator.getArgumentsForConstraint("profileCriteria", "name", descriptor);
    assertThat(args, is(notNullValue()));
    assertThat(args.length, is(1));
    assertThat(args[0], is(instanceOf(DefaultMessageSourceResolvable.class)));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes().length, is(4));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[0], is("profileCriteria.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[1], is("profile.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[2], is("profileSelection.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[3], is("name"));
    
    args = validator.getArgumentsForConstraint("profileSelection", "name", descriptor);
    assertThat(args, is(notNullValue()));
    assertThat(args.length, is(1));
    assertThat(args[0], is(instanceOf(DefaultMessageSourceResolvable.class)));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes().length, is(4));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[0], is("profileSelection.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[1], is("profile.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[2], is("profileCriteria.name"));
    assertThat(((DefaultMessageSourceResolvable)args[0]).getCodes()[3], is("name"));
    
}
 
Example #14
Source File: JseLocalValidatorFactoryBean.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Object[] getArgumentsForConstraint(final String objectName, String field, ConstraintDescriptor<?> descriptor) {
    Object[] args = super.getArgumentsForConstraint(objectName, field, descriptor);
    int index = 0;
    for (Object arg : args) {
        if (arg instanceof DefaultMessageSourceResolvable) {
            args[index] = getMessageSourceResolvable(objectName, field);
        }
        index++;
    }
    return args;
}
 
Example #15
Source File: RestExceptionHandler.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * prova ad utilizzare il default message, altrimenti va sul default
 *
 * @param fieldError
 * @return
 */
private String resolveLocalizedErrorMessage(DefaultMessageSourceResolvable fieldError) {
    Locale currentLocale = LocaleContextHolder.getLocale();
    String msgCode = StringUtils.isNotBlank(fieldError.getDefaultMessage()) ? fieldError.getDefaultMessage() : fieldError.getCode();
    String localizedErrorMessage = getMessageSource().getMessage(msgCode, fieldError.getArguments(), currentLocale);
    return localizedErrorMessage;
}
 
Example #16
Source File: MessageTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest(), pc.getServletContext());
	assertEquals("test message", rc.getMessage("test"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null));
	assertEquals("test message", rc.getMessage("test", "default"));
	assertEquals("test message", rc.getMessage("test", (Object[]) null, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", new String[] {"arg1", "arg2"}, "default"));
	assertEquals("test arg1 message arg2",
			rc.getMessage("testArgs", Arrays.asList(new String[] {"arg1", "arg2"}), "default"));
	assertEquals("default", rc.getMessage("testa", "default"));
	assertEquals("default", rc.getMessage("testa", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"test"});
	assertEquals("test message", rc.getMessage(resolvable));
}
 
Example #17
Source File: BlogController.java    From MyBlog with Apache License 2.0 5 votes vote down vote up
@PostMapping("modifyBlog")
public MyResponse modifyBlog(@Validated ModifyBlogParam param, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return MyResponse.createResponse(ResponseEnum.ILLEGAL_PARAM,
                bindingResult.getAllErrors().stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(toList()));
    }
    if (blogService.modifyBlog(param)) {
        return MyResponse.createResponse(ResponseEnum.SUCC);
    }
    return MyResponse.createResponse(ResponseEnum.FAIL);
}
 
Example #18
Source File: BlogController.java    From MyBlog with Apache License 2.0 5 votes vote down vote up
@PostMapping("addBlog")
public MyResponse addBlog(@Validated AddBlogParam param, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        return MyResponse.createResponse(ResponseEnum.ILLEGAL_PARAM,
                bindingResult.getAllErrors().stream()
                        .map(DefaultMessageSourceResolvable::getDefaultMessage)
                        .collect(toList()));
    }
    if (blogService.addBlog(param)) {
        return MyResponse.createResponse(ResponseEnum.SUCC);
    }
    return MyResponse.createResponse(ResponseEnum.FAIL);
}
 
Example #19
Source File: ResponseEntityBuilder.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static ResponseEntity<Result> buildOkData(Object data) {
	String[] msg;
	if (data instanceof BindingResult) {
		List<String> errorsList = new ArrayList();
		BindingResult bindingResult = (BindingResult) data;
		errorsList.addAll(bindingResult.getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.toList()));
		data = null;
		msg = new String[errorsList.size()];
		msg = errorsList.toArray(msg);
	} else {
		msg = new String[0];
	}
	return buildOk(data, msg);
}
 
Example #20
Source File: ExceptionHandler.java    From learning-code with Apache License 2.0 5 votes vote down vote up
/**
 * 参数检验违反约束(数据校验)
 *
 * @param e BindException
 * @return error message
 */
@org.springframework.web.bind.annotation.ExceptionHandler(BindException.class)
public ResponseEntity<String> handleConstraintViolationException(BindException e) {
    LOGGER.debug(e.getMessage(), e);
    return ResponseEntity.status(BAD_REQUEST).body(
            e.getBindingResult()
                    .getAllErrors()
                    .stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.joining(",")));
}
 
Example #21
Source File: ThemeTagTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void requestContext() throws ServletException {
	PageContext pc = createPageContext();
	RequestContext rc = new RequestContext((HttpServletRequest) pc.getRequest());
	assertEquals("theme test message", rc.getThemeMessage("themetest"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (String[]) null));
	assertEquals("theme test message", rc.getThemeMessage("themetest", "default"));
	assertEquals("theme test message", rc.getThemeMessage("themetest", (Object[]) null, "default"));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", new String[] {"arg1"}));
	assertEquals("theme test message arg1",
			rc.getThemeMessage("themetestArgs", Arrays.asList(new String[] {"arg1"})));
	assertEquals("default", rc.getThemeMessage("themetesta", "default"));
	assertEquals("default", rc.getThemeMessage("themetesta", (List) null, "default"));
	MessageSourceResolvable resolvable = new DefaultMessageSourceResolvable(new String[] {"themetest"});
	assertEquals("theme test message", rc.getThemeMessage(resolvable));
}
 
Example #22
Source File: CustomGlobalExceptionHandler.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
/**
 * 处理参数校验异常
 *
 * @param ex      ex
 * @param headers headers
 * @param status  status
 * @return ResponseEntity
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> validationBodyException(MethodArgumentNotValidException ex,
                                                      HttpHeaders headers,
                                                      HttpStatus status) {
    // 获取所有异常信息
    List<String> errors = ex.getBindingResult()
            .getFieldErrors()
            .stream()
            .map(DefaultMessageSourceResolvable::getDefaultMessage)
            .collect(Collectors.toList());
    ResponseBean<List<String>> responseBean = new ResponseBean<>(errors, ApiMsg.KEY_SERVICE, ApiMsg.ERROR);
    return new ResponseEntity<>(responseBean, headers, status);
}
 
Example #23
Source File: PermissionSet.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
public MessageSourceResolvable getName() {
  return new DefaultMessageSourceResolvable(new String[] {code()}, null, name());
}
 
Example #24
Source File: StepExecutionProgressInfo.java    From spring-cloud-dataflow with Apache License 2.0 4 votes vote down vote up
public MessageSourceResolvable getMessage() {
	return new DefaultMessageSourceResolvable(codes, message);
}
 
Example #25
Source File: Permission.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
default MessageSourceResolvable getName() {
  String code = Stream.of("permission", getType(), name(), "name").collect(joining("."));
  return new DefaultMessageSourceResolvable(new String[] {code}, null, name());
}
 
Example #26
Source File: Permission.java    From molgenis with GNU Lesser General Public License v3.0 4 votes vote down vote up
default MessageSourceResolvable getDescription() {
  String code = Stream.of("permission", getType(), name(), "description").collect(joining("."));
  return new DefaultMessageSourceResolvable(new String[] {code}, null, getDefaultDescription());
}
 
Example #27
Source File: PipelineController.java    From front50 with Apache License 2.0 4 votes vote down vote up
/**
 * Ensure basic validity of the pipeline. Invalid pipelines will raise runtime exceptions.
 *
 * @param pipeline The Pipeline to validate
 */
private void validatePipeline(final Pipeline pipeline) {
  // Pipelines must have an application and a name
  if (Strings.isNullOrEmpty(pipeline.getApplication())
      || Strings.isNullOrEmpty(pipeline.getName())) {
    throw new InvalidEntityException("A pipeline requires name and application fields");
  }

  // Check if pipeline type is templated
  if (TYPE_TEMPLATED.equals(pipeline.getType())) {
    PipelineTemplateDAO templateDAO = getTemplateDAO();

    // Check templated pipelines to ensure template is valid
    String source;
    switch (pipeline.getSchema()) {
      case "v2":
        V2TemplateConfiguration v2Config =
            objectMapper.convertValue(pipeline, V2TemplateConfiguration.class);
        source = v2Config.getTemplate().getReference();
        break;
      default:
        TemplateConfiguration v1Config =
            objectMapper.convertValue(pipeline.getConfig(), TemplateConfiguration.class);
        source = v1Config.getPipeline().getTemplate().getSource();
        break;
    }

    // With the source check if it starts with "spinnaker://"
    // Check if template id which is after :// is in the store
    if (source.startsWith(SPINNAKER_PREFIX)) {
      String templateId = source.substring(SPINNAKER_PREFIX.length());
      try {
        templateDAO.findById(templateId);
      } catch (NotFoundException notFoundEx) {
        throw new BadRequestException("Configured pipeline template not found", notFoundEx);
      }
    }
  }

  checkForDuplicatePipeline(
      pipeline.getApplication(), pipeline.getName().trim(), pipeline.getId());

  final GenericValidationErrors errors = new GenericValidationErrors(pipeline);
  pipelineValidators.forEach(it -> it.validate(pipeline, errors));

  if (errors.hasErrors()) {
    List<String> message =
        errors.getAllErrors().stream()
            .map(DefaultMessageSourceResolvable::getDefaultMessage)
            .collect(Collectors.toList());
    throw new ValidationException(message);
  }
}
 
Example #28
Source File: ReservationApiV2Controller.java    From alf.io with GNU General Public License v3.0 4 votes vote down vote up
@PostMapping("/event/{eventName}/reservation/{reservationId}")
public ResponseEntity<ValidatedResponse<ReservationPaymentResult>> confirmOverview(@PathVariable("eventName") String eventName,
                                                                                   @PathVariable("reservationId") String reservationId,
                                                                                   @RequestParam("lang") String lang,
                                                                                   @RequestBody  PaymentForm paymentForm,
                                                                                   BindingResult bindingResult,
                                                                                   HttpServletRequest request) {

    return getReservation(eventName, reservationId).map(er -> {

       var event = er.getLeft();
       var ticketReservation = er.getRight();
       var locale = LocaleUtil.forLanguageTag(lang, event);

        if (!ticketReservation.getValidity().after(new Date())) {
            bindingResult.reject(ErrorsCode.STEP_2_ORDER_EXPIRED);
        }


        final TotalPrice reservationCost = ticketReservationManager.totalReservationCostWithVAT(reservationId).getLeft();

        paymentForm.validate(bindingResult, event, reservationCost);
        if (bindingResult.hasErrors()) {
            return buildReservationPaymentStatus(bindingResult);
        }

        if(isCaptchaInvalid(reservationCost.getPriceWithVAT(), paymentForm.getPaymentProxy(), paymentForm.getCaptcha(), request, event)) {
            log.debug("captcha validation failed.");
            bindingResult.reject(ErrorsCode.STEP_2_CAPTCHA_VALIDATION_FAILED);
        }

        if(!bindingResult.hasErrors()) {
            extensionManager.handleReservationValidation(event, ticketReservation, paymentForm, bindingResult);
        }

        if (bindingResult.hasErrors()) {
            return buildReservationPaymentStatus(bindingResult);
        }

        CustomerName customerName = new CustomerName(ticketReservation.getFullName(), ticketReservation.getFirstName(), ticketReservation.getLastName(), event.mustUseFirstAndLastName());

        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, event);

        PaymentToken paymentToken = paymentManager.getPaymentToken(reservationId).orElse(null);
        if(paymentToken == null && StringUtils.isNotEmpty(paymentForm.getGatewayToken())) {
            paymentToken = paymentManager.buildPaymentToken(paymentForm.getGatewayToken(), paymentForm.getPaymentProxy(),
                new PaymentContext(event, reservationId));
        }
        PaymentSpecification spec = new PaymentSpecification(reservationId, paymentToken, reservationCost.getPriceWithVAT(),
            event, ticketReservation.getEmail(), customerName, ticketReservation.getBillingAddress(), ticketReservation.getCustomerReference(),
            locale, ticketReservation.isInvoiceRequested(), !ticketReservation.isDirectAssignmentRequested(),
            orderSummary, ticketReservation.getVatCountryCode(), ticketReservation.getVatNr(), ticketReservation.getVatStatus(),
            Boolean.TRUE.equals(paymentForm.getTermAndConditionsAccepted()), Boolean.TRUE.equals(paymentForm.getPrivacyPolicyAccepted()));

        final PaymentResult status = ticketReservationManager.performPayment(spec, reservationCost, paymentForm.getPaymentProxy(), paymentForm.getSelectedPaymentMethod());

        if (status.isRedirect()) {
            var body = ValidatedResponse.toResponse(bindingResult,
                new ReservationPaymentResult(!bindingResult.hasErrors(), true, status.getRedirectUrl(), status.isFailed(), status.getGatewayIdOrNull()));
            return ResponseEntity.ok(body);
        }

        if (!status.isSuccessful()) {
            String errorMessageCode = status.getErrorCode().orElse(StripeCreditCardManager.STRIPE_UNEXPECTED);
            MessageSourceResolvable message = new DefaultMessageSourceResolvable(new String[]{errorMessageCode, StripeCreditCardManager.STRIPE_UNEXPECTED});
            bindingResult.reject(ErrorsCode.STEP_2_PAYMENT_PROCESSING_ERROR, new Object[]{messageSourceManager.getMessageSourceForEvent(event).getMessage(message, locale)}, null);
            return buildReservationPaymentStatus(bindingResult);
        }


        return buildReservationPaymentStatus(bindingResult);

    }).orElseGet(() -> ResponseEntity.notFound().build());
}
 
Example #29
Source File: StepExecutionProgressInfo.java    From spring-cloud-dataflow with Apache License 2.0 3 votes vote down vote up
public MessageSourceResolvable getEstimatedPercentCompleteMessage() {

		String defaultMessage = String.format(
				"This execution is estimated to be %.0f%% complete after %.0f ms based on %s", percentageComplete * 100,
				duration, percentCompleteBasis.getMessage().getDefaultMessage());

		DefaultMessageSourceResolvable message = new DefaultMessageSourceResolvable(
				new String[] { "step.execution.estimated.progress" },
				new Object[] { percentageComplete, duration, percentCompleteBasis.getMessage() }, defaultMessage);

		return message;

	}
 
Example #30
Source File: DefaultBindingErrorProcessor.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Return FieldError arguments for a binding error on the given field.
 * Invoked for each missing required field and each type mismatch.
 * <p>The default implementation returns a single argument indicating the field name
 * (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
 * @param objectName the name of the target object
 * @param field the field that caused the binding error
 * @return the Object array that represents the FieldError arguments
 * @see org.springframework.validation.FieldError#getArguments
 * @see org.springframework.context.support.DefaultMessageSourceResolvable
 */
protected Object[] getArgumentsForBindError(String objectName, String field) {
	String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
	return new Object[] {new DefaultMessageSourceResolvable(codes, field)};
}