use of org.springframework.web.util.NestedServletException in project scoold by Erudika.
the class VelocityView method mergeTemplate.
/**
* 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 {
response.setCharacterEncoding(Config.DEFAULT_ENCODING);
template.merge(context, response.getWriter());
} catch (MethodInvocationException ex) {
Throwable cause = ex.getCause();
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);
}
}
use of org.springframework.web.util.NestedServletException in project metron by apache.
the class KafkaControllerIntegrationTest method test.
@Test
public void test() throws Exception {
this.kafkaService.deleteTopic("bro");
this.kafkaService.deleteTopic("someTopic");
Thread.sleep(1000);
testAndRetry(() -> this.mockMvc.perform(delete(kafkaUrl + "/topic/bro").with(httpBasic(user, password)).with(csrf())).andExpect(status().isNotFound()));
testAndRetry(() -> this.mockMvc.perform(post(kafkaUrl + "/topic").with(httpBasic(user, password)).with(csrf()).contentType(MediaType.parseMediaType("application/json;charset=UTF-8")).content(broTopic)).andExpect(status().isCreated()).andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8"))).andExpect(jsonPath("$.name").value("bro")).andExpect(jsonPath("$.numPartitions").value(1)).andExpect(jsonPath("$.replicationFactor").value(1)));
Thread.sleep(1000);
testAndRetry(() -> this.mockMvc.perform(get(kafkaUrl + "/topic/bro").with(httpBasic(user, password))).andExpect(status().isOk()).andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8"))).andExpect(jsonPath("$.name").value("bro")).andExpect(jsonPath("$.numPartitions").value(1)).andExpect(jsonPath("$.replicationFactor").value(1)));
this.mockMvc.perform(get(kafkaUrl + "/topic/someTopic").with(httpBasic(user, password))).andExpect(status().isNotFound());
testAndRetry(() -> this.mockMvc.perform(get(kafkaUrl + "/topic").with(httpBasic(user, password))).andExpect(status().isOk()).andExpect(content().contentType(MediaType.parseMediaType("application/json;charset=UTF-8"))).andExpect(jsonPath("$", Matchers.hasItem("bro"))));
testAndRetry(() -> this.mockMvc.perform(post(kafkaUrl + "/topic/bro/produce").with(httpBasic(user, password)).with(csrf()).contentType(MediaType.parseMediaType("application/json;charset=UTF-8")).content(message1)).andExpect(status().isOk()));
testAndRetry(() -> this.mockMvc.perform(get(kafkaUrl + "/topic/bro/sample").with(httpBasic(user, password))).andExpect(status().isOk()).andExpect(content().contentType(MediaType.parseMediaType("text/plain;charset=UTF-8"))).andExpect(jsonPath("$.type").value("message1")));
testAndRetry(() -> this.mockMvc.perform(post(kafkaUrl + "/topic/bro/produce").with(httpBasic(user, password)).with(csrf()).contentType(MediaType.parseMediaType("application/json;charset=UTF-8")).content(message2)).andExpect(status().isOk()));
testAndRetry(() -> this.mockMvc.perform(get(kafkaUrl + "/topic/bro/sample").with(httpBasic(user, password))).andExpect(status().isOk()).andExpect(content().contentType(MediaType.parseMediaType("text/plain;charset=UTF-8"))).andExpect(jsonPath("$.type").value("message2")));
testAndRetry(() -> this.mockMvc.perform(post(kafkaUrl + "/topic/bro/produce").with(httpBasic(user, password)).with(csrf()).contentType(MediaType.parseMediaType("application/json;charset=UTF-8")).content(message3)).andExpect(status().isOk()));
testAndRetry(() -> this.mockMvc.perform(get(kafkaUrl + "/topic/bro/sample").with(httpBasic(user, password))).andExpect(status().isOk()).andExpect(content().contentType(MediaType.parseMediaType("text/plain;charset=UTF-8"))).andExpect(jsonPath("$.type").value("message3")));
this.mockMvc.perform(get(kafkaUrl + "/topic/someTopic/sample").with(httpBasic(user, password))).andExpect(status().isNotFound());
boolean deleted = false;
for (int i = 0; i < KAFKA_RETRY; ++i) {
try {
MvcResult result = this.mockMvc.perform(delete(kafkaUrl + "/topic/bro").with(httpBasic(user, password)).with(csrf())).andReturn();
if (result.getResponse().getStatus() == 200) {
deleted = true;
break;
}
Thread.sleep(1000);
} catch (NestedServletException nse) {
Throwable t = nse.getRootCause();
if (t instanceof TopicAlreadyMarkedForDeletionException) {
continue;
} else {
throw nse;
}
} catch (Throwable t) {
throw t;
}
}
if (!deleted) {
throw new IllegalStateException("Unable to delete kafka topic \"bro\"");
}
}
use of org.springframework.web.util.NestedServletException in project cuba by cuba-platform.
the class HttpServiceExporter method handleRequest.
/*
* In base implementation, exceptions which are thrown during reading remote invocation request, are not handled.
* Client gets useless HTTP status 500 in this case.
*
* This implementation passes some known exceptions to client.
*/
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (!ServiceExportHelper.exposeServices()) {
logger.debug("Services are not exposed due to 'cuba.doNotExposeRemoteServices' is set to true");
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
RemoteInvocationResult result;
RemoteInvocation invocation = null;
try {
invocation = readRemoteInvocation(request);
result = invokeAndCreateResult(invocation, getProxy());
} catch (OptionalDataException | ClassCastException e) {
// typical binary incompatibility exceptions
logger.error("Failed to read remote invocation request", e);
result = new RemoteInvocationResult(e);
} catch (ClassNotFoundException ex) {
throw new NestedServletException("Class not found during deserialization", ex);
}
try {
writeRemoteInvocationResult(request, response, result);
} catch (SerializationException e) {
String serviceName = null;
if (getServiceInterface() != null) {
serviceName = getServiceInterface().getSimpleName();
}
String methodName = null;
String paramTypes = null;
if (invocation != null) {
methodName = invocation.getMethodName();
if (invocation.getParameterTypes() != null) {
paramTypes = Joiner.on(",").join(invocation.getParameterTypes());
}
}
throw new NestedServletException(String.format("Failed to write result for service [%s.%s(%s)]", serviceName, methodName, paramTypes), e);
}
}
use of org.springframework.web.util.NestedServletException in project neubbs by nuitcoder.
the class ApiTestUtil method testApiThrowNoPermissionException.
/**
* 访问 api,抛出用户无权限异常
* - 主要测试三个权限: @LoginAuthorization @AccountActivation @AdminRank
* - 若未抛出指定异常,则可能访问到空页面(Controller 的接口设定了访问限制,例如:consumes 和 参数列表)
*
* @param apiUrl api地址
* @param requestMethod http请求方式
* @param user 用户对象(用于构建Cookie)
*/
void testApiThrowNoPermissionException(String apiUrl, RequestMethod requestMethod, UserDO user) {
// set post | get
MockHttpServletRequestBuilder mockRequest = MockMvcRequestBuilders.get(apiUrl);
if (RequestMethod.POST.equals(requestMethod)) {
mockRequest = MockMvcRequestBuilders.post(apiUrl);
}
// set content type
mockRequest.contentType(MediaType.APPLICATION_JSON);
// upload file type, to change http request
if (apiUrl.contains("/api/file/")) {
mockRequest = MockMvcRequestBuilders.fileUpload(apiUrl).file(new MockMultipartFile("avatarImageFile", "testAvatarFile.jpg", "image/jpg", new byte[0]));
mockRequest.contentType(MediaType.MULTIPART_FORM_DATA_VALUE);
}
if (user != null) {
mockRequest.cookie(new Cookie(ParamConst.AUTHENTICATION, SecretUtil.generateUserInfoToken(user)));
}
try {
mockMvc.perform(mockRequest.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.jsonPath("$.success").value(false)).andExpect(MockMvcResultMatchers.jsonPath("$.message").value(ApiMessage.NO_PERMISSION)).andExpect(MockMvcResultMatchers.jsonPath("$.model").value(CoreMatchers.notNullValue()));
} catch (NestedServletException ne) {
Assert.assertTrue(ne.getRootCause() instanceof PermissionException);
// the account no activated
if (user != null && user.getState() == SetConst.ACCOUNT_NO_ACTIVATED_STATE) {
Assert.assertEquals(ApiMessage.NO_ACTIVATE, ne.getRootCause().getMessage());
} else {
Assert.assertEquals(ApiMessage.NO_PERMISSION, ne.getRootCause().getMessage());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("no throw expected exception");
}
}
use of org.springframework.web.util.NestedServletException in project neubbs by nuitcoder.
the class FileControllerTest method testUploadUserAvatarException.
/**
* 测试 /api/file/avatar
* - 测试上传用户头像异常
* - no permission
* - [✔] no login
* - [✔] the account not activated
* - [✔] upload file format incorrect (no norm)
*/
@Test
@Transactional
public void testUploadUserAvatarException() throws Exception {
// no login
util.testApiThrowNoPermissionException("/api/file/avatar", RequestMethod.POST, null);
// the account not activated
util.testApiThrowNoPermissionException("/api/file/avatar", RequestMethod.POST, util.getNoActivatedUserDO());
// upload file format incorrect
String htmlInputName = "avatarImageFile";
String fileName = "testAvatarFile.jpg";
String fileType = "image/jpg";
byte[] fileBytes = new byte[1024 * 1024 * 1];
MockMultipartFile[] files = { new MockMultipartFile(htmlInputName, fileName, fileType, new byte[0]), new MockMultipartFile(htmlInputName, "exceptionImage.ps", "image/ps", fileBytes), new MockMultipartFile(htmlInputName, "exceptionImage.jpg", "jpg", fileBytes), new MockMultipartFile(htmlInputName, "exceptionImage.avi", "avi", fileBytes), new MockMultipartFile(htmlInputName, fileName, fileType, new byte[1024 * 1024 * 6]) };
for (MockMultipartFile file : files) {
try {
mockMvc.perform(MockMvcRequestBuilders.fileUpload("/api/file/avatar").file(file).cookie(util.getAlreadyLoginUserCookie()).contentType(MediaType.MULTIPART_FORM_DATA_VALUE).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.instanceOf(ParamsErrorException.class));
}
}
util.printSuccessMessage();
}
Aggregations