org.springframework.context.support.MessageSourceAccessor

Here are the examples of the java api org.springframework.context.support.MessageSourceAccessor taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

65 Examples 7

19 Source : BaseGlobalExceptionHandler.java
with MIT License
from zidoshare

/**
 * 统一异常处理
 *
 * @author zido
 */
public abstract clreplaced BaseGlobalExceptionHandler extends ResponseEnreplacedyExceptionHandler {

    private final HttpResponseBodyFactory factory;

    private final MessageSourceAccessor messages = CoffeeMessageSource.getAccessor();

    protected BaseGlobalExceptionHandler(HttpResponseBodyFactory factory) {
        replacedert.notNull(factory, "http response body factory cannot be null");
        this.factory = factory;
    }

    protected ResponseEnreplacedy<Object> handleConstraintViolationException(ConstraintViolationException e, WebRequest request) {
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> errors = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> next = iterator.next();
            Path propertyPath = next.getPropertyPath();
            String name = "unknown";
            // 获取参数名
            for (Path.Node node : propertyPath) {
                name = node.getName();
            }
            // 参数错误提示
            String message = "[" + name + "] " + next.getMessage();
            errors.add(message);
        }
        return handleExceptionInternal(e, factory.error(CommonErrorCode.VALIDATION_FAILED, messages.getMessage("ValidationFailed", "Validation Failed"), errors), new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
    }

    @Override
    protected ResponseEnreplacedy<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return handleExceptionInternal(ex, factory.error(CommonErrorCode.VALIDATION_FAILED, null, parseBindingResult(ex)), headers, status, request);
    }

    public static List<String> parseBindingResult(BindingResult ex) {
        List<String> errors = new ArrayList<>();
        for (FieldError error : ex.getFieldErrors()) {
            String name = error.getField();
            String message = error.getDefaultMessage();
            message = "[" + name + "] " + message;
            errors.add(message);
        }
        return errors;
    }

    /**
     * dto参数校验异常处理
     *
     * @param ex 校验异常
     * @return result
     */
    @Override
    protected ResponseEnreplacedy<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        List<String> errors = new ArrayList<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            String name = error.getField();
            String message = error.getDefaultMessage();
            message = "[" + name + "] " + message;
            errors.add(message);
        }
        return handleExceptionInternal(ex, factory.error(CommonErrorCode.VALIDATION_FAILED, null, errors), headers, status, request);
    }

    protected ResponseEnreplacedy<Object> handleCommonBusinessException(CommonBusinessException e, WebRequest request, HttpServletResponse response) {
        logger.warn("business error:" + e.getMessage());
        response.setStatus(e.getHttpStatus());
        HttpStatus status = HttpStatus.valueOf(e.getHttpStatus());
        HttpHeaders headers = new HttpHeaders();
        return handleExceptionInternal(e, factory.error(e.getCode(), e.getMsg(), null), headers, status, request);
    }

    @Override
    protected ResponseEnreplacedy<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        if (body == null) {
            body = factory.error(ex);
        }
        return super.handleExceptionInternal(ex, body, headers, status, request);
    }
}

19 Source : JwtTokenAuthorizationFilter.java
with Apache License 2.0
from zhouxx

/**
 * attention: must not managed by Spring.If managed by Spring, ignore url will not take effect!
 * @author Zhou Xiaoxiang
 * @since 1.0
 */
public clreplaced JwtTokenAuthorizationFilter extends OncePerRequestFilter {

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    private ExtensibleSecurity extensibleSecurity;

    private JwtTokenUtils jwtTokenUtils;

    private BlackListManager blackListManager;

    public JwtTokenAuthorizationFilter(JwtTokenUtils jwtTokenUtils, ExtensibleSecurity extensibleSecurity, BlackListManager blackListManager) {
        this.extensibleSecurity = extensibleSecurity;
        this.jwtTokenUtils = jwtTokenUtils;
        this.blackListManager = blackListManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = resolveToken(request);
        // Token is null
        if (token == null) {
            throw new AccessDeniedException(messages.getMessage("Token.Error", new Object[] { request.getRequestURI() }, "Token error, please check for {0}!"));
        }
        // token is in black list
        if (blackListManager.inBlackList(token)) {
            throw new AccessDeniedException(messages.getMessage("Token.Error", new Object[] { request.getRequestURI() }, "Token error, please check for {0}!"));
        }
        // validate token
        if (jwtTokenUtils.validateToken(token)) {
            // covert token to authentication
            Authentication authentication = jwtTokenUtils.getAuthentication(token);
            // extension validateToken
            extensibleSecurity.validTokenExtension(token, ((SecurityUser) authentication.getPrincipal()).getBizUser(), request, response);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // refresh token
            if (jwtTokenUtils.compareExpireTime(token)) {
                String newToken = jwtTokenUtils.refreshToken(token);
                response.addHeader(ExtensibleSecurity.HEADER_NAME, newToken);
            }
        } else {
            throw new AccessDeniedException(messages.getMessage("Token.Error", new Object[] { request.getRequestURI() }, "Token error, please check for {0}!"));
        }
        filterChain.doFilter(request, response);
    }

    /**
     * resolve token
     * @param request
     * @return token
     */
    private String resolveToken(HttpServletRequest request) {
        return extensibleSecurity.resolveToken(request);
    }
}

19 Source : CustomSecurityMetadataSource.java
with Apache License 2.0
from zhouxx

/**
 * @author Zhou Xiaoxiang
 * @since 1.0
 */
public clreplaced CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    protected MessageSourceAccessor messages = SecurityBizMessageSource.getAccessor();

    private final ExtensibleSecurity extensibleSecurity;

    private final SecurityBizProperties securityBizProperties;

    private final Map<RequestMatcher, Collection<ConfigAttribute>> requestMatchersPermitAllMap = new HashMap<>();

    public CustomSecurityMetadataSource(ExtensibleSecurity extensibleSecurity, SecurityBizProperties securityBizProperties) {
        this.extensibleSecurity = extensibleSecurity;
        this.securityBizProperties = securityBizProperties;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation fi = (FilterInvocation) object;
        Map<RequestMatcher, Collection<ConfigAttribute>> metadataSource = getMetadataSource(fi.getHttpRequest());
        for (Map.Entry<RequestMatcher, Collection<ConfigAttribute>> entry : metadataSource.entrySet()) {
            RequestMatcher requestMatcher = entry.getKey();
            if (requestMatcher.matches(fi.getHttpRequest())) {
                return entry.getValue();
            }
        }
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Clreplaced<?> clazz) {
        return FilterInvocation.clreplaced.isreplacedignableFrom(clazz);
    }

    private Map<RequestMatcher, Collection<ConfigAttribute>> getMetadataSource(HttpServletRequest request) {
        // 拿到用户,判断是否是最大权限
        // 从上下文中取得用户对象,只需要解析一次token
        BizUser bizUser = ((SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getBizUser();
        // 角色code
        Collection<String> roles = new ArrayList<>();
        // 默认uri匹配
        RequestMatcher requestMatcher = new AntPathRequestMatcher(request.getRequestURI(), request.getMethod());
        // 有最大权限的用户
        if (securityBizProperties.getPermitAllUserNames().contains(bizUser.getUsername())) {
            // 添加全部资源的角色
            roles.add("ROLE_ALL");
        } else // 不需要鉴权的url
        if (isMatchRequest(request)) {
            return requestMatchersPermitAllMap;
        } else {
            // 需要鉴权的
            BizResource bizResource = extensibleSecurity.obtainResource(request);
            if (bizResource == null) {
                throw new AccessDeniedException(messages.getMessage("Authorization.Failure", new Object[] { request.getRequestURI() }, "Authorization failure, make sure you can get roles for resource of {0}!"));
            } else {
                roles = bizResource.getRoles();
                requestMatcher = bizResource.getRequestMatcher();
            }
        }
        // 为了强制鉴权
        if (roles.isEmpty()) {
            roles.add(UUID.randomUUID().toString());
        }
        Collection<ConfigAttribute> configAttributes = new ArrayList<>();
        roles.forEach(roleCode -> {
            ConfigAttribute configAttribute = new SecurityConfig(roleCode);
            configAttributes.add(configAttribute);
        });
        Map<RequestMatcher, Collection<ConfigAttribute>> ret = new HashMap<>();
        ret.put(requestMatcher, configAttributes);
        return ret;
    }

    public Map<RequestMatcher, Collection<ConfigAttribute>> getRequestMatchersPermitAllMap() {
        if (CollectionUtils.isEmpty(requestMatchersPermitAllMap)) {
            List<AntPathRequestMatcher> requestMatchers = securityBizProperties.getPermitAllPatterns().stream().map(requestMatcher -> new AntPathRequestMatcher(requestMatcher.getPattern(), requestMatcher.getMethod().toString())).collect(Collectors.toList());
            for (RequestMatcher requestMatcher : requestMatchers) {
                ConfigAttribute configAttribute = new SecurityConfig("ROLE_PUBLIC");
                requestMatchersPermitAllMap.put(requestMatcher, Collections.singletonList(configAttribute));
            }
        }
        return requestMatchersPermitAllMap;
    }

    private boolean isMatchRequest(HttpServletRequest request) {
        Map<RequestMatcher, Collection<ConfigAttribute>> requestMatchersPermitAllMap = getRequestMatchersPermitAllMap();
        AtomicBoolean isMatch = new AtomicBoolean(false);
        requestMatchersPermitAllMap.forEach((requestMatcher, configAttributes) -> {
            if (requestMatcher.matches(request)) {
                isMatch.set(true);
            }
        });
        return isMatch.get();
    }
}

19 Source : CustomAccessDecisionManager.java
with Apache License 2.0
from zhouxx

/**
 * @author Zhou Xiaoxiang
 * @since 1.0
 */
public clreplaced CustomAccessDecisionManager implements AccessDecisionManager {

    protected MessageSourceAccessor messages = SecurityBizMessageSource.getAccessor();

    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        FilterInvocation fi = (FilterInvocation) object;
        String requestURI = fi.getHttpRequest().getRequestURI();
        for (ConfigAttribute attribute : configAttributes) {
            if (authentication == null) {
                throw new AccessDeniedException(messages.getMessage("Authorization.NotAllowed", new Object[] { requestURI }, "Authorization is not allowed for {0}!"));
            }
            String needCode = attribute.getAttribute();
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            for (GrantedAuthority authority : authorities) {
                if (StringUtils.equals(authority.getAuthority(), needCode)) {
                    return;
                }
            }
        }
        throw new AccessDeniedException(messages.getMessage("Authorization.NotAllowed", new Object[] { requestURI }, "Authorization is not allowed for {0}!"));
    }

    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    public boolean supports(Clreplaced<?> clazz) {
        return FilterInvocation.clreplaced.isreplacedignableFrom(clazz);
    }
}

19 Source : TfaOtpAuthenticationProvider.java
with Apache License 2.0
from xm-online

public void setMessages(MessageSourceAccessor messages) {
    this.messages = messages;
}

19 Source : ServerEndpointFilterBase.java
with Apache License 2.0
from webauthn4j

