Java Code Examples for org.springframework.web.util.NestedServletException

The following examples show how to use org.springframework.web.util.NestedServletException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
void testCopyEntityDuplicateEntity() throws Throwable {
  @SuppressWarnings("unchecked")
  Repository<Entity> repositoryToCopy = mock(Repository.class);
  mocksForCopyEntitySuccess(repositoryToCopy);

  String content = "{newEntityName: 'duplicateEntity'}";
  try {
    mockMvc.perform(post(HREF_COPY_ENTITY).content(content).contentType(APPLICATION_JSON));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            RepositoryAlreadyExistsException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage())
        .containsPattern("repository:org_molgenis_blah_duplicateEntity");
  }
}
 
Example 2
Source Project: airsonic-advanced   Source File: RESTFilter.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void handleException(Throwable x, HttpServletRequest request, HttpServletResponse response) {
    if (x instanceof NestedServletException && x.getCause() != null) {
        x = x.getCause();
    }

    SubsonicRESTController.ErrorCode code = (x instanceof ServletRequestBindingException) ? SubsonicRESTController.ErrorCode.MISSING_PARAMETER : SubsonicRESTController.ErrorCode.GENERIC;
    String msg = getErrorMessage(x);

    // This happens often and outside of the control of the server, so
    // we catch Tomcat/Jetty "connection aborted by client" exceptions
    // and display a short error message.
    boolean shouldCatch = Util.isInstanceOfClassName(x, "org.apache.catalina.connector.ClientAbortException");
    if (shouldCatch) {
        LOG.info("{}: Client unexpectedly closed connection while loading {} ({})", request.getRemoteAddr(),
                Util.getAnonymizedURLForRequest(request), x.getMessage());
    } else {
        LOG.warn("Error in REST API", x);

        try {
            jaxbWriter.writeErrorResponse(request, response, code, msg);
        } catch (Exception e) {
            LOG.error("Failed to write error response.", e);
        }
    }

}
 
Example 3
@Test
void retrieveResourceCollectionUnknownEntityType() throws Throwable {
  String unknownEntityTypeId = "unknown";
  doThrow(new UnknownEntityTypeException(unknownEntityTypeId))
      .when(dataService)
      .getRepository(unknownEntityTypeId);

  try {
    mockMvc.perform(get(BASE_URI + '/' + unknownEntityTypeId));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownEntityTypeException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("id:unknown");
  }
}
 
Example 4
public ConcurrentResultHandlerMethod(final Object result, ConcurrentResultMethodParameter returnType) {
	super((Callable<Object>) () -> {
		if (result instanceof Exception) {
			throw (Exception) result;
		}
		else if (result instanceof Throwable) {
			throw new NestedServletException("Async processing failed", (Throwable) result);
		}
		return result;
	}, CALLABLE_METHOD);

	if (ServletInvocableHandlerMethod.this.returnValueHandlers != null) {
		setHandlerMethodReturnValueHandlers(ServletInvocableHandlerMethod.this.returnValueHandlers);
	}
	this.returnType = returnType;
}
 
