org.springframework.http.MediaType Java Examples

The following examples show how to use org.springframework.http.MediaType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RelationshipController.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
@PutMapping( path = "/{id}", consumes = MediaType.APPLICATION_XML_VALUE, produces = APPLICATION_XML_VALUE )
public ImportSummary updateRelationshipXml(
    @PathVariable String id,
    ImportOptions importOptions,
    HttpServletRequest request
)
    throws IOException
{
    InputStream inputStream = StreamUtils.wrapAndCheckCompressionFormat( request.getInputStream() );
    ImportSummary importSummary = relationshipService.updateRelationshipXml( id, inputStream, importOptions );
    importSummary.setImportOptions( importOptions );

    return importSummary;
}
 
Example #2
Source File: UserResourceIntTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
@Transactional
public void getAllUsers() throws Exception {
    // Initialize the database
    userRepository.saveAndFlush(user);

    // Get all the users
    restUserMockMvc.perform(get("/api/users?sort=id,desc")
        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
        .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
        .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
        .andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
        .andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
        .andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
}
 
Example #3
Source File: EntryResourceIntTest.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
@Test
@Transactional
public void searchEntry() throws Exception {
    // Initialize the database
    entryRepository.saveAndFlush(entry);
    entrySearchRepository.save(entry);

    // Search the entry
    restEntryMockMvc.perform(get("/api/_search/entries?query=id:" + entry.getId()))
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.[*].id").value(hasItem(entry.getId().intValue())))
        .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString())))
        .andExpect(jsonPath("$.[*].content").value(hasItem(DEFAULT_CONTENT.toString())))
        .andExpect(jsonPath("$.[*].date").value(hasItem(sameInstant(DEFAULT_DATE))));
}
 
Example #4
Source File: QuickStartControllerTest.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
/**
     * 快速新增服务版本
     *
     * @throws Exception
     */
    @Test
    public void test_quick_start_2_addserviceVersion() throws Exception {
//        ClassPathResource classPathResource1 = new ClassPathResource("1.yml");
//        MockMultipartFile multipartFile1 = new MockMultipartFile("file", "1.yml", "application/octet-stream", classPathResource1.getInputStream());
//
//        ClassPathResource classPathResource2 = new ClassPathResource("2.yml");
//        MockMultipartFile multipartFile2 = new MockMultipartFile("file", "2.yml", "application/octet-stream", classPathResource2.getInputStream());
//
//        ClassPathResource classPathResource3 = new ClassPathResource("3.yml");
//        MockMultipartFile multipartFile3 = new MockMultipartFile("file", "3.yml", "application/octet-stream", classPathResource3.getInputStream());
        String result = this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/api/v1/quickStart/addServiceVersion")
//                .file(multipartFile1)
//                .file(multipartFile2)
//                .file(multipartFile3)
                .param("project", "project1")
                .param("cluster", "cluster1")
                .param("service", "service1")
                .param("version", "1.0.0.2")
                .param("desc", "版本描述")
                .contentType(MediaType.MULTIPART_FORM_DATA)
                .session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
                .accept(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk())
                .andReturn().getResponse().getContentAsString();
        Utils.assertResult(result);
    }
 