public abstract clreplaced ServerEndpointFilterBase extends GenericFilterBean {

    // ~ Instance fields
    // ================================================================================================
    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    protected ObjectConverter objectConverter;

    protected ServerEndpointFilterUtil serverEndpointFilterUtil;

    /**
     * Url this filter should get activated on.
     */
    private String filterProcessesUrl;

    public ServerEndpointFilterBase(String filterProcessesUrl, ObjectConverter objectConverter) {
        this.filterProcessesUrl = filterProcessesUrl;
        this.objectConverter = objectConverter;
        this.serverEndpointFilterUtil = new ServerEndpointFilterUtil(this.objectConverter);
        checkConfig();
    }

    public ServerEndpointFilterBase() {
    }

    @Override
    public void afterPropertiesSet() {
        checkConfig();
    }

    private void checkConfig() {
        replacedert.notNull(filterProcessesUrl, "filterProcessesUrl must not be null");
        replacedert.notNull(objectConverter, "objectConverter must not be null");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        FilterInvocation fi = new FilterInvocation(request, response, chain);
        try {
            HttpServletRequest httpServletRequest = fi.getRequest();
            HttpServletResponse httpServletResponse = fi.getResponse();
            if (!httpServletRequest.getMethod().equals(HttpMethod.POST.name())) {
                throw new AuthenticationServiceException("Authentication method not supported: " + httpServletRequest.getMethod());
            }
            if (!processFilter(httpServletRequest)) {
                chain.doFilter(request, response);
                return;
            }
            try {
                ServerResponse serverResponse = processRequest(httpServletRequest);
                serverEndpointFilterUtil.writeResponse(httpServletResponse, serverResponse);
            } catch (WebAuthnException e) {
                throw ExceptionUtil.wrapWithAuthenticationException(e);
            }
        } catch (RuntimeException e) {
            logger.debug("RuntimeException is thrown", e);
            serverEndpointFilterUtil.writeErrorResponse(fi.getResponse(), e);
        }
    }

    protected abstract ServerResponse processRequest(HttpServletRequest request);

    /**
     * The filter will be used in case the URL of the request contains the FILTER_URL.
     *
     * @param request request used to determine whether to enable this filter
     * @return true if this filter should be used
     */
    private boolean processFilter(HttpServletRequest request) {
        return (request.getRequestURI().contains(filterProcessesUrl));
    }

    public String getFilterProcessesUrl() {
        return filterProcessesUrl;
    }

    public void setFilterProcessesUrl(String filterProcessesUrl) {
        replacedert.hasText(filterProcessesUrl, "filterProcessesUrl parameter must not be empty or null");
        this.filterProcessesUrl = filterProcessesUrl;
    }
}

19 Source : PropertyMessageService.java
with Apache License 2.0
from PaaS-TA

/**
 * paastaDeliveryPipelineApi
 * paasta.delivery.pipeline.ui.common
 *
 * @author REX
 * @version 1.0
 * @since 5 /12/2017
 */
@Service
public clreplaced PropertyMessageService {

    private MessageSourceAccessor messageSourceAccessor;

    /**
     * Instantiates a new Property message service.
     *
     * @param messageSourceAccessor the message source accessor
     */
    @Autowired
    public PropertyMessageService(MessageSourceAccessor messageSourceAccessor) {
        setMessageSourceAccessor(messageSourceAccessor);
    }

    /**
     * Gets message source accessor.
     *
     * @return the message source accessor
     */
    public MessageSourceAccessor getMessageSourceAccessor() {
        return messageSourceAccessor;
    }

    private void setMessageSourceAccessor(MessageSourceAccessor messageSourceAccessor) {
        this.messageSourceAccessor = messageSourceAccessor;
    }

    /**
     * Gets message.
     *
     * @param key the key
     * @return the message
     */
    public String getMessage(String key) {
        return messageSourceAccessor.getMessage(key);
    }

    /**
     * Gets message.
     *
     * @param key     the key
     * @param strings the strings
     * @return the message
     */
    public String getMessage(String key, String[] strings) {
        return messageSourceAccessor.getMessage(key, strings);
    }
}

19 Source : PropertyMessageService.java
with Apache License 2.0
from PaaS-TA

private void setMessageSourceAccessor(MessageSourceAccessor messageSourceAccessor) {
    this.messageSourceAccessor = messageSourceAccessor;
}

19 Source : MessageSourceResolvableHttpMessageConverter.java
with Apache License 2.0
from odrotbohm

/**
 * An {@link HttpMessageConverter} that immediately renders {@link MessageSourceResolvable} instances returned from a
 * Spring MVC controller as plain text if {@link MediaType#TEXT_PLAIN} is requested.
 *
 * @author Oliver Drotbohm
 */
public clreplaced MessageSourceResolvableHttpMessageConverter extends AbstractHttpMessageConverter<MessageSourceResolvable> {

    private final MessageSourceAccessor messages;

    /**
     * Creates a new {@link MessageSourceResolvableHttpMessageConverter} for the given {@link MessageSourceAccessor}.
     *
     * @param messages must not be {@literal null}.
     */
    MessageSourceResolvableHttpMessageConverter(MessageSourceAccessor messages) {
        super(MediaType.TEXT_PLAIN);
        replacedert.notNull(messages, "Messages must not be null!");
        this.messages = messages;
    }

    /*
	 * (non-Javadoc)
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#supports(java.lang.Clreplaced)
	 */
    @Override
    protected boolean supports(Clreplaced<?> clazz) {
        return MessageSourceResolvable.clreplaced.isreplacedignableFrom(clazz);
    }

    /*
	 * (non-Javadoc)
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#writeInternal(java.lang.Object, org.springframework.http.HttpOutputMessage)
	 */
    @Override
    protected void writeInternal(MessageSourceResolvable t, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        outputMessage.getBody().write(messages.getMessage(t).getBytes());
    }

    /*
	 * (non-Javadoc)
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#canRead(org.springframework.http.MediaType)
	 */
    @Override
    protected boolean canRead(MediaType mediaType) {
        return false;
    }

    /*
	 * (non-Javadoc)
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Clreplaced, org.springframework.http.HttpInputMessage)
	 */
    @Override
    protected MessageSourceResolvable readInternal(Clreplaced<? extends MessageSourceResolvable> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        throw new UnsupportedOperationException();
    }
}

19 Source : MessageSourceResolvableSerializer.java
with Apache License 2.0
from odrotbohm

/**
 * A Jackson serializer triggering message resolution via a {@link MessageSourceAccessor} for
 * {@link MessageSourceResolvable} instances about to be serialized.
 *
 * @author Oliver Drotbohm
 */
clreplaced MessageSourceResolvableSerializer extends StdSerializer<MessageSourceResolvable> {

    private static final long serialVersionUID = 4302540100251549622L;

    private final MessageSourceAccessor accessor;

    /**
     * Creates a new {@link MessageSourceResolvableSerializer} for the given {@link MessageSourceAccessor}.
     *
     * @param accessor must not be {@literal null}.
     */
    public MessageSourceResolvableSerializer(MessageSourceAccessor accessor) {
        super(MessageSourceResolvable.clreplaced);
        this.accessor = accessor;
    }

    /*
	 * (non-Javadoc)
	 * @see com.fasterxml.jackson.databind.ser.std.StdSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
	 */
    @Override
    @SuppressWarnings("null")
    public void serialize(MessageSourceResolvable value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(accessor.getMessage(value));
    }
}

19 Source : DefaultPasswordStrategy.java
with MIT License
from leecho

/**
 * @author LIQIU
 * created on 2018/12/29
 */
public clreplaced DefaultPreplacedwordStrategy implements PreplacedwordStrategy {

    private final PreplacedwordProperties properties;

    protected MessageSourceAccessor messages;

    public DefaultPreplacedwordStrategy(PreplacedwordProperties properties) {
        this.properties = properties;
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        messages = new MessageSourceAccessor(messageSource);
    }

    /**
     * 检查密码强度
     *
     * @param preplacedword 密码
     */
    @Override
    public void check(String preplacedword) {
        if (StringUtils.isEmpty(preplacedword)) {
            throw new InvalidPreplacedwordException(messages.getMessage("PreplacedwordIsNull", "Preplacedword must not be null"));
        }
        if (StringUtils.length(preplacedword) < properties.getMinLength()) {
            throw new InvalidPreplacedwordException(messages.getMessage("PreplacedwordIsTooShort", "The length of preplacedword is too short"));
        }
        if (StringUtils.length(preplacedword) > properties.getMinLength()) {
            throw new InvalidPreplacedwordException(messages.getMessage("PreplacedwordIsTooLong", "The length of preplacedword is too long"));
        }
    }
}

19 Source : IOProcessorImpl.java
with Apache License 2.0
from i-novus-llc

public void setMessageSourceAccessor(MessageSourceAccessor messageSourceAccessor) {
    this.messageSourceAccessor = messageSourceAccessor;
}

19 Source : N2oEnvironment.java
with Apache License 2.0
from i-novus-llc

public void setMessageSource(MessageSourceAccessor messageSource) {
    this.messageSource = messageSource;
}

19 Source : AutoTestApplication.java
with Apache License 2.0
from i-novus-llc

@Bean
ErrorMessageBuilder errorMessageBuilder(@Qualifier("n2oMessageSourceAccessor") MessageSourceAccessor messageSourceAccessor) {
    return new ErrorMessageBuilder(messageSourceAccessor);
}

19 Source : ErrorMessageBuilder.java
with Apache License 2.0
from i-novus-llc

/**
 * Сборка сообщения об ошибке в формате клиента
 */
public clreplaced ErrorMessageBuilder {

    private static final String LINE_SEPARATOR = System.getProperty("line.separator");

    private MessageSourceAccessor messageSourceAccessor;

    private Boolean showStacktrace = true;

    public ErrorMessageBuilder(MessageSourceAccessor messageSourceAccessor) {
        this.messageSourceAccessor = messageSourceAccessor;
    }

    public ErrorMessageBuilder(MessageSourceAccessor messageSourceAccessor, Boolean showStacktrace) {
        this.messageSourceAccessor = messageSourceAccessor;
        this.showStacktrace = showStacktrace;
    }

    public ResponseMessage build(Exception e) {
        ResponseMessage resp = new ResponseMessage();
        resp.setText(buildText(e));
        if (showStacktrace && !(e instanceof N2oUserException))
            resp.setStacktrace(getStackFrames(getStackTrace(e)));
        if (e instanceof N2oException) {
            resp.setSeverityType(((N2oException) e).getSeverity());
            resp.setField(((N2oException) e).getField());
        } else {
            resp.setSeverityType(SeverityType.danger);
        }
        return resp;
    }

    private List<ResponseMessage> buildValidationMessages(N2oValidationException e) {
        List<ResponseMessage> messages = new ArrayList<>();
        if (e.getMessages() != null) {
            for (ValidationMessage message : e.getMessages()) {
                ResponseMessage resp = new ResponseMessage();
                // resp.setChoice(e.getChoice()); todo use dialog
                resp.setSeverityType(e.getSeverity());
                resp.setField(message.getFieldId());
                resp.setText(message.getMessage());
                messages.add(resp);
            }
        }
        return messages;
    }

    private String getStackTrace(Throwable throwable) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        return sw.getBuffer().toString();
    }

    private List<String> getStackFrames(String stacktrace) {
        StringTokenizer frames = new StringTokenizer(stacktrace, LINE_SEPARATOR);
        List<String> list = new ArrayList<>();
        while (frames.hasMoreTokens()) {
            list.add(frames.nextToken());
        }
        return list;
    }

    private String buildText(Exception e) {
        String message = "n2o.exceptions.error.message";
        String userMessage = e instanceof N2oException ? ((N2oException) e).getUserMessage() : null;
        message = userMessage != null ? userMessage : message;
        String localizedMessage = messageSourceAccessor.getMessage(message, message);
        if (e instanceof N2oException)
            return StringUtils.resolveLinks(localizedMessage, ((N2oException) e).getData());
        else
            return localizedMessage;
    }

    public List<ResponseMessage> buildMessages(Exception e) {
        return e instanceof N2oValidationException ? buildValidationMessages((N2oValidationException) e) : Collections.singletonList(build(e));
    }
}

