Java Code Examples for org.springframework.http.MediaType

The following are top voted examples for showing how to use org.springframework.http.MediaType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: NGB-master   File: VcfController.java   Source Code and License 7 votes vote down vote up
@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));
    }
}
 
Example 2
Project: cloud-s4-sdk-examples   File: CostCenterServiceIntegrationTest.java   Source Code and License 7 votes vote down vote up
@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());
        }
    });
}
 
Example 3
Project: spring-tutorial   File: EmployeeController.java   Source Code and License 7 votes vote down vote up
@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);
	}
	
}
 
Example 4
Project: bruxelas   File: TalkerRestControllerTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 5
Project: parrot-rest   File: ListenTalkMapIT.java   Source Code and License 6 votes vote down vote up
@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));    
  }
 
Example 6
Project: theskeleton   File: RoleRestControllerTest.java   Source Code and License 6 votes vote down vote up
@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()));
}
 
Example 7
Project: teamcity-hashicorp-vault-plugin   File: AbstractJackson2HttpMessageConverter.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 8
Project: NGB-master   File: ExternalDBController.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 9
Project: cas-5.1.0   File: RestGoogleAuthenticatorTokenCredentialRepository.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 10
Project: docs-manage   File: StatelessAuthcFilter.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 11
Project: Code4Health-Platform   File: OperinoComponentResourceIntTest.java   Source Code and License 6 votes vote down vote up
@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())));
}
 
Example 12
Project: xm-ms-entity   File: XmEntityResourceIntTest.java   Source Code and License 6 votes vote down vote up
@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()));
}
 
Example 13
Project: csap-core   File: HostRequests.java   Source Code and License 6 votes vote down vote up
@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 ) );
}
 
Example 14
Project: sentry   File: StreamerResourceIntTest.java   Source Code and License 6 votes vote down vote up
@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()));
}
 
Example 15
Project: spring-io   File: AuditResourceIntTest.java   Source Code and License 5 votes vote down vote up
@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"));
}
 
Example 16
Project: document-management-store-app   File: ThumbnailTest.java   Source Code and License 5 votes vote down vote up
@Test
public void should_upload_a_gif_ani_and_retrieve_a_supported_image_thumbnail() throws Exception {
    final MockHttpServletResponse response = mvc.perform(fileUpload("/documents")
        .file(gifAniFile)
        .param("classification", Classifications.PRIVATE.toString())
        .headers(headers))
        .andReturn().getResponse();

    final String url = getThumbnailUrlFromResponse(response);

    mvc.perform(get(url)
        .headers(headers))
        .andExpect(content().contentType(MediaType.IMAGE_JPEG_VALUE));
}
 
Example 17
Project: DAFramework   File: AccountControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void get() throws Exception {
	MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/account/get/1").accept(MediaType.APPLICATION_JSON)).andReturn();
	int status = mvcResult.getResponse().getStatus();
	String content = mvcResult.getResponse().getContentAsString();
	System.out.println(status + "--" + content);
}
 
Example 18
Project: buenojo   File: UserProfileResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /userProfiles/:id -> get the "id" userProfile.
 */