Example 5
Source Project: spring-analysis-note   Source File: HessianServiceExporter.java    License: MIT License 6 votes vote down vote up
/**
 * Processes the incoming Hessian request and creates a Hessian response.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (!"POST".equals(request.getMethod())) {
		throw new HttpRequestMethodNotSupportedException(request.getMethod(),
				new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
	}

	response.setContentType(CONTENT_TYPE_HESSIAN);
	try {
		invoke(request.getInputStream(), response.getOutputStream());
	}
	catch (Throwable ex) {
		throw new NestedServletException("Hessian skeleton invocation failed", ex);
	}
}
 
Example 6
Source Project: kardio   Source File: AdminControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = NestedServletException.class)
public void testAuthTokenNullSession() throws Exception {
    AppFullName afn = getAppFullName();
    String authToken = "auth_token";

    AppSession session = new AppSession();
    session.setAppSessionId(1);
    session.setAuthToken(null);
    session.setUserId("admin_id");
    session.setUserName("admin");
    session.setAdmin(true);
    session.setSessionStartTime(new Date());
    when(adminService.getAppSession(authToken)).thenReturn(session);

    mockMvc.perform(post("/addAppFullName")
            .contentType(MediaType.APPLICATION_JSON)
            .param("authToken", authToken)
            .content(TestUtils.asJsonString(afn)));
}
 
Example 7
Source Project: kardio   Source File: AdminControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = NestedServletException.class)
public void testAuthTokenNotAdmin() throws Exception {
    AppFullName afn = getAppFullName();
    String authToken = "auth_token";

    AppSession session = new AppSession();
    session.setAppSessionId(1);
    session.setAuthToken(authToken);
    session.setUserId("admin_id");
    session.setUserName("admin");
    session.setAdmin(false);
    session.setSessionStartTime(new Date());
    when(adminService.getAppSession(authToken)).thenReturn(session);

    mockMvc.perform(post("/addAppFullName")
            .contentType(MediaType.APPLICATION_JSON)
            .param("authToken", authToken)
            .content(TestUtils.asJsonString(afn)));
}
 
Example 8
public ConcurrentResultHandlerMethod(final Object result, ConcurrentResultMethodParameter returnType) {
	super((Callable<Object>) () -> {
		if (result instanceof Exception) {
			throw (Exception) result;
		}
		else if (result instanceof Throwable) {
			throw new NestedServletException("Async processing failed", (Throwable) result);
		}
		return result;
	}, CALLABLE_METHOD);

	if (ServletInvocableHandlerMethod.this.returnValueHandlers != null) {
		setHandlerMethodReturnValueHandlers(ServletInvocableHandlerMethod.this.returnValueHandlers);
	}
	this.returnType = returnType;
}
 
Example 9
Source Project: java-technology-stack   Source File: HessianServiceExporter.java    License: MIT License 6 votes vote down vote up
/**
 * Processes the incoming Hessian request and creates a Hessian response.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (!"POST".equals(request.getMethod())) {
		throw new HttpRequestMethodNotSupportedException(request.getMethod(),
				new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
	}

	response.setContentType(CONTENT_TYPE_HESSIAN);
	try {
		invoke(request.getInputStream(), response.getOutputStream());
	}
	catch (Throwable ex) {
		throw new NestedServletException("Hessian skeleton invocation failed", ex);
	}
}
 
Example 10
Source Project: elide-spring-boot   Source File: ElidePropertiesTest.java    License: Apache License 2.0 6 votes vote down vote up
@Transactional
@Test(expected = NullPointerException.class)
public void testDisableDI() throws Throwable {
  MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();

  try {
    String postBook = "{\"data\": {\"type\": \"account\",\"attributes\": {\"username\": \"username\",\"password\": \"password\"}}}";

    mockMvc.perform(post("/api/account")
        .contentType(JSON_API_CONTENT_TYPE)
        .content(postBook)
        .accept(JSON_API_CONTENT_TYPE))
        .andExpect(content().contentType(JSON_API_RESPONSE))
        .andExpect(status().isCreated());
  } catch (NestedServletException e) {
    throw e.getCause();
  }
}
 
Example 11
Source Project: lams   Source File: VelocityView.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Merge the template with the context.
 * Can be overridden to customize the behavior.
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
		Template template, Context context, HttpServletResponse response) throws Exception {

	try {
		template.merge(context, response.getWriter());
	}
	catch (MethodInvocationException ex) {
		Throwable cause = ex.getWrappedThrowable();
		throw new NestedServletException(
				"Method invocation failed during rendering of Velocity view with name '" +
				getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
				"], method '" + ex.getMethodName() + "'",
				cause==null ? ex : cause);
	}
}
 
Example 12
public ConcurrentResultHandlerMethod(final Object result, ConcurrentResultMethodParameter returnType) {
	super(new Callable<Object>() {
		@Override
		public Object call() throws Exception {
			if (result instanceof Exception) {
				throw (Exception) result;
			}
			else if (result instanceof Throwable) {
				throw new NestedServletException("Async processing failed", (Throwable) result);
			}
			return result;
		}
	}, CALLABLE_METHOD);

	setHandlerMethodReturnValueHandlers(ServletInvocableHandlerMethod.this.returnValueHandlers);
	this.returnType = returnType;
}
 
Example 13
@Test
void testUpdateEntitiesUnknownEntity() throws Throwable {
  String unknownEntityTypeId = "entity2";
  doThrow(new UnknownEntityTypeException(unknownEntityTypeId))
      .when(dataService)
      .getEntityType(unknownEntityTypeId);

  try {
    mockMvc.perform(
        put(BASE_URI + "/" + "entity2")
            .content("{entities:[{email:'[email protected]'}]}")
            .contentType(APPLICATION_JSON));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownEntityTypeException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("id:entity2");
  }
}
 
Example 14
Source Project: lams   Source File: HessianServiceExporter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Processes the incoming Hessian request and creates a Hessian response.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (!"POST".equals(request.getMethod())) {
		throw new HttpRequestMethodNotSupportedException(request.getMethod(),
				new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
	}

	response.setContentType(CONTENT_TYPE_HESSIAN);
	try {
	  invoke(request.getInputStream(), response.getOutputStream());
	}
	catch (Throwable ex) {
	  throw new NestedServletException("Hessian skeleton invocation failed", ex);
	}
}
 
Example 15
Source Project: scoold   Source File: VelocityView.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
			}
		}
	}
}
 
Example 16
Source Project: spring4-understanding   Source File: VelocityView.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Merge the template with the context.
 * Can be overridden to customize the behavior.
 * @param template the template to merge
 * @param context the Velocity context to use for rendering
 * @param response servlet response (use this to get the OutputStream or Writer)
 * @throws Exception if thrown by Velocity
 * @see org.apache.velocity.Template#merge
 */