19 Source : VotingQuestionEnricher.java
with MIT License
from FAForever

@Inject
public void init(MessageSourceAccessor messageSourceAccessor) {
    VotingQuestionEnricher.messageSourceAccessor = messageSourceAccessor;
}

19 Source : TutorialCategoryEnricherListener.java
with MIT License
from FAForever

@Inject
public void init(MessageSourceAccessor messageSourceAccessor) {
    TutorialCategoryEnricherListener.messageSourceAccessor = messageSourceAccessor;
}

19 Source : EventLocalizationListener.java
with MIT License
from FAForever

@Inject
public void init(MessageSourceAccessor messageSourceAccessor) {
    EventLocalizationListener.messageSourceAccessor = messageSourceAccessor;
}

19 Source : AchievementLocalizationListener.java
with MIT License
from FAForever

@Inject
public void init(MessageSourceAccessor messageSourceAccessor) {
    AchievementLocalizationListener.messageSourceAccessor = messageSourceAccessor;
}

18 Source : TokenAuthorizationFilter.java
with Apache License 2.0
from zhouxx

/**
 * attention: must not managed by Spring.If managed by Spring, ignore url will not take effect!
 * @author Zhou Xiaoxiang
 * @since 1.0
 */
public clreplaced TokenAuthorizationFilter extends OncePerRequestFilter {

    protected MessageSourceAccessor messages = SecurityBizMessageSource.getAccessor();

    private final SecurityTokenUtils securityTokenUtils;

    private final ExtensibleSecurity extensibleSecurity;

    public TokenAuthorizationFilter(SecurityTokenUtils securityTokenUtils, ExtensibleSecurity extensibleSecurity) {
        this.extensibleSecurity = extensibleSecurity;
        this.securityTokenUtils = securityTokenUtils;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = resolveToken(request);
        // Token is null
        if (token == null) {
            throw new AccessDeniedException(messages.getMessage("Token.Empty", new Object[] { request.getRequestURI() }, "Token error, please check for {0}!"));
        }
        // token is exist
        if (!securityTokenUtils.exist(token)) {
            throw new AccessDeniedException(messages.getMessage("Token.Invalid", new Object[] { request.getRequestURI() }, "Token error, please check for {0}!"));
        }
        // covert token to authentication
        Authentication authentication = securityTokenUtils.getAuthentication(token);
        // extension validateToken
        extensibleSecurity.validTokenExtension(token, ((SecurityUser) authentication.getPrincipal()).getBizUser(), request, response);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        filterChain.doFilter(request, response);
    }

    /**
     * resolve token
     */
    private String resolveToken(HttpServletRequest request) {
        return extensibleSecurity.resolveToken(request);
    }
}

18 Source : Messages.java
with MIT License
from willianantunes

@Component
public clreplaced Messages {

    public static final String COMMAND_START = "command.start";

    public static final String COMMAND_CONFIGURAR = "command.configurar";

    public static final String COMMAND_ATUAL = "command.atual";

    public static final String COMMAND_ATUAL_NO_ONE = "command.atual.no-one";

    public static final String COMMAND_RETIRAR_CONFIGURED = "command.retirar.configured";

    public static final String COMMAND_RETIRAR_COMPLETED = "command.retirar.completed";

    public static final String COMMAND_RETIRAR_WRONG_OPTION = "command.retirar.wrong-option";

    public static final String COMMAND_RETIRAR_NOT_CONFIGURED = "command.retirar.not-configured";

    public static final String COMMAND_RESEARCH = "command.research";

    public static final String COMMAND_RESEARCH_OUTPUT_START = "command.research.output.start";

    public static final String COMMAND_RESEARCH_OUTPUT_MORE = "command.research.output.more";

    public static final String COMMAND_RESEARCH_OUTPUT_ENTRY = "command.research.output.entry";

    public static final String COMMAND_RESEARCH_OUTPUT_NOTHING = "command.research.output.nothing";

    public static final String COMMAND_RESEARCH_OUTPUT_MORE_ENTRIES = "command.research.output.more-entries";

    public static final String COMMAND_RESEARCH_COMPLETED = "command.research.completed";

    public static final String COMMAND_RESEARCH_LOADING_ONE = "command.research.loading.one";

    public static final String COMMAND_RESEARCH_LOADING_TWO = "command.research.loading.two";

    public static final String COMMAND_RESEARCH_LOADING_THREE = "command.research.loading.three";

    public static final String COMMAND_RESEARCH_LOADING_TIMEOUT = "command.research.loading.timeout";

    public static final String COMMAND_RESEARCH_BUTTON_SATISFIED = "command.research.button.satisfied";

    public static final String COMMAND_RESEARCH_BUTTON_MORE = "command.research.button.more";

    public static final String COMMAND_INVALID = "command.invalid";

    public static final String COMMAND_NOT_AVAILABLE = "command.not-available";

    @Autowired
    private MessageSource messageSource;

    private MessageSourceAccessor accessor;

    @PostConstruct
    private void init() {
        accessor = new MessageSourceAccessor(messageSource, Locale.forLanguageTag("pt-BR"));
    }

    public String get(String code) {
        return accessor.getMessage(code);
    }

    public String get(String code, Object... args) {
        return accessor.getMessage(code, args);
    }
}

18 Source : SpringSecurityWebAuthnMessageSourceTest.java
with Apache License 2.0
from webauthn4j

@Test
public void getAccessor_test() {
    MessageSourceAccessor accessor = SpringSecurityWebAuthnMessageSource.getAccessor();
    replacedertThat(accessor).isNotNull();
}

18 Source : WebAuthnAuthenticationProvider.java
with Apache License 2.0
from webauthn4j

/**
 * An {@link AuthenticationProvider} implementation for processing {@link WebAuthnreplacedertionAuthenticationToken}
 */
public clreplaced WebAuthnAuthenticationProvider implements AuthenticationProvider {

    // ~ Instance fields
    // ================================================================================================
    protected final Log logger = LogFactory.getLog(getClreplaced());

    protected final MessageSourceAccessor messages = SpringSecurityWebAuthnMessageSource.getAccessor();

    private final WebAuthnAuthenticatorService authenticatorService;

    private final WebAuthnManager webAuthnManager;

    private boolean hideCredentialIdNotFoundExceptions = true;

    // ~ Constructor
    // ========================================================================================================
    public WebAuthnAuthenticationProvider(WebAuthnAuthenticatorService authenticatorService, WebAuthnManager webAuthnManager) {
        replacedert.notNull(authenticatorService, "authenticatorService must not be null");
        replacedert.notNull(webAuthnManager, "webAuthnManager must not be null");
        this.authenticatorService = authenticatorService;
        this.webAuthnManager = webAuthnManager;
    }

    // ~ Methods
    // ========================================================================================================
    /**
     * {@inheritDoc}
     */
    @Override
    public Authentication authenticate(Authentication authentication) {
        if (!supports(authentication.getClreplaced())) {
            throw new IllegalArgumentException("Only WebAuthnreplacedertionAuthenticationToken is supported, " + authentication.getClreplaced() + " was attempted");
        }
        WebAuthnreplacedertionAuthenticationToken authenticationToken = (WebAuthnreplacedertionAuthenticationToken) authentication;
        WebAuthnAuthenticationRequest credentials = authenticationToken.getCredentials();
        if (credentials == null) {
            logger.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(messages.getMessage("WebAuthnAuthenticationProvider.badCredentials", "Bad credentials"));
        }
        byte[] credentialId = credentials.getCredentialId();
        WebAuthnAuthenticator webAuthnAuthenticator = retrieveAuthenticator(credentialId);
        doAuthenticate(authenticationToken, webAuthnAuthenticator);
        authenticatorService.updateCounter(credentialId, webAuthnAuthenticator.getCounter());
        return createSuccessAuthentication(authenticationToken, webAuthnAuthenticator);
    }

    protected Authentication createSuccessAuthentication(WebAuthnreplacedertionAuthenticationToken authenticationToken, WebAuthnAuthenticator webAuthnAuthenticator) {
        Object principal = webAuthnAuthenticator.getUserPrincipal();
        Collection<? extends GrantedAuthority> authorities = null;
        if (principal instanceof UserDetails) {
            authorities = ((UserDetails) principal).getAuthorities();
        }
        WebAuthnAuthenticationToken webAuthnAuthenticationToken = new WebAuthnAuthenticationToken(principal, authenticationToken.getCredentials(), authorities);
        webAuthnAuthenticationToken.setDetails(authenticationToken.getDetails());
        return webAuthnAuthenticationToken;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean supports(Clreplaced<?> authentication) {
        return WebAuthnreplacedertionAuthenticationToken.clreplaced.isreplacedignableFrom(authentication);
    }

    void doAuthenticate(WebAuthnreplacedertionAuthenticationToken authenticationToken, WebAuthnAuthenticator webAuthnAuthenticator) {
        WebAuthnAuthenticationRequest request = authenticationToken.getCredentials();
        WebAuthnAuthenticationParameters parameters = authenticationToken.getParameters();
        AuthenticationRequest authenticationRequest = new AuthenticationRequest(request.getCredentialId(), request.getAuthenticatorData(), request.getClientDataJSON(), request.getClientExtensionsJSON(), request.getSignature());
        AuthenticationParameters authenticationParameters = new AuthenticationParameters(parameters.getServerProperty(), new AuthenticatorImpl(webAuthnAuthenticator.getAttestedCredentialData(), webAuthnAuthenticator.getAttestationStatement(), webAuthnAuthenticator.getCounter(), webAuthnAuthenticator.getTransports(), webAuthnAuthenticator.getClientExtensions(), webAuthnAuthenticator.getAuthenticatorExtensions()), parameters.isUserVerificationRequired(), parameters.isUserPresenceRequired());
        try {
            webAuthnManager.validate(authenticationRequest, authenticationParameters);
        } catch (WebAuthnException e) {
            throw ExceptionUtil.wrapWithAuthenticationException(e);
        }
    }

    public boolean isHideCredentialIdNotFoundExceptions() {
        return hideCredentialIdNotFoundExceptions;
    }

    /**
     * By default the <code>WebAuthnAuthenticationProvider</code> throws a
     * <code>BadCredentialsException</code> if a credentialId is not found or the credential is
     * incorrect. Setting this property to <code>false</code> will cause
     * <code>CredentialIdNotFoundException</code>s to be thrown instead for the former. Note
     * this is considered less secure than throwing <code>BadCredentialsException</code>
     * for both exceptions.
     *
     * @param hideCredentialIdNotFoundExceptions set to <code>false</code> if you wish
     *                                           <code>CredentialIdNotFoundException</code>s to be thrown instead of the non-specific
     *                                           <code>BadCredentialsException</code> (defaults to <code>true</code>)
     */
    public void setHideCredentialIdNotFoundExceptions(boolean hideCredentialIdNotFoundExceptions) {
        this.hideCredentialIdNotFoundExceptions = hideCredentialIdNotFoundExceptions;
    }

    WebAuthnAuthenticator retrieveAuthenticator(byte[] credentialId) {
        WebAuthnAuthenticator webAuthnAuthenticator;
        try {
            webAuthnAuthenticator = authenticatorService.loadAuthenticatorByCredentialId(credentialId);
        } catch (CredentialIdNotFoundException notFound) {
            if (hideCredentialIdNotFoundExceptions) {
                throw new BadCredentialsException(messages.getMessage("WebAuthnAuthenticationProvider.badCredentials", "Bad credentials"));
            } else {
                throw notFound;
            }
        } catch (Exception repositoryProblem) {
            throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
        }
        if (webAuthnAuthenticator == null) {
            throw new InternalAuthenticationServiceException("WebAuthnAuthenticatorService returned null, which is an interface contract violation");
        }
        return webAuthnAuthenticator;
    }
}

18 Source : KeycloakOAuth2ErrorConverter.java
with Apache License 2.0
from penggle

@Override
public OAuth2Error convert(Map<String, String> parameters) {
    MessageSourceAccessor messageSourceAccessor = ApplicationConstants.DEFAULT_MESSAGE_SOURCE_ACCESSOR.get();
    String errorCode = parameters.get(OAuth2ParameterNames.ERROR);
    String errorDescription = parameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION);
    String errorUri = parameters.get(OAuth2ParameterNames.ERROR_URI);
    if ("invalid_grant".equals(errorCode) && errorDescription != null && errorDescription.contains("Invalid user credentials")) {
        errorDescription = messageSourceAccessor.getMessage("spring.security.oauth2.error.invalid_user_credentials", errorDescription);
    } else if ("Incorrect result size: expected 1, actual 0".equals(errorCode)) {
        errorCode = "invalid_grant";
        errorDescription = messageSourceAccessor.getMessage("spring.security.oauth2.error.invalid_user_credentials", errorDescription);
    } else if ("unauthorized_client".equals(errorCode) && errorDescription != null && errorDescription.contains("Invalid client secret")) {
        errorDescription = messageSourceAccessor.getMessage("spring.security.oauth2.error.invalid_client_secret", errorDescription);
    }
    return new OAuth2Error(errorCode, errorDescription, errorUri);
}

