Search in sources :

Example 16 with NestedServletException

use of org.springframework.web.util.NestedServletException in project neubbs by nuitcoder.

the class AccountControllerTest method testActivateAccountException.

/**
 * 测试 /api/account/activate
 *      - 测试激活账户异常
 *          - request param error
 *              - [✔] null
 *              - [✔] format not norm
 *          - service exception
 *              - [✔] no user
 *          - [✔] 60s send mail interval time for the same account
 */
@Test
@Transactional
public void testActivateAccountException() throws Exception {
    // request param error
    String[] params = { null, "123", "test@", "liushuwei0925@gmail.com" };
    for (String email : params) {
        String requestBody = "{\"email\":\"" + email + "\"}";
        System.out.println("input post param request-body: " + requestBody);
        try {
            mockMvc.perform(MockMvcRequestBuilders.post("/api/account/activate").contentType(MediaType.APPLICATION_JSON).content(requestBody).accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.jsonPath("$.success").value(false)).andExpect(MockMvcResultMatchers.jsonPath("$.message").exists()).andExpect(MockMvcResultMatchers.jsonPath("$.model").exists());
        } catch (NestedServletException ne) {
            Assert.assertThat(ne.getRootCause(), CoreMatchers.anyOf(CoreMatchers.instanceOf(ParamsErrorException.class), CoreMatchers.instanceOf(ServiceException.class)));
        }
    }
    // test again send mail, exist interval time(not sent repeatedly)
    String email = "testActivate@test.com";
    userService.registerUser(email.substring(0, email.indexOf("@")), "123456", email);
    // cache server set 60s send mail interval time for the same account
    ICacheService redisService = (ICacheService) webApplicationContext.getBean("redisServiceImpl");
    redisService.saveUserEmailKey(email);
    mockMvc.perform(MockMvcRequestBuilders.post("/api/account/activate").contentType(MediaType.APPLICATION_JSON).content("{\"email\":\"" + email + "\"}").accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.jsonPath("$.success").value(false)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value(ApiMessage.WAIT_TIMER)).andExpect(MockMvcResultMatchers.jsonPath("$.model").exists()).andExpect(MockMvcResultMatchers.jsonPath("$.model.timer").value(CoreMatchers.notNullValue()));
    System.out.println("send email exist interval time limit , test success!");
    util.printSuccessMessage();
}
Also used : ParamsErrorException(org.neusoft.neubbs.exception.ParamsErrorException) NestedServletException(org.springframework.web.util.NestedServletException) ServiceException(org.neusoft.neubbs.exception.ServiceException) ICacheService(org.neusoft.neubbs.service.ICacheService) Test(org.junit.Test) Transactional(javax.transaction.Transactional)

Example 17 with NestedServletException

use of org.springframework.web.util.NestedServletException in project spring-security-oauth by spring-projects.

the class OAuth2ClientContextFilter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    request.setAttribute(CURRENT_URI, calculateCurrentUri(request));
    try {
        chain.doFilter(servletRequest, servletResponse);
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        // Try to extract a SpringSecurityException from the stacktrace
        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
        UserRedirectRequiredException redirect = (UserRedirectRequiredException) throwableAnalyzer.getFirstThrowableOfType(UserRedirectRequiredException.class, causeChain);
        if (redirect != null) {
            redirectUser(redirect, request, response);
        } else {
            if (ex instanceof ServletException) {
                throw (ServletException) ex;
            }
            if (ex instanceof RuntimeException) {
                throw (RuntimeException) ex;
            }
            throw new NestedServletException("Unhandled exception", ex);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) NestedServletException(org.springframework.web.util.NestedServletException) NestedServletException(org.springframework.web.util.NestedServletException) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) NestedServletException(org.springframework.web.util.NestedServletException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)

Example 18 with NestedServletException

use of org.springframework.web.util.NestedServletException in project gocd by gocd.

the class AgentRemoteInvokerServiceExporter method handleRequest.

@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (rejectRMI()) {
        // yes, ideally, this should be short-circuited in the agent auth filter, but keeping this logic here has
        // some advantages:
        // - it keeps all deprecated RMI logic in one place so it's easier to remove (just remove this class)
        // - it's 100% reliable by virtue of its proximity to the RMI invocation code and can't be thwarted by
        // some clever URI encoding to circumvent the uri path test that we would need to write at the filter
        // level in order to selectively apply this logic to the RMI endpoint and not the JSON API endpoint
        reject(response, SC_GONE, "This RMI endpoint is disabled.");
        return;
    }
    try {
        RemoteInvocation invocation = readRemoteInvocation(request);
        if (!authorized(request, response, invocation)) {
            return;
        }
        RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy());
        writeRemoteInvocationResult(request, response, result);
    } catch (ClassNotFoundException ex) {
        throw new NestedServletException("Class not found during deserialization", ex);
    }
}
Also used : RemoteInvocation(org.springframework.remoting.support.RemoteInvocation) NestedServletException(org.springframework.web.util.NestedServletException) RemoteInvocationResult(org.springframework.remoting.support.RemoteInvocationResult)

Example 19 with NestedServletException