protected void mergeTemplate(
		Template template, Context context, HttpServletResponse response) throws Exception {

	try {
		template.merge(context, response.getWriter());
	}
	catch (MethodInvocationException ex) {
		Throwable cause = ex.getWrappedThrowable();
		throw new NestedServletException(
				"Method invocation failed during rendering of Velocity view with name '" +
				getBeanName() + "': " + ex.getMessage() + "; reference [" + ex.getReferenceName() +
				"], method '" + ex.getMethodName() + "'",
				cause==null ? ex : cause);
	}
}
 
Example 17
public ConcurrentResultHandlerMethod(final Object result, ConcurrentResultMethodParameter returnType) {
	super(new Callable<Object>() {
		@Override
		public Object call() throws Exception {
			if (result instanceof Exception) {
				throw (Exception) result;
			}
			else if (result instanceof Throwable) {
				throw new NestedServletException("Async processing failed", (Throwable) result);
			}
			return result;
		}
	}, CALLABLE_METHOD);
	setHandlerMethodReturnValueHandlers(ServletInvocableHandlerMethod.this.returnValueHandlers);
	this.returnType = returnType;
}
 
Example 18
@Test
public void equivalentMappingsWithSameMethodName() throws Exception {
	initServlet(ChildController.class);
	servlet.init(new MockServletConfig());

	MockHttpServletRequest request = new MockHttpServletRequest("GET", "/child/test");
	request.addParameter("childId", "100");
	MockHttpServletResponse response = new MockHttpServletResponse();
	try {
		servlet.service(request, response);
		fail("Didn't fail with due to ambiguous method mapping");
	}
	catch (NestedServletException ex) {
		assertTrue(ex.getCause() instanceof IllegalStateException);
		assertTrue(ex.getCause().getMessage().contains("doGet"));
	}
}
 
Example 19
@Test
void updateAttribute_unknownAttribute() throws Throwable {
  try {
    mockMvc.perform(
        post(HREF_ENTITY_ID + "/unknownattribute")
            .param("_method", "PUT")
            .content("Klaas")
            .contentType(APPLICATION_JSON));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownAttributeException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("type:Person attribute:unknownattribute");
  }
}
 