18 Source : MessageSourceResolvableHttpMessageConverterTests.java
with Apache License 2.0
from odrotbohm

/**
 * @author Oliver Drotbohm
 */
@ExtendWith(MockitoExtension.clreplaced)
clreplaced MessageSourceResolvableHttpMessageConverterTests {

    @Mock
    MessageSourceAccessor accessor;

    @Test
    void supportsMessageSourceResolvableForTextPlain() throws Exception {
        HttpMessageConverter<MessageSourceResolvable> converter = new MessageSourceResolvableHttpMessageConverter(accessor);
        replacedertThat(converter.canWrite(MessageSourceResolvable.clreplaced, MediaType.TEXT_PLAIN)).isTrue();
        replacedertThat(converter.canRead(MessageSourceResolvable.clreplaced, MediaType.TEXT_PLAIN)).isFalse();
    }

    @Test
    void translatesMessageSourceResolvable() throws Exception {
        MessageSourceResolvable message = I18nedMessage.of("some.code");
        String expected = "Translated";
        MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
        when(accessor.getMessage(message)).thenReturn(expected);
        new MessageSourceResolvableHttpMessageConverter(accessor).write(message, MediaType.TEXT_PLAIN, outputMessage);
        replacedertThat(outputMessage.getBodyreplacedtring()).isEqualTo(expected);
    }

    @Test
    void doesNotSupportReadingInput() {
        replacedertThatExceptionOfType(UnsupportedOperationException.clreplaced).isThrownBy(() -> new MessageSourceResolvableHttpMessageConverter(accessor).read(MessageSourceResolvable.clreplaced, new MockHttpInputMessage("".getBytes())));
    }
}

18 Source : PasswordPolicyMessageResolver.java
with Apache License 2.0
from MaxKeyTop

public clreplaced PreplacedwordPolicyMessageResolver implements MessageResolver {

    /**
     * A accessor for Spring's {@link MessageSource}
     */
    private final MessageSourceAccessor messageSourceAccessor;

    /**
     * The {@link MessageResolver} for fallback
     */
    private final MessageResolver fallbackMessageResolver = new PropertiesMessageResolver();

    /**
     * Create a new instance with the locale replacedociated with the current thread.
     * @param messageSource a message source managed by spring
     */
    public PreplacedwordPolicyMessageResolver(final MessageSource messageSource) {
        this.messageSourceAccessor = new MessageSourceAccessor(messageSource);
    }

    /**
     * Create a new instance with the specified locale.
     * @param messageSource a message source managed by spring
     * @param locale the locale to use for message access
     */
    public PreplacedwordPolicyMessageResolver(final MessageSource messageSource, final Locale locale) {
        this.messageSourceAccessor = new MessageSourceAccessor(messageSource, locale);
    }

    /**
     * Resolves the message for the supplied rule result detail using Spring's {@link MessageSource}.
     * (If the message can't retrieve from a {@link MessageSource}, return default message provided by preplaceday)
     * @param detail rule result detail
     * @return message for the detail error code
     */
    @Override
    public String resolve(final RuleResultDetail detail) {
        try {
            return this.messageSourceAccessor.getMessage("PreplacedwordPolicy." + detail.getErrorCode(), detail.getValues());
        } catch (NoSuchMessageException e) {
            return this.fallbackMessageResolver.resolve(detail);
        }
    }
}

18 Source : RestAuthenticationEntryPoint.java
with MIT License
from liangzai-cool

/**
 * 这个入口点其实仅仅是被ExceptionTranslationFilter引用
 * 由此入口决定redirect、forward的操作
 * @author XueLiang
 * @date 2017年3月1日 上午10:20:39
 * @version 1.0
 */
public clreplaced RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final Logger LOGGER = LogManager.getLogger(RestAuthenticationEntryPoint.clreplaced);

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        LOGGER.warn("Authentication Failed: " + authException.getMessage());
        JSONResponse jsonResponse = new JSONResponse();
        jsonResponse.addError(DefaultException.Error.invalid_parameter.name(), messages.getMessage("AbstractAccessDecisionManager.accessDenied"));
        response.addHeader("Content-type", "application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(jsonResponse.toString());
        printWriter.flush();
        printWriter.close();
    }
}

18 Source : SmsAuthenticationProvider.java
with MIT License
from leecho

/**
 * @author LIQIU
 * created on 2018-11-19
 */
public clreplaced SmsAuthenticationProvider implements AuthenticationProvider {

    protected final Log logger = LogFactory.getLog(getClreplaced());

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    private SmsUserDetailsService smsUserDetailsService;

    private CredentialService credentialService;

    private UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks();

    private UserDetailsChecker postAuthenticationChecks = new DefaultPostAuthenticationChecks();

    public SmsAuthenticationProvider(SmsUserDetailsService smsUserDetailsService, CredentialService credentialService) {
        this.smsUserDetailsService = smsUserDetailsService;
        this.credentialService = credentialService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsAuthenticationToken smsAuthenticationToken = (SmsAuthenticationToken) authentication;
        CredentialValidation validate = new CredentialValidation();
        validate.setPrincipal((String) smsAuthenticationToken.getPrincipal());
        validate.setToken(smsAuthenticationToken.getToken());
        validate.setCredential((String) smsAuthenticationToken.getCredentials());
        validate.setIgnoreCase(false);
        // 判断是否匹配
        if (!credentialService.validate(validate)) {
            throw new BadCredentialsException("The Credential is not match");
        }
        UserDetails user;
        try {
            // 通过手机号获取用户
            user = smsUserDetailsService.loadByPhoneNumber(String.valueOf(authentication.getPrincipal()));
        } catch (UsernameNotFoundException notFound) {
            logger.debug("User '" + authentication.getName() + "' not found");
            throw notFound;
        }
        replacedert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
        preAuthenticationChecks.check(user);
        postAuthenticationChecks.check(user);
        return this.createSuccessAuthentication(user, authentication, user);
    }

    protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
        SmsAuthenticationToken result = new SmsAuthenticationToken(principal, user.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Clreplaced<?> authentication) {
        return authentication.isreplacedignableFrom(SmsAuthenticationToken.clreplaced);
    }

    private clreplaced DefaultPreAuthenticationChecks implements UserDetailsChecker {

        @Override
        public void check(UserDetails user) {
            if (!user.isAccountNonLocked()) {
                logger.debug("User account is locked");
                throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
            }
            if (!user.isEnabled()) {
                logger.debug("User account is disabled");
                throw new DisabledException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
            }
            if (!user.isAccountNonExpired()) {
                logger.debug("User account is expired");
                throw new AccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
            }
        }
    }

    private clreplaced DefaultPostAuthenticationChecks implements UserDetailsChecker {

        @Override
        public void check(UserDetails user) {
            if (!user.isCredentialsNonExpired()) {
                logger.debug("User account credentials have expired");
                throw new CredentialsExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired"));
            }
        }
    }
}

18 Source : AppConfigServlet.java
with Apache License 2.0
from i-novus-llc

private Map<String, String> getMessages() {
    MessageSourceAccessor accessor = new MessageSourceAccessor(messageSource);
    Locale locale = LocaleContextHolder.getLocale();
    Set<String> messagesBaseNames = messageSource.getBasenameSet();
    Map<String, String> map = new TreeMap<>();
    for (String baseName : messagesBaseNames) {
        Set<String> keys = messageSource.getKeys(baseName, locale);
        for (String key : keys) {
            map.put(key, accessor.getMessage(key, locale));
        }
    }
    return map;
}

18 Source : VotingSubjectEnricherTest.java
with MIT License
from FAForever