use of org.springframework.web.util.NestedServletException in project ma-core-public by infiniteautomation.

the class MangoErrorHandler method generateAcceptableResponse.

/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jetty.server.handler.ErrorHandler#generateAcceptableResponse(
	 * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, int, java.lang.String,
	 * java.lang.String)
	 */
@Override
protected void generateAcceptableResponse(Request baseRequest, HttpServletRequest request, HttpServletResponse response, int code, String message, String mimeType) throws IOException {
    switch(code) {
        case 404:
            if (MangoSecurityConfiguration.browserHtmlRequestMatcher().matches(request)) {
                // Forward to Not Found URI
                String uri = DefaultPagesDefinition.getNotFoundUri(request, response);
                response.sendRedirect(uri);
            } else {
                // Resource/Rest Request
                baseRequest.setHandled(true);
            }
            break;
        default:
            // Catch All unhandled Responses with errors
            Throwable th = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
            // Does this require handling
            if (th != null) {
                if (th instanceof NestedServletException)
                    th = th.getCause();
                // Log it
                ExceptionUtils.logWebException(th, request, LOG);
                HttpSession sesh = baseRequest.getSession(false);
                String uri;
                // We are handling this here
                baseRequest.setHandled(true);
                // We need to do something
                if (MangoSecurityConfiguration.browserHtmlRequestMatcher().matches(request)) {
                    // Are we a PermissionException
                    if (th instanceof PermissionException) {
                        User user = Common.getHttpUser();
                        if (user == null)
                            uri = ACCESS_DENIED;
                        else
                            uri = DefaultPagesDefinition.getUnauthorizedUri(request, response, Common.getHttpUser());
                        // Put exception into request scope (perhaps of use to a view)
                        request.setAttribute(WebAttributes.ACCESS_DENIED_403, th);
                        response.sendRedirect(uri);
                    } else {
                        // Redirect to Error URI
                        if (sesh != null)
                            sesh.setAttribute(Common.SESSION_USER_EXCEPTION, th);
                        uri = DefaultPagesDefinition.getErrorUri(baseRequest, response);
                        response.sendRedirect(uri);
                    }
                } else {
                    // Resource/Rest Request
                    baseRequest.setHandled(true);
                    if (sesh != null)
                        sesh.setAttribute(Common.SESSION_USER_EXCEPTION, th.getCause());
                }
            }
            break;
    }
}
Also used : PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) NestedServletException(org.springframework.web.util.NestedServletException) User(com.serotonin.m2m2.vo.User) HttpSession(javax.servlet.http.HttpSession)

Example 20 with NestedServletException

use of org.springframework.web.util.NestedServletException in project scoold by Erudika.

the class VelocityView method exposeToolAttributes.

/**
 * Expose the tool attributes, according to corresponding bean property settings.
 * <p>
 * Do not override this method unless for further tools driven by bean properties. Override one of the
 * {@code exposeHelpers} methods to add custom helpers.
 *
 * @param velocityContext Velocity context that will be passed to the template
 * @param request current HTTP request
 * @throws Exception if there's a fatal error while we're adding model attributes
 */
protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception {
    // Expose generic attributes.
    if (this.toolAttributes != null) {
        for (Map.Entry<String, Class<?>> entry : this.toolAttributes.entrySet()) {
            String attributeName = entry.getKey();
            Class<?> toolClass = entry.getValue();
            try {
                Object tool = toolClass.getDeclaredConstructor().newInstance();
                initTool(tool, velocityContext);
                velocityContext.put(attributeName, tool);
            } catch (Exception ex) {
                throw new NestedServletException("Could not instantiate Velocity tool '" + attributeName + "'", ex);
            }
        }
    }
}
Also used : NestedServletException(org.springframework.web.util.NestedServletException) Map(java.util.Map) BeansException(org.springframework.beans.BeansException) ApplicationContextException(org.springframework.context.ApplicationContextException) NestedIOException(org.springframework.core.NestedIOException) NestedServletException(org.springframework.web.util.NestedServletException) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) MethodInvocationException(org.apache.velocity.exception.MethodInvocationException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException)

Aggregations

NestedServletException (org.springframework.web.util.NestedServletException)22 IOException (java.io.IOException)5 Test (org.junit.Test)5 RemoteInvocation (org.springframework.remoting.support.RemoteInvocation)4 RemoteInvocationResult (org.springframework.remoting.support.RemoteInvocationResult)4 ServletException (javax.servlet.ServletException)3 Test (org.junit.jupiter.api.Test)3 WebAsyncManager (org.springframework.web.context.request.async.WebAsyncManager)3 ServletException (jakarta.servlet.ServletException)2 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Map (java.util.Map)2 Transactional (javax.transaction.Transactional)2 MethodInvocationException (org.apache.velocity.exception.MethodInvocationException)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 MockMultipartFile (org.springframework.mock.web.MockMultipartFile)2 SerializationException (com.haulmont.cuba.core.sys.serialization.SerializationException)1 User (com.serotonin.m2m2.vo.User)1 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)1 RequestDispatcher (jakarta.servlet.RequestDispatcher)1