下面列出了怎么用org.springframework.http.MediaType的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
@SuppressWarnings("unchecked")
public void normal() throws IOException {
HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(converter);
HttpHeaders responseHeaders = new HttpHeaders();
MediaType contentType = MediaType.TEXT_PLAIN;
responseHeaders.setContentType(contentType);
String expected = "Foo";
extractor = new HttpMessageConverterExtractor<String>(String.class, converters);
given(response.getStatusCode()).willReturn(HttpStatus.OK);
given(response.getHeaders()).willReturn(responseHeaders);
given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
given(converter.canRead(String.class, contentType)).willReturn(true);
given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected);
Object result = extractor.extractData(response);
assertEquals(expected, result);
}
@Test
@Transactional
public void searchEntry() throws Exception {
// Initialize the database
entryRepository.saveAndFlush(entry);
entrySearchRepository.save(entry);
// Search the entry
restEntryMockMvc.perform(get("/api/_search/entries?query=id:" + entry.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(entry.getId().intValue())))
.andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString())))
.andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString())))
.andExpect(jsonPath("$.[*].date").value(hasItem(sameInstant(DEFAULT_DATE))));
}
@Test
@Transactional
public void getAllUsers() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
// Get all the users
restUserMockMvc.perform(get("/api/users?sort=id,desc")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
.andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
.andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
.andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
.andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
}
@ParameterizedTest
@ArgumentsSource(RequestFactorySource.class)
void shouldCompressWithGivenAlgorithm(final ClientHttpRequestFactory factory) {
driver.addExpectation(onRequestTo("/")
.withMethod(POST)
.withHeader("Content-Encoding", "identity") // not handled by Jetty
.withoutHeader("X-Content-Encoding")
.withBody(equalTo("{}"), "application/json"),
giveResponse("", "text/plain"));
final Http http = buildHttp(factory, new RequestCompressionPlugin(Compression.of("identity", it -> it)));
http.post("/")
.contentType(MediaType.APPLICATION_JSON)
.body(new HashMap<>())
.call(pass())
.join();
}
@Test
public void testCTRElementUpdate() throws Exception {
repository.save(new TaskDefinition("a1", "t1: task && t2: task2"));
repository.save(new TaskDefinition("a2", "task"));
repository.save(new TaskDefinition("a1-t1", "task"));
repository.save(new TaskDefinition("a1-t2", "task"));
mockMvc.perform(get("/tasks/definitions/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.content", hasSize(4)))
.andExpect(jsonPath("$.content[0].name", is("a1")))
.andExpect(jsonPath("$.content[0].composedTaskElement", is(false)))
.andExpect(jsonPath("$.content[1].name", is("a2")))
.andExpect(jsonPath("$.content[1].composedTaskElement", is(false)))
.andExpect(jsonPath("$.content[2].name", is("a1-t1")))
.andExpect(jsonPath("$.content[2].composedTaskElement", is(true)))
.andExpect(jsonPath("$.content[3].name", is("a1-t2")))
.andExpect(jsonPath("$.content[3].composedTaskElement", is(true)));
mockMvc.perform(get("/tasks/definitions/a1-t2").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$.name", is("a1-t2")))
.andExpect(jsonPath("$.composedTaskElement", is(true)));
}
/**
* 快速新增服务版本
*
* @throws Exception
*/
@Test
public void test_quick_start_2_addserviceVersion() throws Exception {
// ClassPathResource classPathResource1 = new ClassPathResource("1.yml");
// MockMultipartFile multipartFile1 = new MockMultipartFile("file", "1.yml", "application/octet-stream", classPathResource1.getInputStream());
//
// ClassPathResource classPathResource2 = new ClassPathResource("2.yml");
// MockMultipartFile multipartFile2 = new MockMultipartFile("file", "2.yml", "application/octet-stream", classPathResource2.getInputStream());
//
// ClassPathResource classPathResource3 = new ClassPathResource("3.yml");
// MockMultipartFile multipartFile3 = new MockMultipartFile("file", "3.yml", "application/octet-stream", classPathResource3.getInputStream());
String result = this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/api/v1/quickStart/addServiceVersion")
// .file(multipartFile1)
// .file(multipartFile2)
// .file(multipartFile3)
.param("project", "project1")
.param("cluster", "cluster1")
.param("service", "service1")
.param("version", "1.0.0.2")
.param("desc", "版本描述")
.contentType(MediaType.MULTIPART_FORM_DATA)
.session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
.accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
.andReturn().getResponse().getContentAsString();
Utils.assertResult(result);
}
@Test
void getBindingToAppSucceeds() throws Exception {
setupServiceInstanceBindingService(GetServiceInstanceAppBindingResponse.builder()
.build());
MvcResult mvcResult = mockMvc.perform(get(buildCreateUrl(PLATFORM_INSTANCE_ID, false))
.header(API_INFO_LOCATION_HEADER, API_INFO_LOCATION)
.header(ORIGINATING_IDENTITY_HEADER, buildOriginatingIdentityHeader())
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(request().asyncStarted())
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk());
GetServiceInstanceBindingRequest actualRequest = verifyGetBinding();
assertHeaderValuesSet(actualRequest);
}
@Test
public void shouldTryCreateRestDestinationWithBadRequest() throws Exception {
when(
restDestinationService
.register(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(RestDestination.class)))
.thenReturn(ServiceResponseBuilder
.<RestDestination>error()
.withMessage(RestDestinationService.Validations.DESTINATION_NOT_FOUND.getCode())
.build());
getMockMvc()
.perform(MockMvcRequestBuilders.post(MessageFormat.format("/{0}/{1}/", application.getName(), BASEPATH))
.content(getJson(new RestDestinationVO().apply(restDestination1)))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is4xxClientError())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value())))
.andExpect(jsonPath("$.status", is("error")))
.andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
.andExpect(jsonPath("$.messages").exists())
.andExpect(jsonPath("$.result").doesNotExist());
}
public User createViewer(String username, List<Long> userGroups) throws Exception {
User u1 = new User();
u1.setUsername(username);
u1.setName("n1");
u1.setTempPassword("t1");
u1.setUserGroups(userGroups);
u1.setSysRole(Constants.SYS_ROLE_VIEWER);
String body = mapper.writeValueAsString(u1);
mvcResult = this.mvc.perform(
post("/ws/users")
.contentType(MediaType.APPLICATION_JSON)
.requestAttr(Constants.HTTP_REQUEST_ATTR_USER, adminUser)
.content(body)
)
.andExpect(status().isCreated())
.andReturn();
long id = Long.parseLong(mvcResult.getResponse().getContentAsString());
u1.setId(id);
return u1;
}
@Test
public void shouldTryDeleteNonexistentDeviceConfig() throws Exception {
when(deviceConfigSetupService.remove(tenant, application, deviceModel, location))
.thenReturn(ServiceResponseBuilder.<DeviceConfigSetup> error()
.withMessage(DeviceConfigSetupService.Validations.DEVICE_CONFIG_NOT_FOUND.getCode())
.build());
getMockMvc().perform(MockMvcRequestBuilders
.delete(MessageFormat.format("/{0}/{1}/{2}/{3}/", application.getName(), BASEPATH, deviceModel.getName(), location.getName()))
.contentType("application/json")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is4xxClientError())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
.andExpect(jsonPath("$.status", is("error")))
.andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
.andExpect(jsonPath("$.messages").exists())
.andExpect(jsonPath("$.result").doesNotExist());
}
@Test
public void responseBodyAdvice() throws Exception {
List<HttpMessageConverter<?>> converters = new ArrayList<>();
converters.add(new MappingJackson2HttpMessageConverter());
this.handlerAdapter.setMessageConverters(converters);
this.webAppContext.registerSingleton("rba", ResponseCodeSuppressingAdvice.class);
this.webAppContext.refresh();
this.request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
this.request.setParameter("c", "callback");
HandlerMethod handlerMethod = handlerMethod(new SimpleController(), "handleBadRequest");
this.handlerAdapter.afterPropertiesSet();
this.handlerAdapter.handle(this.request, this.response, handlerMethod);
assertEquals(200, this.response.getStatus());
assertEquals("{\"status\":400,\"message\":\"body\"}", this.response.getContentAsString());
}
private Properties getDefaultMediaTypes() {
Properties defaultMediaTypes = new Properties();
if (romePresent) {
defaultMediaTypes.put("atom", MediaType.APPLICATION_ATOM_XML_VALUE);
defaultMediaTypes.put("rss", MediaType.APPLICATION_RSS_XML_VALUE);
}
if (jaxb2Present || jackson2XmlPresent) {
defaultMediaTypes.put("xml", MediaType.APPLICATION_XML_VALUE);
}
if (jackson2Present || gsonPresent) {
defaultMediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE);
}
if (jackson2SmilePresent) {
defaultMediaTypes.put("smile", "application/x-jackson-smile");
}
if (jackson2CborPresent) {
defaultMediaTypes.put("cbor", "application/cbor");
}
return defaultMediaTypes;
}
@Test
public void delete_page_model_return_OK() throws Exception {
PageModel pageModel = new PageModel();
pageModel.setCode(PAGE_MODEL_CODE);
pageModel.setDescription(PAGE_MODEL_CODE);
this.pageModelManager.addPageModel(pageModel);
ResultActions result = mockMvc.perform(
delete("/pageModels/{code}", PAGE_MODEL_CODE)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.header("Authorization", "Bearer " + accessToken));
result.andExpect(status().isOk());
}
@Test
public void testMethodArgumentNotValid() throws Exception {
mockMvc.perform(post("/api/exception-translator-test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION))
.andExpect(jsonPath("$.fieldErrors.[0].objectName").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].field").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull"));
}
@PutMapping( path = "/{id}", consumes = MediaType.APPLICATION_XML_VALUE, produces = APPLICATION_XML_VALUE )
public ImportSummary updateRelationshipXml(
@PathVariable String id,
ImportOptions importOptions,
HttpServletRequest request
)
throws IOException
{
InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() );
ImportSummary importSummary = relationshipService.updateRelationshipXml( id, inputStream, importOptions );
importSummary.setImportOptions( importOptions );
return importSummary;
}
@Test
public void adminLoads() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = new TestRestTemplate().exchange(
"http://localhost:" + this.port + "/env", HttpMethod.GET,
new HttpEntity<>("parameters", headers), Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
}
@ApiOperation(value = "getAllBrokers", notes = "Get details for all known Kafka brokers")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success", response = BrokerVO.class)
})
@RequestMapping(path = "/broker", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET)
public @ResponseBody List<BrokerVO> brokerDetailsJson()
{
return kafkaMonitor.getBrokers();
}
@Test
public void compose() throws Exception {
ResponseEntity<String> result = this.rest.exchange(RequestEntity
.get(new URI("/concat,reverse/foo")).accept(MediaType.TEXT_PLAIN).build(),
String.class);
assertThat(result.getBody()).isEqualTo("oofoof");
}
@Test
public void testGetPlants() throws Exception {
mockMvc.perform(get("/api/plants").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.plants", Matchers.hasSize(9)));
}
/**
* Assert the request content type as a {@link MediaType}.
*/
public RequestMatcher contentType(final MediaType expectedContentType) {
return request -> {
MediaType actualContentType = request.getHeaders().getContentType();
assertTrue("Content type not set", actualContentType != null);
assertEquals("Content type", expectedContentType, actualContentType);
};
}
/**
* Executes the search, and checks that the default entity is not returned
*/
private void defaultDimensionShouldNotBeFound(String filter) throws Exception {
restDimensionMockMvc.perform(get("/api/dimensions?sort=id,desc&" + filter))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").isEmpty());
}
@Test
public void shouldTestGetPageModelUsage() throws Exception {
String code = "home";
mockMvc.perform(get("/pageModels/{code}/usage", code)
.contentType(MediaType.APPLICATION_JSON_VALUE)
.header("Authorization", "Bearer " + accessToken))
.andExpect(status().isOk())
.andExpect(jsonPath("$.payload.type", is(PageModelController.COMPONENT_ID)))
.andExpect(jsonPath("$.payload.code", is(code)))
.andExpect(jsonPath("$.payload.usage", is(25)))
.andReturn();;
}
/**
* Assert the ServletResponse content type is compatible with the given
* content type as defined by {@link MediaType#isCompatibleWith(MediaType)}.
*/
public ResultMatcher contentTypeCompatibleWith(final MediaType contentType) {
return result -> {
String actual = result.getResponse().getContentType();
assertTrue("Content type not set", actual != null);
if (actual != null) {
MediaType actualContentType = MediaType.parseMediaType(actual);
assertTrue("Content type [" + actual + "] is not compatible with [" + contentType + "]",
actualContentType.isCompatibleWith(contentType));
}
};
}
/**
* Return the more specific of the acceptable and the producible media types with the
* q-value of the former.
*/
private MediaType getMostSpecificMediaType(MediaType acceptType,
MediaType produceType) {
MediaType produceTypeToUse = produceType.copyQualityValue(acceptType);
return (MediaType.SPECIFICITY_COMPARATOR.compare(acceptType,
produceTypeToUse) <= 0 ? acceptType : produceTypeToUse);
}
/**
* 配置列表
*
* @return json
*/
@RequestMapping(value = "list_data.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String list(String whitePath, String name) {
if (whitelistDirectoryService.checkNgxDirectory(whitePath)) {
if (StrUtil.isEmpty(name)) {
name = "/";
}
String newName = pathSafe(name);
JSONArray array = nginxService.list(whitePath, newName);
return JsonMessage.getString(200, "", array);
}
return JsonMessage.getString(400, "文件路径错误");
}
/**
* DELETE /race-results/:id : delete the "id" raceResult.
*
* @param id the id of the raceResult to delete
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/race-results/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> deleteRaceResult(@PathVariable String id) {
log.debug("REST request to delete RaceResult : {}", id);
raceResultRepository.delete(UUID.fromString(id));
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("raceResult", id.toString())).build();
}
/**
* POST /things -> Create a new thing.
*/
@RequestMapping(value = "/things",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> create(@RequestBody Thing thing) throws URISyntaxException {
log.debug("REST request to save Thing : {}", thing);
if (thing.getId() != null) {
return ResponseEntity.badRequest().header("Failure", "A new thing cannot already have an ID").build();
}
thingRepository.save(thing);
return ResponseEntity.created(new URI("/api/things/" + thing.getId())).build();
}
@Test
public void createTodo_withValidationError() throws Exception {
Todo mockTodo = new Todo(CREATED_TODO_ID, "Jack", "Learn Spring MVC", new Date(), false);
String todo = "{\"user\":\"Jack\",\"desc\":\"Learn\",\"done\":\"false\"}";
when(service.addTodo(anyString(), anyString(), isNull(), anyBoolean())).thenReturn(mockTodo);
MvcResult result = mvc.perform(
MockMvcRequestBuilders.post("/users/Jack/todos").content(todo).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is4xxClientError()).andReturn();
}
@Override
public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
if (!MultiValueMap.class.isAssignableFrom(elementType.toClass())) {
return false;
}
if (MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(mediaType)) {
// Optimistically, any MultiValueMap with or without generics
return true;
}
if (mediaType == null) {
// Only String-based MultiValueMap
return MULTIVALUE_TYPE.isAssignableFrom(elementType);
}
return false;
}
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<GuiFragmentDto>> addGuiFragment(@Valid @RequestBody GuiFragmentRequestBody guiFragmentRequest, BindingResult bindingResult) throws ApsSystemException {
//field validations
if (bindingResult.hasErrors()) {
throw new ValidationGenericException(bindingResult);
}
//business validations
this.getGuiFragmentValidator().validate(guiFragmentRequest, bindingResult);
if (bindingResult.hasErrors()) {
throw new ValidationGenericException(bindingResult);
}
GuiFragmentDto fragment = this.getGuiFragmentService().addGuiFragment(guiFragmentRequest);
return new ResponseEntity<>(new SimpleRestResponse<>(fragment), HttpStatus.OK);
}