下面列出了org.springframework.core.io.ResourceEditor#org.springframework.web.util.NestedServletException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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");
}
}
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);
}
}
}
@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");
}
}
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;
}
/**
* 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);
}
}
@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)));
}
@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)));
}
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;
}
/**
* 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);
}
}
@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();
}
}
/**
* 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);
}
}
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;
}
@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");
}
}
/**
* 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);
}
}
/**
* 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);
}
}
}
}
/**
* 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);
}
}
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;
}
@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"));
}
}
@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");
}
}
/**
* 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);
}
}
@Test
void testUpdateEntitiesSpecificAttributeInvalidId() throws Throwable {
try {
mockMvc.perform(
put(BASE_URI + "/entity/email")
.content("{\"entities\":[{\"id\":\"4\",\"email\":\"[email protected]\"}]}")
.contentType(APPLICATION_JSON));
} catch (NestedServletException e) {
Exception exception =
assertThrows(
UnknownEntityException.class,
() -> {
throw e.getCause();
});
assertThat(exception.getMessage()).containsPattern("type:entity id:4 attribute:id");
}
}
@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");
}
@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");
}
}
@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");
}
}
@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");
}
}
@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");
}
}
@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");
}
}
@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");
}
}
@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");
}
}
@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");
}
}