@RequestMapping(value = "/userProfiles/{id}",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<UserProfile> getUserProfile(@PathVariable Long id) {
    log.debug("REST request to get UserProfile : {}", id);
    return Optional.ofNullable(userProfileRepository.findOne(id))
        .map(userProfile -> new ResponseEntity<>(
            userProfile,
            HttpStatus.OK))
        .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
 
Example 19
Project: graphium   File: GraphVersionImportHttpNotifierImpl.java   Source Code and License 5 votes vote down vote up
private void updateGraphVersionState(String url, String graphName, String version, State state, Integer segmentsCount) throws RestClientException {
		Map<String, Object> requestParams = new HashMap<String, Object>();

		String graphVersionStateUpdateUrl = createSetGraphVersionStateUrl(url, graphName, version, state.toString(), segmentsCount);
// TODO: Set Credentials
		HttpHeaders headers = getHeaders(graphVersionStateUpdateUrl); //, subscription.getUser(), subscription.getPassword());
		headers.setContentType(MediaType.APPLICATION_JSON);
		
		HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String,Object>>(requestParams, 
				headers);
		restTemplate.put(graphVersionStateUpdateUrl, request);	
	}
 
Example 20
Project: buenojo   File: ImageCompletionExerciseResource.java   Source Code and License 5 votes vote down vote up
/**
 * POST  /imageCompletionExercises -> Create a new imageCompletionExercise.
 */
@RequestMapping(value = "/imageCompletionExercises",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<ImageCompletionExercise> createImageCompletionExercise(@RequestBody ImageCompletionExercise imageCompletionExercise) throws URISyntaxException {
    log.debug("REST request to save ImageCompletionExercise : {}", imageCompletionExercise);
    if (imageCompletionExercise.getId() != null) {
        return ResponseEntity.badRequest().header("Failure", "A new imageCompletionExercise cannot already have an ID").body(null);
    }
    ImageCompletionExercise result = imageCompletionExerciseRepository.save(imageCompletionExercise);
    return ResponseEntity.created(new URI("/api/imageCompletionExercises/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert("imageCompletionExercise", result.getId().toString()))
        .body(result);
}
 
Example 21
Project: ponto-inteligente-api   File: LancamentoControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
@WithMockUser(username = "[email protected]", roles = {"ADMIN"})
public void testRemoverLancamento() throws Exception {
	BDDMockito.given(this.lancamentoService.buscarPorId(Mockito.anyLong())).willReturn(Optional.of(new Lancamento()));

	mvc.perform(MockMvcRequestBuilders.delete(URL_BASE + ID_LANCAMENTO)
			.accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk());
}
 
Example 22
Project: Spring-cloud-gather   File: AccountControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldRegisterNewAccount() throws Exception {

	final User user = new User();
	user.setUsername("test");
	user.setPassword("password");

	String json = mapper.writeValueAsString(user);
	System.out.println(json);
	mockMvc.perform(post("/").principal(new UserPrincipal("test")).contentType(MediaType.APPLICATION_JSON).content(json))
			.andExpect(status().isOk());
}
 
Example 23
Project: buenojo   File: MultipleChoiceAnswerResource.java   Source Code and License 5 votes vote down vote up
/**
 * POST  /multipleChoiceAnswers -> Create a new multipleChoiceAnswer.
 */
@RequestMapping(value = "/multipleChoiceAnswers",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<MultipleChoiceAnswer> createMultipleChoiceAnswer(@Valid @RequestBody MultipleChoiceAnswer multipleChoiceAnswer) throws URISyntaxException {
    log.debug("REST request to save MultipleChoiceAnswer : {}", multipleChoiceAnswer);
    if (multipleChoiceAnswer.getId() != null) {
        return ResponseEntity.badRequest().header("Failure", "A new multipleChoiceAnswer cannot already have an ID").body(null);
    }
    MultipleChoiceAnswer result = multipleChoiceAnswerRepository.save(multipleChoiceAnswer);
    return ResponseEntity.created(new URI("/api/multipleChoiceAnswers/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert("multipleChoiceAnswer", result.getId().toString()))
        .body(result);
}
 
Example 24
Project: NutriBuddi   File: ImageStepsDelete.java   Source Code and License 5 votes vote down vote up
@When("^Jenny deletes an image$")
public void jennyDeletesAnImage() throws Throwable {
    String userAuthorization = "Basic " + Base64.getEncoder().encodeToString(("user" + ":" + "default").getBytes());
    response = mockMvc.perform(get("http://localhost:8080/imageClassifier/deleteImage")
            .header("Authorization", userAuthorization)
            .param("email", "[email protected]")
            .param("fileName", "ChihuahuaOrMuffin")
            .accept(MediaType.APPLICATION_JSON));
}
 
Example 25
Project: buenojo   File: HangManExerciseHintResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /hangManExerciseHints -> get all the hangManExerciseHints.
 */
@RequestMapping(value = "/hangManExerciseHints",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<HangManExerciseHint> getAllHangManExerciseHints() {
    log.debug("REST request to get all HangManExerciseHints");
    return hangManExerciseHintRepository.findAll();
}
 
Example 26
Project: todo-app-java-on-azure   File: TodoListController.java   Source Code and License 5 votes vote down vote up
/**
 * HTTP GET ALL
 */
@RequestMapping(value = "/api/todolist", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<?> getAllTodoItems() {
    try {
        return new ResponseEntity<List<TodoItem>>(todoItemRepository.findAll(), HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<String>("Nothing found", HttpStatus.NOT_FOUND);
    }
}
 
Example 27
Project: xmanager   File: CommonsController.java   Source Code and License 5 votes vote down vote up
/**
 * ueditor编辑器
 */
@RequestMapping("ueditor")
public ResponseEntity<String> ueditor(HttpServletRequest request) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_HTML);
    String json = ueditorService.exec(request);
    return new ResponseEntity<String>(json, headers, HttpStatus.OK);
}
 
Example 28
Project: AngularAndSpring   File: BitfinexController.java   Source Code and License 5 votes vote down vote up
@GetMapping("/{currpair}/orderbook")
public Mono<String> getOrderbook(@PathVariable String currpair,HttpServletRequest request) {
	if(!WebUtils.checkOBRequest(request, WebUtils.LASTOBCALLBF)) {
		return Mono.just("{\n" + 
				"  \"bids\":[],\n" + 
				"  \"asks\":[]\n" + 
				"}");
	}
	WebClient wc = WebUtils.buildWebClient(URLBF);
	return wc.get().uri("/v1/book/"+currpair+"/").accept(MediaType.APPLICATION_JSON).exchange().flatMap(res -> res.bodyToMono(String.class));
}
 
Example 29
Project: document-management-store-app   File: ThumbnailTest.java   Source Code and License 5 votes vote down vote up
@Test
public void should_upload_a_jpg_and_retrieve_a_supported_image_thumbnail() throws Exception {
    final MockHttpServletResponse response = mvc.perform(fileUpload("/documents")
        .file(jpgFile)
        .param("classification", Classifications.PRIVATE.toString())
        .headers(headers))
        .andReturn().getResponse();

    final String url = getThumbnailUrlFromResponse(response);

    mvc.perform(get(url)
        .headers(headers))
        .andExpect(content().contentType(MediaType.IMAGE_JPEG_VALUE));
}
 
Example 30
Project: xmanager   File: IndexTest.java   Source Code and License 5 votes vote down vote up
/**
 * 参考链接:Spring MVC测试框架详解——服务端测试
 * <URL>http://jinnianshilongnian.iteye.com/blog/2004660</URL>
 */
@Test
public void index() throws Exception {
	MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders
			.get("/")
			.accept(MediaType.TEXT_HTML))
			.andDo(MockMvcResultHandlers.print())
			.andReturn();
}
 
Example 31
Project: api-webhook-sample-application   File: Client.java   Source Code and License 5 votes vote down vote up
public Client build() {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    //prepare ROPC request
    MultiValueMap<String, String> params = new LinkedMultiValueMap();
    params.add(CLIENT_ID_PARAM, clientId);
    params.add(CLIENT_SECRET_PARAM, clientSecret);
    params.add(GRANT_TYPE_PARAM, "password");
    params.add(USERNAME_PARAM, username);
    params.add(PASSWORD_PARAM, password);

    System.out.println("PARAMS: " + params.toString());
    RestTemplate restTemplate = new RestTemplate();
    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity(params, headers);

    String tokenUrl = String.format("%s/oauth2/v1/token", baseUrl);
    System.out.println("tokenURL: " + tokenUrl);

    try {
        //obtain access token and return client instance
        Client client = restTemplate
                .exchange(tokenUrl, HttpMethod.POST, entity, Client.class)
                .getBody();
        client.init(baseUrl);
        return client;
    }
    catch(Exception ex){
        ex.printStackTrace();
        return null;
    }
}
 
Example 32
Project: lams   File: BufferedImageHttpMessageConverter.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the default {@code Content-Type} to be used for writing.
 * @throws IllegalArgumentException if the given content type is not supported by the Java Image I/O API
 */
public void setDefaultContentType(MediaType defaultContentType) {
	Assert.notNull(defaultContentType, "'contentType' must not be null");
	Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(defaultContentType.toString());
	if (!imageWriters.hasNext()) {
		throw new IllegalArgumentException(
				"Content-Type [" + defaultContentType + "] is not supported by the Java Image I/O API");
	}

	this.defaultContentType = defaultContentType;
}
 
Example 33
Project: buenojo   File: ExerciseTipResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /exerciseTips/:id -> get the "id" exerciseTip.
 */
@RequestMapping(value = "/exerciseTips/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<ExerciseTip> getExerciseTip(@PathVariable Long id) {
    log.debug("REST request to get ExerciseTip : {}", id);
    return Optional.ofNullable(exerciseTipRepository.findOne(id))
        .map(exerciseTip -> new ResponseEntity<>(
            exerciseTip,
            HttpStatus.OK))
        .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
 
Example 34
Project: spring-io   File: SubCategoryResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void getSubCategory() throws Exception {
    // Initialize the database
    subCategoryRepository.saveAndFlush(subCategory);

    // Get the subCategory
    restSubCategoryMockMvc.perform(get("/api/sub-categories/{id}", subCategory.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.id").value(subCategory.getId().intValue()))
        .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString()));
}
 
Example 35
Project: buenojo   File: MultipleChoiceAnswerResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void getMultipleChoiceAnswer() throws Exception {
    // Initialize the database
    multipleChoiceAnswerRepository.saveAndFlush(multipleChoiceAnswer);

    // Get the multipleChoiceAnswer
    restMultipleChoiceAnswerMockMvc.perform(get("/api/multipleChoiceAnswers/{id}", multipleChoiceAnswer.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.id").value(multipleChoiceAnswer.getId().intValue()))
        .andExpect(jsonPath("$.answer").value(DEFAULT_ANSWER.toString()))
        .andExpect(jsonPath("$.isRight").value(DEFAULT_IS_RIGHT.booleanValue()))
        .andExpect(jsonPath("$.source").value(DEFAULT_SOURCE.toString()));
}
 
Example 36
Project: devoxxus-jhipster-microservices-demo   File: AccountResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNonAuthenticatedUser() throws Exception {
    restUserMockMvc.perform(get("/api/authenticate")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().string(""));
}
 
Example 37
Project: klask-io   File: ProjectResource.java   Source Code and License 5 votes vote down vote up
/**
 * SEARCH  /_search/projects?query=:query : search for the project corresponding
 * to the query.
 *
 * @param query the query of the project search
 * @return the result of the search
 */
@RequestMapping(value = "/projects",
    method = RequestMethod.GET,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<ProjectDTO>> searchprojects(@RequestParam(required = false) String query)
    throws URISyntaxException {
    log.debug("REST request to search projects for query {}", query);
    Map<String, Long> projects = customSearchRepository.aggregateByRawField("project", query);
    List<ProjectDTO> listProjectDTO = new LinkedList<>();
    projects.forEach((key, value) -> listProjectDTO.add(new ProjectDTO(key, value)));
    return new ResponseEntity<>(listProjectDTO, HttpStatus.OK);
}
 
Example 38
Project: homer   File: UserRestController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value="/users", method=RequestMethod.POST, produces={ MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Object> createUser(@Valid @RequestBody User user) {
    User maybeUser = userRepository.findByEmail(user.getEmail());
    if (maybeUser != null) return ResponseEntity
            .status(HttpStatus.BAD_REQUEST)
            .contentType(MediaType.APPLICATION_JSON)
            .body("{ \"error\" : \"User already exist\" }");
    return ResponseEntity.ok(userRepository.save(user));
}
 
Example 39
Project: Armory   File: AuditResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getAllAudits() throws Exception {
    // Initialize the database
    auditEventRepository.save(auditEvent);

    // Get all the audits
    restAuditMockMvc.perform(get("/management/audits"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
 
Example 40
Project: xm-ms-entity   File: ContentResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void getContent() throws Exception {
    // Initialize the database
    contentRepository.saveAndFlush(content);

    // Get the content
    restContentMockMvc.perform(get("/api/contents/{id}", content.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.id").value(content.getId().intValue()))
        .andExpect(jsonPath("$.value").value(Base64Utils.encodeToString(DEFAULT_VALUE)));
}
 
Example 41
Project: Spring-5.0-Cookbook   File: TestReactService.java   Source Code and License 5 votes vote down vote up
@Test
  public void testDeptByIdRouter(){
  	
  	
  	FluxExchangeResult<Department> result = webTestClient.get().uri("http://localhost:8901/selectDeptById/359").accept(MediaType.APPLICATION_JSON_UTF8)
  			.exchange().returnResult(Department.class);
  	assertEquals( result.getStatus().value(), 200);
Department dept = result.getResponseBody().blockFirst();
System.out.println(dept.getName());

  }
 
Example 42
Project: buenojo   File: PhotoLocationExtraSatelliteImageResource.java   Source Code and License 5 votes vote down vote up
/**
   * POST  /photoLocationExtraSatelliteImages/upload/:id -> Create a new photoLocationExtraSatelliteImage.
   * @throws BuenOjoCSVParserException 
   * @throws IOException 
   */
  @RequestMapping(value = "/photoLocationExtraSatelliteImages/upload/{id}",
      method = RequestMethod.POST,
      produces = MediaType.APPLICATION_JSON_VALUE)
  @Timed
  public ResponseEntity<Void> createSatelliteImagesFromCSVForCourse (@PathVariable Long id, @RequestParam("file") MultipartFile csvMetadataFile) throws URISyntaxException, IOException, BuenOjoCSVParserException {
      log.debug("REST request to save PhotoLocationExtraImages from CSV");
     
      if (csvMetadataFile == null)
  		return ResponseEntity.badRequest().headers(HeaderUtil.createBadRequestHeaderAlert("CSV file parameter missing")).body(null);
      
      Course course = courseRepository.findOne(id);
      
      if (course == null) {
      	return ResponseEntity.badRequest().headers(HeaderUtil.createBadRequestHeaderAlert("No course with ID "+id)).body(null);
      }
      Set<PhotoLocationSatelliteImage> images  = annotatedResourceFactory.importSatelliteImageKeywordsFromCSV(csvMetadataFile);
      
      
      ArrayList<PhotoLocationExtraSatelliteImage> result = new ArrayList<>(images.size());
      
      for (PhotoLocationSatelliteImage photoLocationExtraSatelliteImage : images) {
	
      	PhotoLocationExtraSatelliteImage extraImage = new PhotoLocationExtraSatelliteImage();
      	extraImage.setCourse(course);

      	extraImage.setImage(photoLocationExtraSatelliteImage);
      	result.add(extraImage);
      	
}
      photoLocationExtraSatelliteImageRepository.save(result);
      return ResponseEntity.ok()
              .headers(HeaderUtil.createEntitiesCreationAlert("imágenes extra creadas:", new Integer(result.size()).toString())).build();
  }
 
Example 43
Project: buenojo   File: ActivityResource.java   Source Code and License 5 votes vote down vote up
/**
 * POST  /activities -> Create a new activity.
 */
@RequestMapping(value = "/activities",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Activity> createActivity(@Valid @RequestBody Activity activity) throws URISyntaxException {
    log.debug("REST request to save Activity : {}", activity);
    if (activity.getId() != null) {
        return ResponseEntity.badRequest().header("Failure", "A new activity cannot already have an ID").body(null);
    }
    Activity result = activityRepository.save(activity);
    return ResponseEntity.created(new URI("/api/activities/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert("activity", result.getId().toString()))
        .body(result);
}
 
Example 44
Project: loom   File: LoomMvcClient.java   Source Code and License 5 votes vote down vote up
@Override
public QueryResultList getAggregations(final String tapestryId, final List<String> threadIds,
        final boolean noSession) throws LoomClientException {
    try {
        MockHttpServletRequestBuilder requestBuilder =
                MockMvcRequestBuilders.post(ApiConfig.TAPESTRY_BASE + "/" + tapestryId + "/threads/results")
                        .contentType(MediaType.APPLICATION_JSON);

        return perform(requestBuilder, new ObjectMapper().writeValueAsString(threadIds), QueryResultList.class,
                noSession);
    } catch (Exception e) {
        throw new LoomClientException(e);
    }
}
 
Example 45
Project: xm-ms-entity   File: MultipartMixedConverter.java   Source Code and License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void write(MultiValueMap<String, ?> map, MediaType contentType, HttpOutputMessage outputMessage)
    throws IOException {

    if (!isMultipart(map, contentType)) {
        writeForm((MultiValueMap<String, String>) map, contentType, outputMessage);
    } else {
        writeMultipart((MultiValueMap<String, Object>) map, outputMessage);
    }
}
 
Example 46
Project: qpp-conversion-tool   File: ExceptionHandlerControllerV1.java   Source Code and License 5 votes vote down vote up
private ResponseEntity<AllErrors> cope(TransformException exception) {
	HttpHeaders httpHeaders = new HttpHeaders();
	httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

	return new ResponseEntity<>(exception.getDetails(), httpHeaders, HttpStatus.UNPROCESSABLE_ENTITY);
}
 
Example 47
Project: cmc-claim-store   File: AcceptOrRejectOfferTest.java   Source Code and License 5 votes vote down vote up
private ResultActions postRequestTo(String endpoint) throws Exception {
    return webClient
        .perform(
            post(format("/claims/%d/offers/%s/%s", claim.getId(), MadeBy.CLAIMANT.name(), endpoint))
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .header(HttpHeaders.AUTHORIZATION, CLAIMANT_AUTH_TOKEN)
        );
}
 
Example 48
Project: admin-shiro   File: RestTemplateConfig.java   Source Code and License 5 votes vote down vote up
private StringHttpMessageConverter initStringHttpMessageConverter() {
    StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
    supportedMediaTypes.add(new MediaType("text", "plain", Charset.defaultCharset()));
    supportedMediaTypes.add(new MediaType("application", "json", Charset.defaultCharset()));
    supportedMediaTypes.add(new MediaType("text", "html", Charset.defaultCharset()));
    stringHttpMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
    return stringHttpMessageConverter;
}
 
Example 49
Project: sporticus   File: RestControllerOrganisation.java   Source Code and License 5 votes vote down vote up
/**
 * Function to create an Organisation
 * Only a system administrator can create an Organisation
 *
 * @param organisation
 * @return ResponseEntity<DtoOrganisation>
 */
@RequestMapping(value = "", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> create(@RequestBody final DtoOrganisation organisation) {
    LOGGER.debug(() -> "Creating Organisation " + organisation.getName());
    try {
        return new ResponseEntity<>(convertToDtoOrganisation(serviceOrganisation.createOrganisation(getLoggedInUser(), organisation)), HttpStatus.OK);
    } catch (ServiceOrganisationExceptionNotAllowed ex) {
        return new ResponseEntity<>(ex, HttpStatus.FORBIDDEN);
    }
}
 
Example 50
Project: nest-spider   File: WebpageController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/exportTitleContentPairBySpiderUUID.do", method = RequestMethod.GET, produces = "application/octet-stream")
public void exportTitleContentPairBySpiderUUID(String uuid, HttpServletResponse response) throws IOException {
	response.setCharacterEncoding("utf-8");
       response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
       response.setHeader("Content-Disposition", "attachment;fileName=" + new String((uuid).getBytes("UTF-8"), "iso-8859-1") + ".segtxt");
       OutputStream out = response.getOutputStream();
       service.exportTitleContentPairBySpiderUUID(uuid, out);
       out.close();
}
 
Example 51
Project: Armory   File: AccountResourceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetExistingAccount() throws Exception {
    Set<Authority> authorities = new HashSet<>();
    Authority authority = new Authority();
    authority.setName(AuthoritiesConstants.ADMIN);
    authorities.add(authority);

    User user = new User();
    user.setLogin("test");
    user.setFirstName("john");
    user.setLastName("doe");
    user.setEmail("[email protected]");
    user.setImageUrl("http://placehold.it/50x50");
    user.setAuthorities(authorities);
    when(mockUserService.getUserWithAuthorities()).thenReturn(user);

    restUserMockMvc.perform(get("/api/account")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.login").value("test"))
            .andExpect(jsonPath("$.firstName").value("john"))
            .andExpect(jsonPath("$.lastName").value("doe"))
            .andExpect(jsonPath("$.email").value("[email protected]"))
            .andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
            .andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
 
Example 52
Project: blog_post_examples   File: ConfigurationReactiveControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUpdateConfiguration() throws Exception {
    this.webTestClient.put().uri("/configurations")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .syncBody(CONFIG_DOC_AS_JSON_STRING)
            .exchange()
            .expectStatus().isCreated()
            .expectBody()
            .jsonPath("id").isEqualTo("i-am-a-random-id")
            .jsonPath("description").isEqualTo("random description for test case")
            .jsonPath("author").isEqualTo("john doe")
            .jsonPath("name").isEqualTo("configuration test name");
}
 
Example 53
Project: Spring-Security-Third-Edition   File: CalendarApplicationTests.java   Source Code and License 5 votes vote down vote up
@Test
    public void test_failed_Login() throws Exception {
        mvc.perform(post("/login")
                        .accept(MediaType.TEXT_HTML)
                        .contentType(
                                MediaType.APPLICATION_FORM_URLENCODED)
                        .param("username", "[email protected]")
                        .param("password", "bob1")
//                .with(csrf())
        )
                .andExpect(status().is4xxClientError())
                .andDo(print())
        ;
    }
 
Example 54
Project: WIFIProbe   File: StoreHourController.java   Source Code and License 5 votes vote down vote up
@ApiOperation(value = "StoreHours Statistic Detail", notes = "Query detail storeHour statistic data",
        response = Tuple.class, responseContainer = "list",produces = "application/json;charset=UTF-8")
@PostMapping(value = "/detail",produces= MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResultVo<List<Tuple<String, Number>>> getDetails(@Valid @RequestBody QueryJson queryJson) {
    return new ResultVo<>(ServerCode.SUCCESS,
            service.findByHourAndProbe(queryJson.getHour(),queryJson.getProbeId()));
}
 
Example 55
Project: Spring-Shiro-Spark   File: GlobalExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(value = {ResultException.class})
public ResponseEntity<Object> handleException(ResultException ex, HttpServletRequest request) throws URISyntaxException {
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(new URI(request.getRequestURI()));
    headers.setContentType(MediaType.APPLICATION_JSON);
    logger.error("-----exception Handler---Host: {} invokes url: {} ERROR: {} Cause:",request.getRemoteHost(),request.getRequestURL(), ex.getMessage(),ex.getCause());
    return handleExceptionInternal(ex,headers,HttpStatus.INTERNAL_SERVER_ERROR,request);
}
 
Example 56
Project: Spring-Security-Third-Edition   File: CalendarApplicationTests.java   Source Code and License 5 votes vote down vote up
@Test
public void test_user1_Login() throws Exception {
    mockMvc.perform(post("/login")
                    .accept(MediaType.TEXT_HTML)
                    .contentType(
                            MediaType.APPLICATION_FORM_URLENCODED)
                    .param("username", "[email protected]")
                    .param("password", "user1")
    )
            .andExpect(status().is3xxRedirection())
            .andExpect(redirectedUrl("/default"))
            .andDo(print())
    ;
}
 
Example 57
Project: cloud-s4-sdk-examples   File: CostCenterServiceIntegrationTest.java   Source Code and License 5 votes vote down vote up
private void createDataInTenant(String costCenter) throws Exception {
    final String newCostCenterJson = buildCostCenterJson(costCenter);
    ResultActions action = mockMvc
            .perform(MockMvcRequestBuilders
                    .request(HttpMethod.POST, "/cost-center")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .content(newCostCenterJson));
    action.andExpect(MockMvcResultMatchers.status().isOk());
}
 
Example 58
Project: Facegram   File: StoryControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldCreateStory() throws Exception {
    StoryRequest storyRequest = new StoryRequest("test","test","1",new Geolocation(0.0,0.0));

    when(storyService.createStory(anyString(), any(StoryRequest.class))).thenReturn(Constants.OK);

    mockMvc.perform(post("/story/create")
                .content(asJsonString(storyRequest))
                .contentType(MediaType.APPLICATION_JSON).principal(new UserPrincipal("testUserId")))
            .andExpect(status().isOk())
            .andExpect(mvcResult -> Constants.OK.equals(mvcResult));

}
 
Example 59
Project: spring-boot-additional-validation   File: ValidationControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldAcceptValidDataEn() throws Exception {
    this.mockMvc.perform(post("/validation")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .header(HttpHeaders.ACCEPT_LANGUAGE, "en-GB")
            .content("{" +
                    "\"someStringValue\":\"ab\"," +
                    "\"someIntValue\":2" +
                    "}"))
            .andExpect(status().isOk());
}
 
Example 60
Project: xm-uaa   File: TwitterEscapingFormHttpMessageConverter.java   Source Code and License 5 votes vote down vote up
@Override
public void write(MultiValueMap<String, ?> map, MediaType contentType, HttpOutputMessage outputMessage)
    throws IOException {
    // only do special escaping if this is a non-multipart request
    if (!isMultipart(map, contentType)) {
        super.write(map, contentType, new TwitterEscapingHttpOutputMessage(outputMessage));
    } else {
        super.write(map, contentType, outputMessage);
    }
}