Example #5
Source File: TaskControllerTests.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Test
public void testCTRElementUpdate() throws Exception {
	repository.save(new TaskDefinition("a1", "t1: task && t2: task2"));
	repository.save(new TaskDefinition("a2", "task"));
	repository.save(new TaskDefinition("a1-t1", "task"));
	repository.save(new TaskDefinition("a1-t2", "task"));

	mockMvc.perform(get("/tasks/definitions/").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
			.andExpect(jsonPath("$.content", hasSize(4)))
			.andExpect(jsonPath("$.content[0].name", is("a1")))
			.andExpect(jsonPath("$.content[0].composedTaskElement", is(false)))
			.andExpect(jsonPath("$.content[1].name", is("a2")))
			.andExpect(jsonPath("$.content[1].composedTaskElement", is(false)))
			.andExpect(jsonPath("$.content[2].name", is("a1-t1")))
			.andExpect(jsonPath("$.content[2].composedTaskElement", is(true)))
			.andExpect(jsonPath("$.content[3].name", is("a1-t2")))
			.andExpect(jsonPath("$.content[3].composedTaskElement", is(true)));

	mockMvc.perform(get("/tasks/definitions/a1-t2").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
			.andExpect(jsonPath("$.name", is("a1-t2")))
			.andExpect(jsonPath("$.composedTaskElement", is(true)));
}
 
Example #6
Source File: ServiceInstanceBindingControllerIntegrationTest.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
@Test
void getBindingToAppSucceeds() throws Exception {
	setupServiceInstanceBindingService(GetServiceInstanceAppBindingResponse.builder()
			.build());

	MvcResult mvcResult = mockMvc.perform(get(buildCreateUrl(PLATFORM_INSTANCE_ID, false))
			.header(API_INFO_LOCATION_HEADER, API_INFO_LOCATION)
			.header(ORIGINATING_IDENTITY_HEADER, buildOriginatingIdentityHeader())
			.accept(MediaType.APPLICATION_JSON)
			.contentType(MediaType.APPLICATION_JSON))
			.andExpect(request().asyncStarted())
			.andReturn();

	mockMvc.perform(asyncDispatch(mvcResult))
			.andExpect(status().isOk());

	GetServiceInstanceBindingRequest actualRequest = verifyGetBinding();
	assertHeaderValuesSet(actualRequest);
}
 
Example #7
Source File: RestDestinationControllerTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTryCreateRestDestinationWithBadRequest() throws Exception {
    when(
    	restDestinationService
    		.register(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(RestDestination.class)))
    .thenReturn(ServiceResponseBuilder
    				.<RestDestination>error()
    				.withMessage(RestDestinationService.Validations.DESTINATION_NOT_FOUND.getCode())
    				.build());

    getMockMvc()
    .perform(MockMvcRequestBuilders.post(MessageFormat.format("/{0}/{1}/", application.getName(), BASEPATH))
    		.content(getJson(new RestDestinationVO().apply(restDestination1)))
    		.contentType(MediaType.APPLICATION_JSON)
    		.accept(MediaType.APPLICATION_JSON))
    .andExpect(status().is4xxClientError())
    .andExpect(content().contentType("application/json;charset=UTF-8"))
    .andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value())))
    .andExpect(jsonPath("$.status", is("error")))
    .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
    .andExpect(jsonPath("$.messages").exists())
    .andExpect(jsonPath("$.result").doesNotExist());

}
 
Example #8
Source File: AbstractWsTest.java    From poli with MIT License 6 votes vote down vote up
public User createViewer(String username, List<Long> userGroups) throws Exception {
    User u1 = new User();
    u1.setUsername(username);
    u1.setName("n1");
    u1.setTempPassword("t1");
    u1.setUserGroups(userGroups);
    u1.setSysRole(Constants.SYS_ROLE_VIEWER);
    String body = mapper.writeValueAsString(u1);
    mvcResult = this.mvc.perform(
            post("/ws/users")
                    .contentType(MediaType.APPLICATION_JSON)
                    .requestAttr(Constants.HTTP_REQUEST_ATTR_USER, adminUser)
                    .content(body)
    )
            .andExpect(status().isCreated())
            .andReturn();
    long id = Long.parseLong(mvcResult.getResponse().getContentAsString());
    u1.setId(id);
    return u1;
}
 
