本文整理汇总了Java中org.springframework.http.MediaType类的典型用法代码示例。如果您正苦于以下问题:Java MediaType类的具体用法?Java MediaType怎么用?Java MediaType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MediaType类属于org.springframework.http包,在下文中一共展示了MediaType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testHttpAddSuccess
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
public void testHttpAddSuccess() throws Exception {
final SapClient sapClient = mockSdk.getErpSystem().getSapClient();
final String newCostCenterJson = getNewCostCenterAsJson(DEMO_COSTCENTER_ID);
final RequestBuilder newCostCenterRequest = MockMvcRequestBuilders
.request(HttpMethod.POST, "/api/v1/rest/client/"+sapClient+"/controllingarea/"+DEMO_CONTROLLING_AREA+"/costcenters")
.param("testRun", "true")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(newCostCenterJson);
mockSdk.requestContextExecutor().execute(new Executable() {
@Override
public void execute() throws Exception {
mockMvc.perform(newCostCenterRequest).andExpect(MockMvcResultMatchers.status().isOk());
}
});
}
示例2: loadVariation
import org.springframework.http.MediaType; //导入依赖的package包/类
@ResponseBody
@RequestMapping(value = "/vcf/variation/load", method = RequestMethod.POST)
@ApiOperation(
value = "Returns extended data for a variation",
notes = "Provides extended data about the particular variation: </br>" +
"info field : Additional information that is presented in INFO column</br>" +
"genotypeInfo field : Genotype information for a specific sample</br>",
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(
value = {@ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION)
})
public Result<Variation> loadVariation(@RequestBody final VariationQuery query,
@RequestParam(required = false) final String fileUrl,
@RequestParam(required = false) final String indexUrl)
throws FeatureFileReadingException {
if (fileUrl == null) {
return Result.success(vcfManager.loadVariation(query));
} else {
return Result.success(vcfManager.loadVariation(query, fileUrl, indexUrl));
}
}
示例3: addEmployee
import org.springframework.http.MediaType; //导入依赖的package包/类
@RequestMapping(value = "/employee", method = { RequestMethod.POST }, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MyResponse> addEmployee(@RequestBody Employee employee) {
MyResponse resp = new MyResponse();
empService.create(employee);
if(HttpStatus.OK.is2xxSuccessful()){
resp.setStatus(HttpStatus.OK.value());
resp.setMessage("Succesfuly created an employee object");
return new ResponseEntity<MyResponse>(resp, HttpStatus.OK);
}
else{
resp.setStatus(HttpStatus.OK.value());
resp.setMessage("Error while creating an employee object");
return new ResponseEntity<MyResponse>(resp, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
示例4: testSaveTalker
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
public void testSaveTalker() throws Exception{
String talkerAsJson = this.mapper.writeValueAsString(this.talkerAny);
when(this.talkerServiceMock.save(this.talkerAny)).thenReturn(this.talkerAny);
ResultActions resultActions = mockMvc.perform(post("/api/talker")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(talkerAsJson))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
assertNotNull("[resultActions] should not be null", resultActions);
MockHttpServletResponse response = resultActions.andReturn().getResponse();
assertNotNull("[ContentAsString] should not be null", response.getContentAsString());
Talker talkerFromJson = this.mapper.readValue(response.getContentAsString(), Talker.class);
assertEquals("[talkerFromJson] should be equals to [talkerAny]", this.talkerAny, talkerFromJson);
verify(this.talkerServiceMock, times(1)).save(this.talkerAny);
}
示例5: testListenTalkBasic
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
public void testListenTalkBasic() throws Exception {
Phrase phrase = new Phrase();
phrase.setAppContext("app_context");
phrase.setUrl("the_url");
phrase.setResponse(JSON_RESPONSE);
Gson gson = new Gson();
String json = gson.toJson(phrase);
// Listen
mockMvc.perform(post("/listen").contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk())
.andExpect(content().string("OK"));
// Talk
mockMvc.perform(get("/talk/app_context/the_url"))
.andExpect(status().isOk())
.andExpect(content().string(JSON_RESPONSE));
}
示例6: testAddPrivilegeToRole
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
public void testAddPrivilegeToRole() throws Exception {
final RoleEntity role = new RoleEntity()
.setId("role123")
.setCode("role123");
when(roleService.addPrivilegeToRole("role123", "privilege123")).thenReturn(role);
ResultActions resultActions = mockMvc.perform(put("/api/roles/role123/privileges")
.content("{\"privilege\": \"privilege123\"}")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("role-privilege-create"));
MockHttpServletResponse response = resultActions
.andReturn()
.getResponse();
verify(roleService).addPrivilegeToRole("role123", "privilege123");
assertThat(response.getContentAsByteArray())
.isEqualTo(objectMapper.writeValueAsBytes(RoleRestData.builder().fromRoleEntity(role).build()));
}
示例7: canRead
import org.springframework.http.MediaType; //导入依赖的package包/类
@Override
public boolean canRead(Type type, Class<?> contextClass, MediaType mediaType) {
if (!canRead(mediaType)) {
return false;
}
JavaType javaType = getJavaType(type, contextClass);
if (!jackson23Available || !logger.isWarnEnabled()) {
return this.objectMapper.canDeserialize(javaType);
}
AtomicReference<Throwable> causeRef = new AtomicReference<Throwable>();
if (this.objectMapper.canDeserialize(javaType, causeRef)) {
return true;
}
Throwable cause = causeRef.get();
if (cause != null) {
String msg = "Failed to evaluate Jackson deserialization for type " + javaType;
if (logger.isDebugEnabled()) {
logger.warn(msg, cause);
}
else {
logger.warn(msg + ": " + cause);
}
}
return false;
}
开发者ID:JetBrains,项目名称:teamcity-hashicorp-vault-plugin,代码行数:26,代码来源:AbstractJackson2HttpMessageConverter.java
示例8: name
import org.springframework.http.MediaType; //导入依赖的package包/类
@ResponseBody
@RequestMapping(value = "/externaldb/ncbi/variation/region", method = RequestMethod.POST)
@ApiOperation(
value = "NCBI: Retrieves information on variations located in given interval",
notes = "NCBI snp database is being queried for variations in given interval" +
"in a proper way and returned by service.<br/><br/>" +
PARAMETERS_NOTE +
"<b>species</b> - species name (e.g. \"human\")<br/>" +
"<b>chromosome</b> - chromosome name (e.g. \"1\")<br/>" +
"<b>start</b> - start coordinate in a given chromosome (e.g. 140424943)<br/>" +
"<b>finish</b> - end coordinate in a given chromosome (e.g. 140624564)<br/>" +
RSID_DESCRIPTION_NOTE,
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(value = { @ApiResponse(code = HTTP_STATUS_OK, message = API_STATUS_DESCRIPTION) })
public Result<List<Variation>> fetchNCBIVariationInfoOnInterval(@RequestBody final RegionQuery regionQuery)
throws ExternalDbUnavailableException {
String chromosome = regionQuery.getChromosome();
String start = regionQuery.getStart();
String finish = regionQuery.getFinish();
String species = regionQuery.getSpecies();
List<Variation> variations = ncbiShortVarManager.fetchVariationsOnRegion(species, start, finish, chromosome);
return Result.success(variations, getMessage(SUCCESS, NCBI));
}
示例9: save
import org.springframework.http.MediaType; //导入依赖的package包/类
@Override
public void save(final String userName, final String secretKey, final int validationCode, final List<Integer> scratchCodes) {
final MultifactorAuthenticationProperties.GAuth.Rest rest = gauth.getRest();
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.put("username", Arrays.asList(userName));
headers.put("validationCode", Arrays.asList(String.valueOf(validationCode)));
headers.put("secretKey", Arrays.asList(secretKey));
headers.put("scratchCodes", scratchCodes.stream().map(String::valueOf).collect(Collectors.toList()));
final HttpEntity<String> entity = new HttpEntity<>(headers);
final ResponseEntity<Boolean> result = restTemplate.exchange(rest.getEndpointUrl(), HttpMethod.POST, entity, Boolean.class);
if (result.getStatusCodeValue() == HttpStatus.OK.value()) {
LOGGER.debug("Posted google authenticator account successfully");
}
LOGGER.warn("Failed to save google authenticator account successfully");
}
示例10: isAccessAllowed
import org.springframework.http.MediaType; //导入依赖的package包/类
@Override
protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
HttpServletRequest request = (HttpServletRequest) servletRequest;
String token = jwtHelper.getToken(request);
String username = jwtHelper.getUsernameFromToken(token);
StatelessToken accessToken = new StatelessToken(username, token);
try {
getSubject(servletRequest, servletResponse).login(accessToken);
} catch (AuthenticationException e) {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
objectMapper.writeValue(response.getWriter(), Result.fail(ResultCode.UNAUTHORIZED));
return false;
}
getSubject(servletRequest, servletResponse).isPermitted(request.getRequestURI());
return true;
}
示例11: getAllOperinoComponents
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
@Transactional
public void getAllOperinoComponents() throws Exception {
// Initialize the database
operinoComponentRepository.saveAndFlush(operinoComponent);
// Get all the operinoComponentList
restOperinoComponentMockMvc.perform(get("/api/operino-components?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(operinoComponent.getId().intValue())))
.andExpect(jsonPath("$.[*].hosting").value(hasItem(DEFAULT_HOSTING.toString())))
.andExpect(jsonPath("$.[*].availability").value(hasItem(DEFAULT_AVAILABILITY.booleanValue())))
.andExpect(jsonPath("$.[*].applyLimits").value(hasItem(DEFAULT_APPLY_LIMITS.booleanValue())))
.andExpect(jsonPath("$.[*].recordsNumber").value(hasItem(DEFAULT_RECORDS_NUMBER.intValue())))
.andExpect(jsonPath("$.[*].transactionsLimit").value(hasItem(DEFAULT_TRANSACTIONS_LIMIT.intValue())))
.andExpect(jsonPath("$.[*].diskSpace").value(hasItem(DEFAULT_DISK_SPACE.intValue())))
.andExpect(jsonPath("$.[*].computeResourceLimit").value(hasItem(DEFAULT_COMPUTE_RESOURCE_LIMIT.intValue())))
.andExpect(jsonPath("$.[*].type").value(hasItem(DEFAULT_TYPE.toString())));
}
示例12: getXmEntity
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
@Transactional
public void getXmEntity() throws Exception {
// Initialize the database
xmEntityRepository.saveAndFlush(xmEntity);
// Get the xmEntity
restXmEntityMockMvc.perform(get("/api/xm-entities/{id}", xmEntity.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(xmEntity.getId().intValue()))
.andExpect(jsonPath("$.key").value(DEFAULT_KEY.toString()))
.andExpect(jsonPath("$.typeKey").value(DEFAULT_TYPE_KEY.toString()))
.andExpect(jsonPath("$.stateKey").value(DEFAULT_STATE_KEY.toString()))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()))
.andExpect(jsonPath("$.startDate").value(DEFAULT_START_DATE.toString()))
.andExpect(jsonPath("$.updateDate").value(DEFAULT_UPDATE_DATE.toString()))
.andExpect(jsonPath("$.endDate").value(DEFAULT_END_DATE.toString()))
.andExpect(jsonPath("$.avatarUrl").value(containsString("aaaaa.jpg")))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
.andExpect(jsonPath("$.data.AAAAAAAAAA").value("BBBBBBBBBB"))
.andExpect(jsonPath("$.removed").value(DEFAULT_REMOVED.booleanValue()));
}
示例13: getMetricsIntervals
import org.springframework.http.MediaType; //导入依赖的package包/类
@RequestMapping ( "/metricIntervals/{type}" )
public void getMetricsIntervals (
@PathVariable ( value = "type" ) String reqType,
HttpServletRequest request, HttpServletResponse response )
throws IOException {
response.setContentType( MediaType.APPLICATION_JSON_VALUE );
ArrayNode samplesArray = jacksonMapper.createArrayNode();
String type = reqType;
if ( reqType.startsWith( "jmx" ) ) {
type = "jmx";
}
for ( Integer sampleInterval : csapApp.lifeCycleSettings()
.getMetricToSecondsMap()
.get( type ) ) {
samplesArray.add( sampleInterval );
}
response.getWriter()
.println( jacksonMapper.writeValueAsString( samplesArray ) );
}
示例14: getStreamer
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
public void getStreamer() throws Exception {
// Initialize the database
streamerRepository.save(streamer);
// Get the streamer
restStreamerMockMvc.perform(get("/api/streamers/{id}", streamer.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(streamer.getId()))
.andExpect(jsonPath("$.provider").value(DEFAULT_PROVIDER))
.andExpect(jsonPath("$.name").value(DEFAULT_NAME))
.andExpect(jsonPath("$.league").value(DEFAULT_LEAGUE))
.andExpect(jsonPath("$.division").value(DEFAULT_DIVISION))
.andExpect(jsonPath("$.titleFilter").value(DEFAULT_TITLE_FILTER))
.andExpect(jsonPath("$.announcement").value(DEFAULT_ANNOUNCEMENT))
.andExpect(jsonPath("$.lastAnnouncement").value(sameInstant(DEFAULT_LAST_ANNOUNCEMENT)))
.andExpect(jsonPath("$.enabled").value(DEFAULT_ENABLED))
.andExpect(jsonPath("$.lastStreamId").value(DEFAULT_LAST_STREAM_ID.intValue()));
}
示例15: getNonExistingAuditsByDate
import org.springframework.http.MediaType; //导入依赖的package包/类
@Test
public void getNonExistingAuditsByDate() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Generate dates for selecting audits by date, making sure the period will not contain the sample audit
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0,10);
String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0,10);
// Query audits but expect no results
restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(header().string("X-Total-Count", "0"));
}