@ExtendWith(MockitoExtension.clreplaced)
public clreplaced VotingSubjectEnricherTest {

    private VotingSubjectEnricher instance;

    @Mock
    private MessageSourceAccessor messageSourceAccessor;

    @BeforeEach
    public void setUp() {
        instance = new VotingSubjectEnricher();
        instance.init(messageSourceAccessor);
    }

    @Test
    public void testQuestionEnhancing() {
        VotingQuestion votingQuestion = new VotingQuestion();
        votingQuestion.setAlternativeQuestion(true);
        votingQuestion.setQuestionKey("abc");
        VotingSubject votingSubject = new VotingSubject();
        votingSubject.setEndOfVoteTime(OffsetDateTime.MIN);
        votingSubject.setRevealWinner(true);
        votingQuestion.setVotingSubject(votingSubject);
        Vote vote1 = new Vote();
        Player player1 = new Player();
        vote1.setPlayer(player1);
        Vote vote2 = new Vote();
        Player player2 = new Player();
        vote2.setPlayer(player2);
        Vote vote3 = new Vote();
        Player player3 = new Player();
        vote1.setPlayer(player3);
        Vote vote4 = new Vote();
        Player player4 = new Player();
        vote1.setPlayer(player4);
        Vote vote5 = new Vote();
        Player player5 = new Player();
        vote1.setPlayer(player5);
        VotingChoice votingChoice = new VotingChoice();
        votingChoice.setId(1);
        votingChoice.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice, votingQuestion, vote1, 0);
        addAnswerToChoice(votingChoice, votingQuestion, vote2, 0);
        VotingChoice votingChoice2 = new VotingChoice();
        votingChoice2.setId(2);
        votingChoice2.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice2, votingQuestion, vote3, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote4, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote5, 1);
        VotingChoice votingChoice3 = new VotingChoice();
        votingChoice3.setId(3);
        votingChoice3.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice2, votingQuestion, vote5, 0);
        instance.calculateWinners(votingQuestion);
        replacedertThat(votingQuestion.getWinners(), hasItem(votingChoice2));
    }

    @Test
    public void testQuestionEnhancingDraw() {
        VotingQuestion votingQuestion = new VotingQuestion();
        votingQuestion.setId(1);
        votingQuestion.setAlternativeQuestion(true);
        votingQuestion.setQuestionKey("abc");
        VotingSubject votingSubject = new VotingSubject();
        votingSubject.setId(1);
        votingSubject.setEndOfVoteTime(OffsetDateTime.MIN);
        votingSubject.setRevealWinner(true);
        votingQuestion.setVotingSubject(votingSubject);
        Vote vote1 = (Vote) new Vote().setId(1);
        Player player1 = (Player) new Player().setId(1);
        vote1.setPlayer(player1);
        Vote vote2 = (Vote) new Vote().setId(2);
        Player player2 = (Player) new Player().setId(2);
        vote2.setPlayer(player2);
        Vote vote3 = (Vote) new Vote().setId(3);
        Player player3 = (Player) new Player().setId(3);
        vote3.setPlayer(player3);
        Vote vote4 = (Vote) new Vote().setId(4);
        Player player4 = (Player) new Player().setId(4);
        vote4.setPlayer(player4);
        Vote vote5 = (Vote) new Vote().setId(5);
        Player player5 = (Player) new Player().setId(5);
        vote5.setPlayer(player5);
        Vote vote6 = (Vote) new Vote().setId(6);
        Player player6 = (Player) new Player().setId(6);
        vote6.setPlayer(player6);
        VotingChoice votingChoice = new VotingChoice();
        votingChoice.setId(1);
        votingChoice.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice, votingQuestion, vote1, 0);
        addAnswerToChoice(votingChoice, votingQuestion, vote2, 0);
        addAnswerToChoice(votingChoice, votingQuestion, vote6, 0);
        VotingChoice votingChoice2 = new VotingChoice();
        votingChoice2.setId(2);
        votingChoice2.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice2, votingQuestion, vote4, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote3, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote5, 1);
        VotingChoice votingChoice3 = new VotingChoice();
        votingChoice3.setId(3);
        votingChoice3.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice3, votingQuestion, vote5, 0);
        instance.calculateWinners(votingQuestion);
        replacedertThat(votingQuestion.getWinners(), Matchers.allOf(hasItem(votingChoice2), hasItem(votingChoice)));
    }

    @Test
    public void testQuestionEnhancingDrawWithBlankOption() {
        VotingQuestion votingQuestion = new VotingQuestion();
        votingQuestion.setId(1);
        votingQuestion.setAlternativeQuestion(true);
        votingQuestion.setQuestionKey("abc");
        VotingSubject votingSubject = new VotingSubject();
        votingSubject.setId(1);
        votingSubject.setEndOfVoteTime(OffsetDateTime.MIN);
        votingSubject.setRevealWinner(true);
        votingQuestion.setVotingSubject(votingSubject);
        Vote vote1 = (Vote) new Vote().setId(1);
        Player player1 = (Player) new Player().setId(1);
        vote1.setPlayer(player1);
        Vote vote2 = (Vote) new Vote().setId(2);
        Player player2 = (Player) new Player().setId(2);
        vote2.setPlayer(player2);
        Vote vote3 = (Vote) new Vote().setId(3);
        Player player3 = (Player) new Player().setId(3);
        vote3.setPlayer(player3);
        Vote vote4 = (Vote) new Vote().setId(4);
        Player player4 = (Player) new Player().setId(4);
        vote4.setPlayer(player4);
        Vote vote5 = (Vote) new Vote().setId(5);
        Player player5 = (Player) new Player().setId(5);
        vote5.setPlayer(player5);
        Vote vote6 = (Vote) new Vote().setId(6);
        Player player6 = (Player) new Player().setId(6);
        vote6.setPlayer(player6);
        Vote vote7 = (Vote) new Vote().setId(7);
        Player player7 = (Player) new Player().setId(7);
        vote6.setPlayer(player7);
        VotingChoice votingChoice = new VotingChoice();
        votingChoice.setId(1);
        votingChoice.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice, votingQuestion, vote1, 0);
        addAnswerToChoice(votingChoice, votingQuestion, vote2, 0);
        addAnswerToChoice(votingChoice, votingQuestion, vote6, 0);
        VotingChoice votingChoice2 = new VotingChoice();
        votingChoice2.setId(2);
        votingChoice2.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice2, votingQuestion, vote4, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote3, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote5, 0);
        VotingChoice votingChoice3 = new VotingChoice();
        votingChoice3.setId(3);
        votingChoice3.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice3, votingQuestion, vote7, 0);
        addAnswerToChoice(null, votingQuestion, vote7, 1);
        instance.calculateWinners(votingQuestion);
        replacedertThat(votingQuestion.getWinners(), Matchers.allOf(hasItem(votingChoice2), hasItem(votingChoice)));
    }

    @Test
    public void testQuestionEnhancingDrawWithTwoCandidatesGettingEliminatedAtTheSameTime() {
        VotingQuestion votingQuestion = new VotingQuestion();
        votingQuestion.setId(1);
        votingQuestion.setAlternativeQuestion(true);
        votingQuestion.setQuestionKey("abc");
        VotingSubject votingSubject = new VotingSubject();
        votingSubject.setId(1);
        votingSubject.setEndOfVoteTime(OffsetDateTime.MIN);
        votingSubject.setRevealWinner(true);
        votingQuestion.setVotingSubject(votingSubject);
        Vote vote1 = (Vote) new Vote().setId(1);
        Player player1 = (Player) new Player().setId(1);
        vote1.setPlayer(player1);
        Vote vote2 = (Vote) new Vote().setId(2);
        Player player2 = (Player) new Player().setId(2);
        vote2.setPlayer(player2);
        Vote vote3 = (Vote) new Vote().setId(3);
        Player player3 = (Player) new Player().setId(3);
        vote3.setPlayer(player3);
        Vote vote4 = (Vote) new Vote().setId(4);
        Player player4 = (Player) new Player().setId(4);
        vote4.setPlayer(player4);
        Vote vote5 = (Vote) new Vote().setId(5);
        Player player5 = (Player) new Player().setId(5);
        vote5.setPlayer(player5);
        Vote vote6 = (Vote) new Vote().setId(6);
        Player player6 = (Player) new Player().setId(6);
        vote6.setPlayer(player6);
        Vote vote7 = (Vote) new Vote().setId(7);
        Player player7 = (Player) new Player().setId(7);
        vote6.setPlayer(player7);
        VotingChoice votingChoice = new VotingChoice();
        votingChoice.setId(1);
        votingChoice.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice, votingQuestion, vote1, 0);
        addAnswerToChoice(votingChoice, votingQuestion, vote2, 0);
        addAnswerToChoice(votingChoice, votingQuestion, vote3, 1);
        VotingChoice votingChoice2 = new VotingChoice();
        votingChoice2.setId(2);
        votingChoice2.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice2, votingQuestion, vote3, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote4, 0);
        addAnswerToChoice(votingChoice2, votingQuestion, vote1, 1);
        VotingChoice votingChoice3 = new VotingChoice();
        votingChoice3.setId(3);
        votingChoice3.setVotingQuestion(votingQuestion);
        addAnswerToChoice(votingChoice3, votingQuestion, vote5, 0);
        addAnswerToChoice(votingChoice3, votingQuestion, vote6, 0);
        addAnswerToChoice(votingChoice3, votingQuestion, vote7, 0);
        instance.calculateWinners(votingQuestion);
        replacedertThat(votingQuestion.getWinners(), is(Collections.singletonList(votingChoice3)));
    }

    private void addAnswerToChoice(VotingChoice votingChoice, VotingQuestion votingQuestion, Vote vote, int alternativeOrdinal) {
        VotingAnswer votingAnswer = new VotingAnswer();
        votingAnswer.setAlternativeOrdinal(alternativeOrdinal);
        votingAnswer.setVote(vote);
        votingAnswer.setVotingChoice(votingChoice);
        if (vote.getVotingAnswers() != null) {
            vote.getVotingAnswers().add(votingAnswer);
        } else {
            vote.setVotingAnswers(new HashSet<>(Collections.singleton(votingAnswer)));
        }
        if (votingChoice != null) {
            if (votingChoice.getVotingAnswers() != null) {
                votingChoice.getVotingAnswers().add(votingAnswer);
            } else {
                votingChoice.setVotingAnswers(new HashSet<>(Collections.singleton(votingAnswer)));
            }
            if (votingQuestion.getVotingChoices() != null) {
                votingQuestion.getVotingChoices().add(votingChoice);
            } else {
                votingQuestion.setVotingChoices(new HashSet<>(Collections.singleton(votingChoice)));
            }
        }
    }
}

18 Source : TutorialEnricherTest.java
with MIT License
from FAForever

@ExtendWith(MockitoExtension.clreplaced)
public clreplaced TutorialEnricherTest {

    private TutorialEnricherListener instance;

    @Mock
    private MessageSourceAccessor messageSourceAccessor;

    @BeforeEach
    public void setUp() {
        FafApiProperties fafApiProperties = new FafApiProperties();
        fafApiProperties.getTutorial().setThumbnailUrlFormat("http://example.com/%s");
        instance = new TutorialEnricherListener();
        instance.init(fafApiProperties, messageSourceAccessor);
    }

    @Test
    public void enrich() {
        Tutorial tutorial = new Tutorial();
        tutorial.setImage("abc.png");
        instance.enrich(tutorial);
        replacedertThat(tutorial.getImageUrl(), is("http://example.com/abc.png"));
    }
}

18 Source : VotingSubjectEnricher.java
with MIT License
from FAForever