Example #9
Source File: DeviceConfigRestControllerTest.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTryDeleteNonexistentDeviceConfig() throws Exception {

    when(deviceConfigSetupService.remove(tenant, application, deviceModel, location))
        .thenReturn(ServiceResponseBuilder.<DeviceConfigSetup> error()
                .withMessage(DeviceConfigSetupService.Validations.DEVICE_CONFIG_NOT_FOUND.getCode())
                .build());

	getMockMvc().perform(MockMvcRequestBuilders
	        .delete(MessageFormat.format("/{0}/{1}/{2}/{3}/", application.getName(), BASEPATH, deviceModel.getName(), location.getName()))
			.contentType("application/json")
			.accept(MediaType.APPLICATION_JSON))
        	.andExpect(status().is4xxClientError())
        	.andExpect(content().contentType("application/json;charset=UTF-8"))
        	.andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
        	.andExpect(jsonPath("$.status", is("error")))
        	.andExpect(jsonPath("$.timestamp",greaterThan(1400000000)))
        	.andExpect(jsonPath("$.messages").exists())
        	.andExpect(jsonPath("$.result").doesNotExist());

}
 
Example #10
Source File: HttpMessageConverterExtractorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void normal() throws IOException {
	HttpMessageConverter<String> converter = mock(HttpMessageConverter.class);
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
	converters.add(converter);
	HttpHeaders responseHeaders = new HttpHeaders();
	MediaType contentType = MediaType.TEXT_PLAIN;
	responseHeaders.setContentType(contentType);
	String expected = "Foo";
	extractor = new HttpMessageConverterExtractor<String>(String.class, converters);
	given(response.getStatusCode()).willReturn(HttpStatus.OK);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(new ByteArrayInputStream(expected.getBytes()));
	given(converter.canRead(String.class, contentType)).willReturn(true);
	given(converter.read(eq(String.class), any(HttpInputMessage.class))).willReturn(expected);

	Object result = extractor.extractData(response);

	assertEquals(expected, result);
}
 
Example #11
Source File: RequestCompressionPluginTest.java    From riptide with MIT License 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(RequestFactorySource.class)
void shouldCompressWithGivenAlgorithm(final ClientHttpRequestFactory factory) {
    driver.addExpectation(onRequestTo("/")
                    .withMethod(POST)
                    .withHeader("Content-Encoding", "identity") // not handled by Jetty
                    .withoutHeader("X-Content-Encoding")
                    .withBody(equalTo("{}"), "application/json"),
            giveResponse("", "text/plain"));

    final Http http = buildHttp(factory, new RequestCompressionPlugin(Compression.of("identity", it -> it)));
    http.post("/")
            .contentType(MediaType.APPLICATION_JSON)
            .body(new HashMap<>())
            .call(pass())
            .join();
}
 
Example #12
Source File: RequestMappingHandlerAdapterTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void responseBodyAdvice() throws Exception {
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new MappingJackson2HttpMessageConverter());
	this.handlerAdapter.setMessageConverters(converters);

	this.webAppContext.registerSingleton("rba", ResponseCodeSuppressingAdvice.class);
	this.webAppContext.refresh();

	this.request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
	this.request.setParameter("c", "callback");

	HandlerMethod handlerMethod = handlerMethod(new SimpleController(), "handleBadRequest");
	this.handlerAdapter.afterPropertiesSet();
	this.handlerAdapter.handle(this.request, this.response, handlerMethod);

	assertEquals(200, this.response.getStatus());
	assertEquals("{\"status\":400,\"message\":\"body\"}", this.response.getContentAsString());
}
 
Example #13
Source File: AnnotationDrivenBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Properties getDefaultMediaTypes() {
	Properties defaultMediaTypes = new Properties();
	if (romePresent) {
		defaultMediaTypes.put("atom", MediaType.APPLICATION_ATOM_XML_VALUE);
		defaultMediaTypes.put("rss", MediaType.APPLICATION_RSS_XML_VALUE);
	}
	if (jaxb2Present || jackson2XmlPresent) {
		defaultMediaTypes.put("xml", MediaType.APPLICATION_XML_VALUE);
	}
	if (jackson2Present || gsonPresent) {
		defaultMediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE);
	}
	if (jackson2SmilePresent) {
		defaultMediaTypes.put("smile", "application/x-jackson-smile");
	}
	if (jackson2CborPresent) {
		defaultMediaTypes.put("cbor", "application/cbor");
	}
	return defaultMediaTypes;
}
 
