当前位置: 首页>>代码示例>>Java>>正文


Java MediaType类代码示例

本文整理汇总了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());
        }
    });
}
 
开发者ID:SAP,项目名称:cloud-s4-sdk-examples,代码行数:21,代码来源:CostCenterServiceIntegrationTest.java

示例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));
    }
}
 
开发者ID:react-dev26,项目名称:NGB-master,代码行数:22,代码来源:VcfController.java

示例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);
	}
	
}
 
开发者ID:sarojrout,项目名称:spring-tutorial,代码行数:17,代码来源:EmployeeController.java

示例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);
}
 
开发者ID:fabianogoes,项目名称:bruxelas,代码行数:23,代码来源:TalkerRestControllerTest.java

示例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));    
  }
 
开发者ID:davidgamez,项目名称:parrot-rest,代码行数:22,代码来源:ListenTalkMapIT.java

示例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()));
}
 
开发者ID:codenergic,项目名称:theskeleton,代码行数:19,代码来源:RoleRestControllerTest.java

示例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));
}
 
开发者ID:react-dev26,项目名称:NGB-master,代码行数:26,代码来源:ExternalDBController.java

示例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");
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:18,代码来源:RestGoogleAuthenticatorTokenCredentialRepository.java

示例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;
}
 
开发者ID:YupaiTS,项目名称:docs-manage,代码行数:18,代码来源:StatelessAuthcFilter.java

示例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())));
}
 
开发者ID:AppertaFoundation,项目名称:Code4Health-Platform,代码行数:21,代码来源:OperinoComponentResourceIntTest.java

示例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()));
}
 
开发者ID:xm-online,项目名称:xm-ms-entity,代码行数:24,代码来源:XmEntityResourceIntTest.java

示例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 ) );
}
 
开发者ID:csap-platform,项目名称:csap-core,代码行数:25,代码来源:HostRequests.java

示例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()));
}
 
开发者ID:quanticc,项目名称:sentry,代码行数:21,代码来源:StreamerResourceIntTest.java

示例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"));
}
 
开发者ID:deepu105,项目名称:spring-io,代码行数:16,代码来源:AuditResourceIntTest.java


注:本文中的org.springframework.http.MediaType类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。