@Component
public clreplaced VotingSubjectEnricher {

    private static MessageSourceAccessor messageSourceAccessor;

    @Inject
    public void init(MessageSourceAccessor messageSourceAccessor) {
        VotingSubjectEnricher.messageSourceAccessor = messageSourceAccessor;
    }

    @PreUpdate
    public void preUpdate(VotingSubject votingSubject) {
        updateWinners(votingSubject);
    }

    private void updateWinners(VotingSubject votingSubject) {
        votingSubject.getVotingQuestions().forEach(this::calculateWinners);
    }

    @PostLoad
    public void enhance(VotingSubject votingSubject) {
        votingSubject.setNumberOfVotes(votingSubject.getVotes().size());
        votingSubject.setSubject(messageSourceAccessor.getMessage(votingSubject.getSubjectKey()));
        String descriptionKey = votingSubject.getDescriptionKey();
        if (!Strings.isNullOrEmpty(descriptionKey)) {
            votingSubject.setDescription(messageSourceAccessor.getMessage(votingSubject.getDescriptionKey()));
        }
    }

    @VisibleForTesting
    void calculateWinners(VotingQuestion votingQuestion) {
        VotingSubject votingSubject = votingQuestion.getVotingSubject();
        boolean ended = votingSubject.getEndOfVoteTime().isBefore(OffsetDateTime.now());
        List<VotingChoice> winners = votingQuestion.getWinners();
        if ((winners == null || winners.isEmpty()) && ended && votingSubject.getRevealWinner()) {
            votingQuestion.setWinners(getWinners(votingQuestion));
        } else {
            votingQuestion.setWinners(Collections.emptyList());
        }
    }

    private List<VotingChoice> getWinners(VotingQuestion votingQuestion) {
        if (!votingQuestion.isAlternativeQuestion()) {
            OptionalInt max = votingQuestion.getVotingChoices().stream().mapToInt(value -> value.getVotingAnswers().size()).max();
            if (max.isPresent()) {
                return votingQuestion.getVotingChoices().stream().filter(votingChoice -> votingChoice.getVotingAnswers().size() == max.getAsInt()).collect(toList());
            }
            return Collections.emptyList();
        }
        // All the answers sorted by their choice, but only those that are the 1st choice
        Map<VotingChoice, List<VotingAnswer>> votersByChoice = votingQuestion.getVotingChoices().stream().collect(Collectors.toMap(Function.idenreplacedy(), choice -> new ArrayList<>(choice.getVotingAnswers().stream().filter(votingAnswer -> votingAnswer.getAlternativeOrdinal() == 0).collect(toList()))));
        while (votersByChoice.size() > 1) {
            OptionalInt min = votersByChoice.values().stream().mapToInt(List::size).min();
            List<VotingChoice> candidatesToEliminate = votersByChoice.entrySet().stream().filter(votingChoiceListEntry -> votingChoiceListEntry.getValue().size() == min.getAsInt()).map(Entry::getKey).collect(toList());
            if (candidatesToEliminate.size() == votersByChoice.size()) {
                // We got a problem here, we would eliminate all the candidates if we went on normally
                return candidatesToEliminate;
            }
            candidatesToEliminate.forEach(candidate -> {
                List<VotingAnswer> votingAnswersForCandidate = votersByChoice.get(candidate);
                // Lets distribute the answers of the candidate that is eliminated
                votingAnswersForCandidate.forEach(votingAnswer -> {
                    moveOnToTheNextAnswer(votersByChoice, votingAnswer);
                });
                votersByChoice.remove(candidate);
            });
        }
        Optional<Entry<VotingChoice, List<VotingAnswer>>> first = votersByChoice.entrySet().stream().findFirst();
        return first.map(votingChoiceListEntry -> Collections.singletonList(votingChoiceListEntry.getKey())).orElse(Collections.emptyList());
    }

    private void moveOnToTheNextAnswer(Map<VotingChoice, List<VotingAnswer>> votersByChoice, VotingAnswer votingAnswer) {
        int newAlternativeOrdinal = votingAnswer.getAlternativeOrdinal() + 1;
        votingAnswer.getVote().getVotingAnswers().stream().filter(votingAnswerFilter -> votingAnswerFilter.getVotingChoice() != null && Objects.equals(votingAnswerFilter.getVotingChoice().getVotingQuestion(), votingAnswer.getVotingChoice().getVotingQuestion()) && votingAnswerFilter.getAlternativeOrdinal() == newAlternativeOrdinal).findFirst().ifPresent(newVotingAnswer -> {
            VotingChoice votingChoiceToBeRedistributed = newVotingAnswer.getVotingChoice();
            List<VotingAnswer> votingAnswersOfNewChoice = votersByChoice.get(votingChoiceToBeRedistributed);
            if (votingAnswersOfNewChoice == null) {
                /*
          We eliminated two choices/candidates at once and this is the second one.
          Apparently one voter voted the candidate we eliminated before as the next answer.
          So we need to skip this answer and go straight to the next one.
           */
                moveOnToTheNextAnswer(votersByChoice, newVotingAnswer);
                return;
            }
            votingAnswersOfNewChoice.add(newVotingAnswer);
        });
    }
}

18 Source : VotingSubjectEnricher.java
with MIT License
from FAForever

@Inject
public void init(MessageSourceAccessor messageSourceAccessor) {
    VotingSubjectEnricher.messageSourceAccessor = messageSourceAccessor;
}

18 Source : VotingQuestionEnricher.java
with MIT License
from FAForever

@Component
public clreplaced VotingQuestionEnricher {

    private static MessageSourceAccessor messageSourceAccessor;

    @Inject
    public void init(MessageSourceAccessor messageSourceAccessor) {
        VotingQuestionEnricher.messageSourceAccessor = messageSourceAccessor;
    }

    @PostLoad
    public void enhance(VotingQuestion votingQuestion) {
        if (votingQuestion.getVotingChoices() != null) {
            int numberOfAnswers = votingQuestion.getVotingChoices().stream().mapToInt(votingChoice -> {
                if (votingChoice.getVotingAnswers() == null) {
                    return 0;
                }
                return votingChoice.getVotingAnswers().size();
            }).sum();
            votingQuestion.setNumberOfAnswers(numberOfAnswers);
        }
        votingQuestion.setQuestion(messageSourceAccessor.getMessage(votingQuestion.getQuestionKey()));
        if (!Strings.isNullOrEmpty(votingQuestion.getDescriptionKey())) {
            votingQuestion.setDescription(messageSourceAccessor.getMessage(votingQuestion.getDescriptionKey()));
        }
    }
}

18 Source : VotingChoiceEnricher.java
with MIT License
from FAForever

@Component
public clreplaced VotingChoiceEnricher {

    private static MessageSourceAccessor messageSourceAccessor;

    @Inject
    public void init(MessageSourceAccessor messageSourceAccessor) {
        VotingChoiceEnricher.messageSourceAccessor = messageSourceAccessor;
    }

    @PostLoad
    public void enhance(VotingChoice votingChoice) {
        Boolean revealWinner = votingChoice.getVotingQuestion().getVotingSubject().getRevealWinner();
        Set<VotingAnswer> votingAnswers = votingChoice.getVotingAnswers();
        votingChoice.setNumberOfAnswers(revealWinner && votingAnswers != null ? votingAnswers.size() : 0);
        votingChoice.setChoiceText(messageSourceAccessor.getMessage(votingChoice.getChoiceTextKey()));
        if (!Strings.isNullOrEmpty(votingChoice.getDescriptionKey())) {
            votingChoice.setDescription(messageSourceAccessor.getMessage(votingChoice.getDescriptionKey()));
        }
    }
}

18 Source : VotingChoiceEnricher.java
with MIT License
from FAForever

@Inject
public void init(MessageSourceAccessor messageSourceAccessor) {
    VotingChoiceEnricher.messageSourceAccessor = messageSourceAccessor;
}

18 Source : TutorialEnricherListener.java
with MIT License
from FAForever

@Component
public clreplaced TutorialEnricherListener {

    private static FafApiProperties fafApiProperties;

    private static MessageSourceAccessor messageSourceAccessor;

    @Inject
    public void init(FafApiProperties fafApiProperties, MessageSourceAccessor messageSourceAccessor) {
        TutorialEnricherListener.fafApiProperties = fafApiProperties;
        TutorialEnricherListener.messageSourceAccessor = messageSourceAccessor;
    }

    @PostLoad
    public void enrich(Tutorial tutorial) {
        if (!Strings.isNullOrEmpty(tutorial.getImage())) {
            tutorial.setImageUrl(String.format(fafApiProperties.getTutorial().getThumbnailUrlFormat(), tutorial.getImage()));
        }
        tutorial.setreplacedle(messageSourceAccessor.getMessage(tutorial.getreplacedleKey()));
        if (!Strings.isNullOrEmpty(tutorial.getDescriptionKey())) {
            tutorial.setDescription(messageSourceAccessor.getMessage(tutorial.getDescriptionKey()));
        }
    }
}

18 Source : TutorialEnricherListener.java
with MIT License
from FAForever

@Inject
public void init(FafApiProperties fafApiProperties, MessageSourceAccessor messageSourceAccessor) {
    TutorialEnricherListener.fafApiProperties = fafApiProperties;
    TutorialEnricherListener.messageSourceAccessor = messageSourceAccessor;
}

18 Source : TutorialCategoryEnricherListener.java
with MIT License
from FAForever

@Component
public clreplaced TutorialCategoryEnricherListener {

    private static MessageSourceAccessor messageSourceAccessor;

    @Inject
    public void init(MessageSourceAccessor messageSourceAccessor) {
        TutorialCategoryEnricherListener.messageSourceAccessor = messageSourceAccessor;
    }

    @PostLoad
    public void enrich(TutorialCategory tutorialCategory) {
        tutorialCategory.setCategory(messageSourceAccessor.getMessage(tutorialCategory.getCategoryKey()));
    }
}

18 Source : MessageComponent.java
with The Unlicense
from bmstefanski