Example #14
Source File: FooResourceIntTest.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
@Test
@Transactional
public void getAllFoos() throws Exception {
    // Initialize the database
    fooRepository.saveAndFlush(foo);

    // Get all the foos
    restFooMockMvc.perform(get("/api/foos?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$.[*].id").value(hasItem(foo.getId().intValue())))
            .andExpect(jsonPath("$.[*].value").value(hasItem(DEFAULT_VALUE.toString())));
}
 
Example #15
Source File: MainControllerTest.java    From kardio with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMarathonComponents() throws Exception {
    String envName = "getcompenv";
    List<Component> comps = new ArrayList<Component>();
    mockMvc.perform(
            get("/getPlatformComponents").contentType(MediaType.APPLICATION_JSON)
                    .param("environment", envName)
                    .param("platform", TestDataProvider.getPlatform()))
            .andExpect(status().isOk());
    verify(regionStatusService, times(1)).getPlatformComponents(envName, TestDataProvider.getPlatform());
    verifyNoMoreInteractions(regionStatusService);
    when(regionStatusService.getPlatformComponents(envName, TestDataProvider.getPlatform())).thenReturn(comps);
}
 
Example #16
Source File: CalendarApplicationTests.java    From Spring-Security-Third-Edition with MIT 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", "shauser")
    )
            .andExpect(status().is3xxRedirection())
            .andExpect(redirectedUrl("/default"))
            .andDo(print())
    ;
}
 
Example #17
Source File: ServiceConfigControllerTest.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
/**
 * 删除配置
 *
 * @throws Exception
 */
@Test
public void test_service_config_12_download() throws Exception {
    String result = this.mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/service/config/download")
            .param("id", "3783228579949576192")
            .contentType(MediaType.APPLICATION_JSON)
            .session((MockHttpSession) Utils.getLoginSession(this.mockMvc))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andReturn().getResponse().getContentAsString();
    System.out.println(result);
    Utils.assertResult(result);
}
 
Example #18
Source File: ExceptionTranslatorIntTest.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
@Test
public void testParameterizedError2() throws Exception {
    mockMvc.perform(get("/test/parameterized-error2"))
        .andExpect(status().isBadRequest())
        .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
        .andExpect(jsonPath("$.message").value("test parameterized error"))
        .andExpect(jsonPath("$.params.foo").value("foo_value"))
        .andExpect(jsonPath("$.params.bar").value("bar_value"));
}
 
Example #19
Source File: BeerControllerTest.java    From spring-cloud-contract-samples with Apache License 2.0 5 votes vote down vote up
@Test
public void should_give_me_a_beer_when_im_old_enough() throws Exception {
	//remove::start[]
	this.mockMvc.perform(MockMvcRequestBuilders.post("/beer")
			.contentType(MediaType.APPLICATION_JSON)
			.content(this.json.write(new Person("marcin", 22)).getJson()))
			.andExpect(status().isOk())
			.andExpect(content().string("THERE YOU GO"));
	//remove::end[]
}
 
Example #20
Source File: DdiDeploymentBaseTest.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private void getAndVerifyDeploymentBasePayload(final String controllerId, final MediaType mediaType,
        final DistributionSet ds, final String visibleMetadataOsKey, final String visibleMetadataOsValue,
        final Artifact artifact, final Artifact artifactSignature, final Long actionId, final String downloadType,
        final String updateType, final Long osModuleId) throws Exception {
    getAndVerifyDeploymentBasePayload(controllerId, mediaType, ds, artifact, artifactSignature, actionId,
            osModuleId, downloadType, updateType).andExpect(
                    jsonPath("$.deployment.chunks[?(@.part=='os')].metadata[0].key").value(visibleMetadataOsKey))
                    .andExpect(jsonPath("$.deployment.chunks[?(@.part=='os')].metadata[0].value")
                            .value(visibleMetadataOsValue));
}
 