Example 20
/**
 * Processes the incoming Hessian request and creates a Hessian response.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (!"POST".equals(request.getMethod())) {
		throw new HttpRequestMethodNotSupportedException(request.getMethod(),
				new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
	}

	response.setContentType(CONTENT_TYPE_HESSIAN);
	try {
	  invoke(request.getInputStream(), response.getOutputStream());
	}
	catch (Throwable ex) {
	  throw new NestedServletException("Hessian skeleton invocation failed", ex);
	}
}
 
Example 21
@Test
void testUpdateEntitiesSpecificAttributeInvalidId() throws Throwable {
  try {
    mockMvc.perform(
        put(BASE_URI + "/entity/email")
            .content("{\"entities\":[{\"id\":\"4\",\"email\":\"[email protected]m\"}]}")
            .contentType(APPLICATION_JSON));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownEntityException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("type:entity id:4 attribute:id");
  }
}
 
Example 22
@Test
public void should_log_tracing_information_when_500_exception_was_thrown()
		throws Exception {
	Long expectedTraceId = new Random().nextLong();

	try {
		whenSentToExceptionThrowingEndpoint(expectedTraceId);
		fail("Should fail");
	}
	catch (NestedServletException e) {
		then(e).hasRootCauseInstanceOf(RuntimeException.class);
	}

	// we need to dump the span cause it's not in TracingFilter since TF
	// has also error dispatch and the ErrorController would report the span
	then(this.spans).hasSize(1);
	then(this.spans.get(0).error()).hasMessageContaining(
			"Request processing failed; nested exception is java.lang.RuntimeException");
}
 
Example 23
@Test
void testServeAppNoPermissions() throws Throwable {
  PluginIdentity pluginIdentity = new PluginIdentity(APP_PREFIX + "app1");
  when(userPermissionEvaluator.hasPermission(pluginIdentity, VIEW_PLUGIN)).thenReturn(false);
  try {
    mockMvc.perform(get(AppController.URI + "/app1/"));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            PluginPermissionDeniedException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage())
        .containsPattern("pluginPermission: VIEW_PLUGIN, pluginId:app1");
  }
}
 
Example 24
@Test
@WithMockUser("henkie")
void testCreateGroupUnavailableGroupName() throws Throwable {
  when(groupService.isGroupNameAvailable(any())).thenReturn(false);
  try {
    mockMvc
        .perform(
            post(GROUP_END_POINT)
                .contentType(APPLICATION_JSON_UTF8)
                .content(gson.toJson(createGroup("devs", "Developers"))))
        .andExpect(status().isBadRequest());
  } catch (NestedServletException e) {
    verifyNoMoreInteractions(groupService);
    verifyNoMoreInteractions(groupPermissionService);
    verifyNoMoreInteractions(roleMembershipService);
    Exception exception =
        assertThrows(
            GroupNameNotAvailableException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("groupName:devs");
  }
}
 
Example 25
@Test
void testGetMembersPermissionDenied() throws Throwable {
  when(userPermissionEvaluator.hasPermission(new GroupIdentity("devs"), VIEW_MEMBERSHIP))
      .thenReturn(false);
  try {
    mockMvc.perform(get(GROUP_END_POINT + "/devs/member"));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            GroupPermissionDeniedException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage())
        .containsPattern("permission:VIEW_MEMBERSHIP groupName:devs");
  }
}
 
Example 26
@Test
void testGetMembersUnknownGroup() throws Throwable {
  when(userPermissionEvaluator.hasPermission(new GroupIdentity("devs"), VIEW_MEMBERSHIP))
      .thenReturn(true);
  when(groupMetadata.getId()).thenReturn("Group");
  when(attribute.getName()).thenReturn("Name");
  doThrow(new UnknownEntityException(groupMetadata, attribute, "devs"))
      .when(groupService)
      .getGroup("devs");
  try {
    mockMvc.perform(get(GROUP_END_POINT + "/devs/member"));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownEntityException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("type:Group id:devs attribute:Name");
  }
}
 
Example 27
@Test
void testAddMembershipPermissionDenied() throws Throwable {
  when(userPermissionEvaluator.hasPermission(new GroupIdentity("devs"), ADD_MEMBERSHIP))
      .thenReturn(false);
  try {
    mockMvc.perform(
        post(GROUP_END_POINT + "/devs/member")
            .contentType(APPLICATION_JSON_UTF8)
            .content(gson.toJson(addGroupMember("user", "DEVS_EDITOR"))));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            GroupPermissionDeniedException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage())
        .containsPattern("permission:ADD_MEMBERSHIP groupName:devs");
  }
}
 
Example 28
@Test
void testAddMembershipUnknownGroup() throws Throwable {
  when(userPermissionEvaluator.hasPermission(new GroupIdentity("devs"), ADD_MEMBERSHIP))
      .thenReturn(true);

  when(groupMetadata.getId()).thenReturn("Group");
  when(attribute.getName()).thenReturn("Name");
  doThrow(new UnknownEntityException(groupMetadata, attribute, "devs"))
      .when(groupService)
      .getGroup("devs");
  try {
    mockMvc.perform(
        post(GROUP_END_POINT + "/devs/member")
            .contentType(APPLICATION_JSON_UTF8)
            .content(gson.toJson(addGroupMember("user", "DEVS_EDITOR"))));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownEntityException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("type:Group id:devs attribute:Name");
  }
}
 
Example 29
@Test
void testCreateEntitiesUnknownEntityTypeException() throws Throwable {
  String unknownEntityTypeId = "entity2";
  doThrow(new UnknownEntityTypeException(unknownEntityTypeId))
      .when(dataService)
      .getEntityType(unknownEntityTypeId);

  try {
    mockMvc.perform(
        post(BASE_URI + "/" + unknownEntityTypeId)
            .content("{entities:[{email:'[email protected]', extraAttribute:'test'}]}")
            .contentType(APPLICATION_JSON));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownEntityTypeException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("id:entity2");
  }
}
 
Example 30
@Test
void testAddMembershipUnknownUser() throws Throwable {
  when(userPermissionEvaluator.hasPermission(new GroupIdentity("devs"), ADD_MEMBERSHIP))
      .thenReturn(true);
  when(groupService.getGroup("devs")).thenReturn(group);
  when(roleService.getRole("DEVS_EDITOR")).thenReturn(editor);
  when(userMetadata.getId()).thenReturn("User");
  when(attribute.getName()).thenReturn("Name");
  doThrow(new UnknownEntityException(userMetadata, attribute, "henkie"))
      .when(userService)
      .getUser("user");
  try {
    mockMvc.perform(
        post(GROUP_END_POINT + "/devs/member")
            .contentType(APPLICATION_JSON_UTF8)
            .content(gson.toJson(addGroupMember("user", "DEVS_EDITOR"))));
  } catch (NestedServletException e) {
    Exception exception =
        assertThrows(
            UnknownEntityException.class,
            () -> {
              throw e.getCause();
            });
    assertThat(exception.getMessage()).containsPattern("type:User id:henkie attribute:Name");
  }
}