@Component
public clreplaced MessageComponent {

    private final MessageSource messageSource;

    private MessageSourceAccessor messageSourceAccessor;

    @Autowired
    public MessageComponent(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @PostConstruct
    private void initialize() {
        this.messageSourceAccessor = new MessageSourceAccessor(this.messageSource);
    }

    public String get(String key, String... args) {
        return this.messageSourceAccessor.getMessage(key, args);
    }
}

17 Source : ExceptionHandlerAdvice.java
with Apache License 2.0
from zouzhirong

/**
 * 异常
 */
@ControllerAdvice
public clreplaced ExceptionHandlerAdvice extends ApplicationObjectSupport {

    private final Logger logger = LoggerFactory.getLogger(getClreplaced().getPackage().getName());

    private static MessageSourceAccessor messages;

    @Override
    protected void initApplicationContext() throws BeansException {
        messages = super.getMessageSourceAccessor();
    }

    /**
     * 处理ConfigException异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(ConfigException.clreplaced)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public ErrorResponse handleConfigException(HttpServletRequest request, ConfigException e) {
        // 记录exception
        error("ConfigException(code=" + e.getCode() + ")", request, e);
        String code = e.getCode();
        String msg = getMsg(code, e.getArgs());
        return newError(code, msg, e.getError());
    }

    /**
     * 处理未知异常
     *
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.clreplaced)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public ErrorResponse handleException(HttpServletRequest request, Exception e) {
        // 记录exception
        error("", request, e);
        String code = "exception";
        String msg = getMsg(code, null);
        return newError(code, msg, "");
    }

    /**
     * 打印异常日志
     *
     * @param msg
     * @param request
     * @param e
     */
    private void error(String msg, HttpServletRequest request, Exception e) {
        String uri = getRequestURI(request);
        String params = getRequestParams(request);
        // 记录exception
        if (e == null) {
            logger.warn(uri + " " + params + " " + msg);
        } else {
            logger.error(uri + " " + params + " " + msg, e);
        }
    }

    /**
     * 返回请求URI
     *
     * @param request
     * @return
     */
    private String getRequestURI(HttpServletRequest request) {
        return request.getRequestURI();
    }

    /**
     * 返回请求参数
     *
     * @param request
     * @return
     */
    private String getRequestParams(HttpServletRequest request) {
        Map<String, Object> parameterMap = new HashMap<>();
        // http request中的参数
        Map<String, Object> requestparameterMap = WebUtils.getParametersStartingWith(request, "");
        parameterMap.putAll(requestparameterMap);
        return JSON.toJSONString(parameterMap);
    }

    /**
     * 返回异常的错误描述
     *
     * @param code
     * @param args
     * @return
     */
    private String getMsg(String code, Object[] args) {
        String defaultMsg = messages.getMessage("error.code.exception");
        return messages.getMessage("error.code." + code, args, defaultMsg);
    }

    /**
     * 构造错误响应
     *
     * @param code
     * @param msg
     * @param error
     * @return
     */
    private ErrorResponse newError(String code, String msg, String error) {
        ErrorResponse e = new ErrorResponse();
        // 设置错误码
        e.setCode(code);
        // 设置错误提示
        if (msg != null) {
            e.setMsg(msg);
        }
        // 设置异常信息
        if (error != null) {
            e.setError(error);
        }
        return e;
    }
}

17 Source : PhoneAuthUserAuthenticationProvider.java
with MIT License
from zidoshare

/**
 * 手机号验证码用户认证
 *
 * @author zido
 */
public clreplaced PhoneAuthUserAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(PhoneAuthUserAuthenticationProvider.clreplaced);

    private UserDetailsService userDetailsService;

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    private CodeValidator codeValidator = new CustomCodeValidator();

    private PhoneCodeCache phoneCodeCache;

    private String keyPrefix = "";

    @Override
    protected UserDetails retrieveUser(String username, UsernamePreplacedwordAuthenticationToken authentication) throws AuthenticationException {
        try {
            UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
            if (loadedUser == null) {
                throw new InternalAuthenticationServiceException("UserDetailsService returned null, which is an interface contract violation");
            }
            return loadedUser;
        } catch (UsernameNotFoundException | InternalAuthenticationServiceException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
        }
    }

    @Override
    public boolean supports(Clreplaced<?> authentication) {
        return (PhoneCodeAuthenticationToken.clreplaced.isreplacedignableFrom(authentication));
    }

    @Override
    protected void doAfterPropertiesSet() {
        replacedert.notNull(this.phoneCodeCache, "phone code cache must be set");
        replacedert.notNull(this.userDetailsService, "A UserDetailsService must be set");
    }

    public void setCodeValidator(CodeValidator codeValidator) {
        this.codeValidator = codeValidator;
    }

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePreplacedwordAuthenticationToken authentication) throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            LOGGER.debug("Authentication failed: no credentials provided");
            throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
        String principal = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
        if (!codeValidator.validate(phoneCodeCache.getCode(getKey(principal)), authentication.getCredentials().toString())) {
            throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    public void setPhoneCodeCache(PhoneCodeCache phoneCodeCache) {
        this.phoneCodeCache = phoneCodeCache;
    }

    protected String getKey(String key) {
        return keyPrefix + key;
    }

    public void setKeyPrefix(String keyPrefix) {
        this.keyPrefix = keyPrefix;
    }
}

17 Source : CoffeeErrorAttributes.java
with MIT License
from zidoshare

@Order(Ordered.HIGHEST_PRECEDENCE)
public clreplaced CoffeeErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered {

    private static final String ERROR_ATTRIBUTE = CoffeeErrorAttributes.clreplaced.getName() + ".ERROR";

    private static final MessageSourceAccessor messages = CoffeeMessageSource.getAccessor();

    private final boolean includeException;

    private final HttpResponseBodyFactory factory;

    public CoffeeErrorAttributes(HttpResponseBodyFactory factory) {
        this(false, factory);
    }

    public CoffeeErrorAttributes(boolean includeException, HttpResponseBodyFactory factory) {
        this.includeException = includeException;
        this.factory = factory;
    }

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Integer status = getAttribute(webRequest, "javax.servlet.error.status_code");
        int code = CommonErrorCode.UNKNOWN;
        String message = null;
        Throwable error = getError(webRequest);
        if (error != null) {
            while (error instanceof ServletException && error.getCause() != null) {
                error = error.getCause();
            }
        }
        List<Object> errors = new ArrayList<>();
        if (error instanceof BindingResult) {
            errors.addAll(parseBindingResult((BindingResult) error));
        }
        if (error instanceof MethodArgumentNotValidException) {
            errors.addAll(parseBindingResult(((MethodArgumentNotValidException) error).getBindingResult()));
        }
        if (!errors.isEmpty()) {
            code = CommonErrorCode.VALIDATION_FAILED;
            message = messages.getMessage("VALIDATION_FAILED", "数据校验错误");
        }
        if (error != null) {
            Map<String, Object> detail = new HashMap<>();
            detail.put("message", StringUtils.hasText(error.getMessage()) ? error.getMessage() : messages.getMessage("UNKNOWN_ERROR", "未知异常"));
            while (error instanceof ServletException && error.getCause() != null) {
                error = error.getCause();
            }
            if (this.includeException) {
                detail.put("exception", error.getClreplaced().getName());
            }
            if (includeStackTrace) {
                detail.put("trace", getStackTrace(error));
            }
            message = error.getMessage();
            errors.add(detail);
        }
        if (status == null) {
            code = CommonErrorCode.UNKNOWN;
            message = messages.getMessage("UNKNOWN_ERROR", "未知异常");
        } else if (HttpStatus.NOT_FOUND.value() == status) {
            Map<String, Object> detail = new HashMap<>();
            detail.put("path", getAttribute(webRequest, "javax.servlet.error.request_uri"));
            errors.add(detail);
        }
        if (message == null) {
            try {
                message = HttpStatus.valueOf(status).getReasonPhrase();
            } catch (Exception ex) {
                message = messages.getMessage("UNKNOWN_ERROR", "未知异常");
            }
        }
        return factory.errorToMap(code, message, errors);
    }

    private String getStackTrace(Throwable error) {
        StringWriter stackTrace = new StringWriter();
        error.printStackTrace(new PrintWriter(stackTrace));
        stackTrace.flush();
        return stackTrace.toString();
    }

    @Override
    public Throwable getError(WebRequest webRequest) {
        Throwable exception = getAttribute(webRequest, ERROR_ATTRIBUTE);
        if (exception == null) {
            exception = getAttribute(webRequest, "javax.servlet.error.exception");
        }
        return exception;
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @SuppressWarnings("unchecked")
    private <T> T getAttribute(RequestAttributes requestAttributes, String name) {
        return (T) requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
    }

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        storeErrorAttributes(request, ex);
        return null;
    }

    private void storeErrorAttributes(HttpServletRequest request, Exception ex) {
        request.setAttribute(ERROR_ATTRIBUTE, ex);
    }
}

17 Source : WxAuthenticationProvider.java
with MIT License
from wells2333

/**
 * @author tangyi
 * @date 2019/07/05 19:34
 */
@Slf4j
@Data
public clreplaced WxAuthenticationProvider implements AuthenticationProvider {

    private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    private CustomUserDetailsService customUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WxAuthenticationToken wxAuthenticationToken = (WxAuthenticationToken) authentication;
        // 微信的code
        String principal = wxAuthenticationToken.getPrincipal().toString();
        UserDetails userDetails = customUserDetailsService.loadUserByWxCodeAndTenantCode(principal, TenantContextHolder.getTenantCode(), wxAuthenticationToken.getWxUser());
        if (userDetails == null) {
            log.debug("Authentication failed: no credentials provided");
            SpringContextHolder.publishEvent(new CustomAuthenticationFailureEvent(authentication, userDetails));
            throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
        }
        WxAuthenticationToken authenticationToken = new WxAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(wxAuthenticationToken.getDetails());
        SpringContextHolder.publishEvent(new CustomAuthenticationSuccessEvent(authentication, userDetails));
        return authenticationToken;
    }

    @Override
    public boolean supports(Clreplaced<?> authentication) {
        return WxAuthenticationToken.clreplaced.isreplacedignableFrom(authentication);
    }
}

17 Source : MobileAuthenticationProvider.java
with MIT License
from wells2333

/**
 * @author tangyi
 * @date 2019/6/22 21:00
 */
@Slf4j
@Data
public clreplaced MobileAuthenticationProvider implements AuthenticationProvider {

    private MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    private CustomUserDetailsService customUserDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
        String principal = mobileAuthenticationToken.getPrincipal().toString();
        UserDetails userDetails = customUserDetailsService.loadUserBySocialAndTenantCode(TenantContextHolder.getTenantCode(), principal, mobileAuthenticationToken.getMobileUser());
        if (userDetails == null) {
            log.debug("Authentication failed: no credentials provided");
            SpringContextHolder.publishEvent(new CustomAuthenticationFailureEvent(authentication, userDetails));
            throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.noopBindAccount", "Noop Bind Account"));
        }
        MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
        SpringContextHolder.publishEvent((new CustomAuthenticationSuccessEvent(authentication, userDetails)));
        return authenticationToken;
    }

    @Override
    public boolean supports(Clreplaced<?> authentication) {
        return MobileAuthenticationToken.clreplaced.isreplacedignableFrom(authentication);
    }
}

17 Source : AbstractOptionsEndpointFilter.java
with Apache License 2.0
from webauthn4j