Example #21
Source File: AppRegistryControllerTests.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void testUnregisterApplication() throws Exception {
	mockMvc.perform(post("/apps/processor/blubba").param("uri", "maven://org.springframework.cloud.stream.app:log-sink-rabbit:1.2.0.RELEASE").accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isCreated());
	mockMvc.perform(delete("/apps/processor/blubba").accept(MediaType.APPLICATION_JSON))
			.andExpect(status().isOk());
}
 
Example #22
Source File: EqualE2eTest.java    From specification-arg-resolver with Apache License 2.0 5 votes vote down vote up
@Test
public void findsByExactLongValue() throws Exception {
	mockMvc.perform(get("/customers")
			.param("id", homerSimpson.getId().toString())
			.accept(MediaType.APPLICATION_JSON))
		.andExpect(status().isOk())
		.andExpect(jsonPath("$").isArray())
		.andExpect(jsonPath("$[0].firstName").value("Homer"))
		.andExpect(jsonPath("$[1]").doesNotExist());
}
 
Example #23
Source File: RuleDatabaseControllerTest.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateRuleDatabase() throws Exception {
    String content = "{\"id\":\"1\",\"databaseType\":1,\"datasourceName\":\"test123111\",\"databaseUrl\":\"jdbc:h2:~/WeEvent_governance\"," +
            "\"username\":\"root\",\"password\":\"123456\",\"tableName\":\"t_rule_database\"," +
            "\"userId\":" + this.userId + ",\"brokerId\":\"" + this.brokerIdMap.get("brokerId") + "\",\"systemTag\":\"false\"}";
    MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.post("/circulationDatabase/update").contentType(MediaType.APPLICATION_JSON_UTF8).header(JwtUtils.AUTHORIZATION_HEADER_PREFIX, token).content(content)).andReturn().getResponse();

    Assert.assertEquals(response.getStatus(), HttpStatus.SC_OK);
    GovernanceResult governanceResult = JsonHelper.json2Object(response.getContentAsString(), GovernanceResult.class);
    Assert.assertEquals(governanceResult.getStatus().intValue(), 200);
}
 
Example #24
Source File: ApiFallbackProvider.java    From springcloud-course with GNU General Public License v3.0 5 votes vote down vote up
public ClientHttpResponse fallbackResponse(String message) {

        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return 200;
            }

            @Override
            public String getStatusText() throws IOException {
                return "OK";
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String bodyText = String.format("{\"code\": 999,\"message\": \"Service unavailable:%s\"}", message);
                return new ByteArrayInputStream(bodyText.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };

    }
 
Example #25
Source File: ServerSentEventHttpMessageWriterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-16516, SPR-16539
public void writePojoWithCustomEncoding() {
	Flux<Pojo> source = Flux.just(new Pojo("foo\uD834\uDD1E", "bar\uD834\uDD1E"));
	Charset charset = StandardCharsets.UTF_16LE;
	MediaType mediaType = new MediaType("text", "event-stream", charset);
	testWrite(source, mediaType, outputMessage, Pojo.class);

	assertEquals(mediaType, outputMessage.getHeaders().getContentType());
	StepVerifier.create(outputMessage.getBody())
			.consumeNextWith(dataBuffer1 -> {
				String value1 =
						DataBufferTestUtils.dumpString(dataBuffer1, charset);
				DataBufferUtils.release(dataBuffer1);
				assertEquals("data:", value1);
			})
			.consumeNextWith(dataBuffer -> {
				String value = DataBufferTestUtils.dumpString(dataBuffer, charset);
				DataBufferUtils.release(dataBuffer);
				assertEquals("{\"foo\":\"foo\uD834\uDD1E\",\"bar\":\"bar\uD834\uDD1E\"}", value);
			})
			.consumeNextWith(dataBuffer2 -> {
				String value2 =
						DataBufferTestUtils.dumpString(dataBuffer2, charset);
				DataBufferUtils.release(dataBuffer2);
				assertEquals("\n", value2);
			})
			.consumeNextWith(dataBuffer3 -> {
				String value3 =
						DataBufferTestUtils.dumpString(dataBuffer3, charset);
				DataBufferUtils.release(dataBuffer3);
				assertEquals("\n", value3);
			})
			.expectComplete()
			.verify();
}
 
