當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。