public abstract clreplaced AbstractOptionsEndpointFilter extends GenericFilterBean {

    // ~ Instance fields
    // ================================================================================================
    /**
     * Url this filter should get activated on.
     */
    private String filterProcessesUrl;

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    protected JsonConverter jsonConverter;

    private AuthenticationTrustResolver trustResolver;

    // ~ Constructors
    // ===================================================================================================
    protected AbstractOptionsEndpointFilter(ObjectConverter objectConverter) {
        this.jsonConverter = objectConverter.getJsonConverter();
        this.trustResolver = new AuthenticationTrustResolverImpl();
    }

    // ~ Methods
    // ========================================================================================================
    @Override
    public void afterPropertiesSet() {
        checkConfig();
    }

    private void checkConfig() {
        replacedert.notNull(getFilterProcessesUrl(), "filterProcessesUrl must not be null");
        replacedert.notNull(jsonConverter, "jsonConverter must not be null");
        replacedert.notNull(trustResolver, "trustResolver must not be null");
    }

    public AuthenticationTrustResolver getTrustResolver() {
        return trustResolver;
    }

    public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
        this.trustResolver = trustResolver;
    }

    public String getFilterProcessesUrl() {
        return filterProcessesUrl;
    }

    public void setFilterProcessesUrl(String filterProcessesUrl) {
        this.filterProcessesUrl = filterProcessesUrl;
    }

    void writeResponse(HttpServletResponse httpServletResponse, Serializable options) throws IOException {
        String responseText = jsonConverter.writeValuereplacedtring(options);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(responseText);
    }

    void writeErrorResponse(HttpServletResponse httpServletResponse, RuntimeException e) throws IOException {
        Response errorResponse;
        int statusCode;
        if (e instanceof InsufficientAuthenticationException) {
            errorResponse = new ErrorResponse("Anonymous access is prohibited");
            statusCode = HttpServletResponse.SC_FORBIDDEN;
        } else {
            errorResponse = new ErrorResponse("The server encountered an internal error");
            statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
        String errorResponseText = jsonConverter.writeValuereplacedtring(errorResponse);
        httpServletResponse.setContentType("application/json");
        httpServletResponse.getWriter().print(errorResponseText);
        httpServletResponse.setStatus(statusCode);
    }

    protected Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (trustResolver.isAnonymous(authentication)) {
            return null;
        } else {
            return authentication;
        }
    }

    /**
     * The filter will be used in case the URL of the request contains the FILTER_URL.
     *
     * @param request request used to determine whether to enable this filter
     * @return true if this filter should be used
     */
    protected boolean processFilter(HttpServletRequest request) {
        return (request.getRequestURI().contains(getFilterProcessesUrl()));
    }
}

17 Source : AbstractUserDetailsAuthenticationProvider.java
with Apache License 2.0
from liuht777

/**
 * 自定义 AuthenticationProvider, 以使用自定义的 MyAuthenticationToken
 *
 * @author liuht
 * 2019/5/13 15:25
 * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
 */
@Slf4j
public abstract clreplaced AbstractUserDetailsAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    private UserCache userCache = new NullUserCache();

    private boolean forcePrincipalreplacedtring = false;

    protected boolean hideUserNotFoundExceptions = true;

    private UserDetailsChecker preAuthenticationChecks = new AbstractUserDetailsAuthenticationProvider.DefaultPreAuthenticationChecks();

    private UserDetailsChecker postAuthenticationChecks = new AbstractUserDetailsAuthenticationProvider.DefaultPostAuthenticationChecks();

    @Override
    public final void afterPropertiesSet() throws Exception {
        replacedert.notNull(this.userCache, "A user cache must be set");
        replacedert.notNull(this.messages, "A message source must be set");
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName();
        boolean cacheWasUsed = true;
        UserDetails user = this.userCache.getUserFromCache(username);
        if (user == null) {
            cacheWasUsed = false;
            try {
                user = this.retrieveUser(username, authentication);
            } catch (UsernameNotFoundException var6) {
                log.error("User \'" + username + "\' not found");
                if (this.hideUserNotFoundExceptions) {
                    throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
                }
                throw var6;
            }
            replacedert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
        }
        try {
            this.preAuthenticationChecks.check(user);
            this.additionalAuthenticationChecks(user, authentication);
        } catch (AuthenticationException var7) {
            if (!cacheWasUsed) {
                throw var7;
            }
            cacheWasUsed = false;
            user = this.retrieveUser(username, authentication);
            this.preAuthenticationChecks.check(user);
            this.additionalAuthenticationChecks(user, authentication);
        }
        this.postAuthenticationChecks.check(user);
        if (!cacheWasUsed) {
            this.userCache.putUserInCache(user);
        }
        Object principalToReturn = user;
        if (this.forcePrincipalreplacedtring) {
            principalToReturn = user.getUsername();
        }
        return this.createSuccessAuthentication(principalToReturn, authentication, user);
    }

    /**
     * 创建自定义的 Authentication 实现
     *
     * @param principal
     * @param authentication
     * @param user
     * @return
     */
    protected abstract Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user);

    /**
     * 校验 authentication 有效性
     *
     * @param userDetails
     * @param authentication
     * @throws AuthenticationException
     */
    protected abstract void additionalAuthenticationChecks(UserDetails userDetails, Authentication authentication) throws AuthenticationException;

    /**
     * 获取 UserDetails 详情
     *
     * @param principal
     * @param authentication
     * @return
     * @throws AuthenticationException
     */
    protected abstract UserDetails retrieveUser(String principal, Authentication authentication) throws AuthenticationException;

    public UserCache getUserCache() {
        return this.userCache;
    }

    public boolean isForcePrincipalreplacedtring() {
        return this.forcePrincipalreplacedtring;
    }

    public boolean isHideUserNotFoundExceptions() {
        return this.hideUserNotFoundExceptions;
    }

    public void setForcePrincipalreplacedtring(boolean forcePrincipalreplacedtring) {
        this.forcePrincipalreplacedtring = forcePrincipalreplacedtring;
    }

    public void setHideUserNotFoundExceptions(boolean hideUserNotFoundExceptions) {
        this.hideUserNotFoundExceptions = hideUserNotFoundExceptions;
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messages = new MessageSourceAccessor(messageSource);
    }

    public void setUserCache(UserCache userCache) {
        this.userCache = userCache;
    }

    protected UserDetailsChecker getPreAuthenticationChecks() {
        return this.preAuthenticationChecks;
    }

    public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) {
        this.preAuthenticationChecks = preAuthenticationChecks;
    }

    protected UserDetailsChecker getPostAuthenticationChecks() {
        return this.postAuthenticationChecks;
    }

    public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) {
        this.postAuthenticationChecks = postAuthenticationChecks;
    }

    private clreplaced DefaultPostAuthenticationChecks implements UserDetailsChecker {

        private DefaultPostAuthenticationChecks() {
        }

        @Override
        public void check(UserDetails user) {
            if (!user.isCredentialsNonExpired()) {
                log.debug("User account credentials have expired");
                throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired"));
            }
        }
    }

    private clreplaced DefaultPreAuthenticationChecks implements UserDetailsChecker {

        private DefaultPreAuthenticationChecks() {
        }

        @Override
        public void check(UserDetails user) {
            if (!user.isAccountNonLocked()) {
                log.debug("User account is locked");
                throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
            } else if (!user.isEnabled()) {
                log.debug("User account is disabled");
                throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
            } else if (!user.isAccountNonExpired()) {
                log.debug("User account is expired");
                throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
            }
        }
    }
}

17 Source : OpenIdAuthenticationProvider.java
with MIT License
from leecho

/**
 * @author LIQIU
 * created on 2018-11-19
 */
public clreplaced OpenIdAuthenticationProvider implements AuthenticationProvider {

    protected final Log logger = LogFactory.getLog(getClreplaced());

    protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

    private SocialUserDetailsService userDetailsService;

    private UsersConnectionRepository usersConnectionRepository;

    private UserDetailsChecker preAuthenticationChecks = new DefaultPreAuthenticationChecks();

    private UserDetailsChecker postAuthenticationChecks = new DefaultPostAuthenticationChecks();

    public OpenIdAuthenticationProvider(SocialUserDetailsService userDetailsService, UsersConnectionRepository usersConnectionRepository) {
        this.userDetailsService = userDetailsService;
        this.usersConnectionRepository = usersConnectionRepository;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        replacedert.isInstanceOf(OpenIdAuthenticationToken.clreplaced, authentication, "unsupported authentication type");
        replacedert.isTrue(!authentication.isAuthenticated(), "already authenticated");
        OpenIdAuthenticationToken authToken = (OpenIdAuthenticationToken) authentication;
        String userId = toUserId(authToken);
        if (userId == null) {
            throw new BadCredentialsException("Unknown access token");
        }
        UserDetails userDetails = userDetailsService.loadUserByUserId(userId);
        if (userDetails == null) {
            throw new UsernameNotFoundException("Unknown connected account id");
        }
        preAuthenticationChecks.check(userDetails);
        postAuthenticationChecks.check(userDetails);
        return this.createSuccessAuthentication(userDetails, authentication, userDetails);
    }

    protected String toUserId(OpenIdAuthenticationToken token) {
        Set<String> providerUserId = new HashSet<>();
        providerUserId.add(String.valueOf(token.getPrincipal()));
        Set<String> userIds = usersConnectionRepository.findUserIdsConnectedTo(String.valueOf(token.getCredentials()), providerUserId);
        // only if a single userId is connected to this providerUserId
        return (userIds.size() == 1) ? userIds.iterator().next() : null;
    }

    protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
        OpenIdAuthenticationToken result = new OpenIdAuthenticationToken(principal, user.getAuthorities());
        result.setDetails(authentication.getDetails());
        return result;
    }

    @Override
    public boolean supports(Clreplaced<?> authentication) {
        return authentication.isreplacedignableFrom(OpenIdAuthenticationToken.clreplaced);
    }

    private clreplaced DefaultPreAuthenticationChecks implements UserDetailsChecker {

        @Override
        public void check(UserDetails user) {
            if (!user.isAccountNonLocked()) {
                logger.debug("User account is locked");
                throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked"));
            }
            if (!user.isEnabled()) {
                logger.debug("User account is disabled");
                throw new DisabledException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
            }
            if (!user.isAccountNonExpired()) {
                logger.debug("User account is expired");
                throw new AccountExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
            }
        }
    }

    private clreplaced DefaultPostAuthenticationChecks implements UserDetailsChecker {

        @Override
        public void check(UserDetails user) {
            if (!user.isCredentialsNonExpired()) {
                logger.debug("User account credentials have expired");
                throw new CredentialsExpiredException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired"));
            }
        }
    }
}

17 Source : N2oJdomTextProcessing.java
with Apache License 2.0
from i-novus-llc

/**
 * User: operehod
 * Date: 14.10.2014
 * Time: 11:34
 */
@Deprecated
public clreplaced N2oJdomTextProcessing implements JdomTextProcessing {

    private MessageSourceAccessor messageSourceAccessor;

    private PropertyResolver systemProperties = new SimplePropertyResolver(new Properties());

    public N2oJdomTextProcessing(MessageSourceAccessor messageSourceAccessor, PropertyResolver systemProperties) {
        this.messageSourceAccessor = messageSourceAccessor;
        this.systemProperties = systemProperties;
    }

    public N2oJdomTextProcessing() {
    }

    @Override
    public String process(String text) {
        if (text == null) {
            return null;
        }
        String resolve = StringUtils.resolveProperties(text, systemProperties::getProperty);
        if (messageSourceAccessor != null)
            resolve = StringUtils.resolveProperties(resolve, messageSourceAccessor::getMessage);
        return resolve;
    }
}

17 Source : ErrorMessageBuilderTest.java
with Apache License 2.0
from i-novus-llc

@Test
public void testUserException() {
    MessageSourceAccessor messageSource = mock(MessageSourceAccessor.clreplaced);
    when(messageSource.getMessage("user.code", "user.code")).thenReturn("User message {0}");
    ErrorMessageBuilder builder = new ErrorMessageBuilder(messageSource);
    N2oException e = new N2oUserException("user.code").addData("test");
    ResponseMessage message = builder.build(e);
    replacedertThat(message.getText(), is("User message test"));
}

See More Examples