Example #26
Source File: AnnotationDrivenBeanDefinitionParser.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Properties getDefaultMediaTypes() {
	Properties props = new Properties();
	if (romePresent) {
		props.put("atom", MediaType.APPLICATION_ATOM_XML_VALUE);
		props.put("rss", "application/rss+xml");
	}
	if (jaxb2Present || jackson2XmlPresent) {
		props.put("xml", MediaType.APPLICATION_XML_VALUE);
	}
	if (jackson2Present || gsonPresent) {
		props.put("json", MediaType.APPLICATION_JSON_VALUE);
	}
	return props;
}
 
Example #27
Source File: RestApiDocumentation.java    From Showcase with Apache License 2.0 5 votes vote down vote up
@Test
public void getCompletedTasksTest() throws Exception {

    MvcResult result = this.mockMvc.perform(post(ShipmentController.SHIPMENT_RESOURCE_PATH)
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsBytes(this.createIncompleteShipmentResourceHashMap())))
            .andExpect(status().isCreated()).andReturn();

    JSONObject jsonResult = new JSONObject(result.getResponse().getContentAsString());
    String trackingId = jsonResult.getString("trackingId");

    CaseExecution completeShipmentOrderCaseExecution = processEngine().getCaseService().createCaseExecutionQuery()
            .activityId(ShipmentCaseConstants.PLAN_ITEM_HUMAN_TASK_COMPLETE_SHIPMENT_ORDER)
            .caseInstanceBusinessKey(trackingId).singleResult();

    // Complete task 'Complete shipment order'
    Task task = processEngine().getTaskService().createTaskQuery()
            .caseExecutionId(completeShipmentOrderCaseExecution.getId()).singleResult();

    processEngine().getTaskService().complete(task.getId());

    //Get Completed Task
    this.mockMvc.perform(get("/educama/v1/tasks/completed" + "/" + trackingId))
            .andExpect(status().isOk())
            .andDo(this.documentationHandler
                    .document(
                            responseFields(fieldWithPath("tasks[]").description("An array of completed task objects"))
                                    .andWithPrefix("tasks[].", fieldDescriptorCompletedTaskResource))
            );
}
 
Example #28
Source File: RedirectViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void customStatusCode() {
	String url = "https://url.somewhere.com";
	RedirectView view = new RedirectView(url, HttpStatus.FOUND);
	view.render(new HashMap<>(), MediaType.TEXT_HTML, this.exchange).block();
	assertEquals(HttpStatus.FOUND, this.exchange.getResponse().getStatusCode());
	assertEquals(URI.create(url), this.exchange.getResponse().getHeaders().getLocation());
}
 
Example #29
Source File: HttpGetIntegrationTests.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
@Test
public void convertGetJson() throws Exception {
	assertThat(this.rest
			.exchange(RequestEntity.get(new URI("/entity/321"))
					.accept(MediaType.APPLICATION_JSON).build(), String.class)
			.getBody()).isEqualTo("{\"value\":321}");
}
 
Example #30
Source File: BeerControllerForBarTest.java    From spring-cloud-contract-samples with Apache License 2.0 5 votes vote down vote up
@Test public void should_give_me_a_beer_when_im_old_enough() throws Exception {
	//remove::start[]
	this.mockMvc.perform(MockMvcRequestBuilders.post("/beer")
			.contentType(MediaType.APPLICATION_JSON)
			.content(this.json.write(new Person("marcin", 22)).getJson()))
			.andExpect(status().isOk())
			.andExpect(content().string("THERE YOU GO MR [marcin]"));
	//remove::end[]
}