Java Code Examples for org.springframework.http.converter.FormHttpMessageConverter

The following examples show how to use org.springframework.http.converter.FormHttpMessageConverter. These examples are extracted from open source projects. 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
@Test
public void multipartFileResource() throws IOException {
	String name = "file";
	String disposition = "form-data; name=\"" + name + "\"; filename=\"myFile.txt\"";
	StandardMultipartHttpServletRequest request = requestWithPart(name, disposition, "myBody");
	MultipartFile multipartFile = request.getFile(name);

	assertNotNull(multipartFile);

	MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.add(name, multipartFile.getResource());

	MockHttpOutputMessage output = new MockHttpOutputMessage();
	new FormHttpMessageConverter().write(map, null, output);

	assertThat(output.getBodyAsString(StandardCharsets.UTF_8), containsString(
			"Content-Disposition: form-data; name=\"file\"; filename=\"myFile.txt\"\r\n" +
					"Content-Type: text/plain\r\n" +
					"Content-Length: 6\r\n" +
					"\r\n" +
					"myBody\r\n"));
}
 
Example 2
private MultiValueMap<String, String> parseFormData(final MediaType mediaType) {
	HttpInputMessage message = new HttpInputMessage() {
		@Override
		public InputStream getBody() {
			return (content != null ? new ByteArrayInputStream(content) : StreamUtils.emptyInput());
		}
		@Override
		public HttpHeaders getHeaders() {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(mediaType);
			return headers;
		}
	};

	try {
		return new FormHttpMessageConverter().read(null, message);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to parse form data in request body", ex);
	}
}
 
Example 3
Source Project: spring-analysis-note   Source File: ContentRequestMatchers.java    License: MIT License 6 votes vote down vote up
/**
 * Parse the body as form data and compare to the given {@code MultiValueMap}.
 * @since 4.3
 */
public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) {
	return request -> {
		HttpInputMessage inputMessage = new HttpInputMessage() {
			@Override
			public InputStream getBody() throws IOException {
				MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
				return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		};
		FormHttpMessageConverter converter = new FormHttpMessageConverter();
		assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
	};
}
 
Example 4
@Test
public void multipartFileResource() throws IOException {
	String name = "file";
	String disposition = "form-data; name=\"" + name + "\"; filename=\"myFile.txt\"";
	StandardMultipartHttpServletRequest request = requestWithPart(name, disposition, "myBody");
	MultipartFile multipartFile = request.getFile(name);

	assertNotNull(multipartFile);

	MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.add(name, multipartFile.getResource());

	MockHttpOutputMessage output = new MockHttpOutputMessage();
	new FormHttpMessageConverter().write(map, null, output);

	assertThat(output.getBodyAsString(StandardCharsets.UTF_8), containsString(
			"Content-Disposition: form-data; name=\"file\"; filename=\"myFile.txt\"\r\n" +
					"Content-Type: text/plain\r\n" +
					"Content-Length: 6\r\n" +
					"\r\n" +
					"myBody\r\n"));
}
 
Example 5
private MultiValueMap<String, String> parseFormData(final MediaType mediaType) {
	HttpInputMessage message = new HttpInputMessage() {
		@Override
		public InputStream getBody() {
			return (content != null ? new ByteArrayInputStream(content) : StreamUtils.emptyInput());
		}
		@Override
		public HttpHeaders getHeaders() {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(mediaType);
			return headers;
		}
	};

	try {
		return new FormHttpMessageConverter().read(null, message);
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to parse form data in request body", ex);
	}
}
 
Example 6
Source Project: java-technology-stack   Source File: ContentRequestMatchers.java    License: MIT License 6 votes vote down vote up
/**
 * Parse the body as form data and compare to the given {@code MultiValueMap}.
 * @since 4.3
 */
public RequestMatcher formData(final MultiValueMap<String, String> expectedContent) {
	return request -> {
		HttpInputMessage inputMessage = new HttpInputMessage() {
			@Override
			public InputStream getBody() throws IOException {
				MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
				return new ByteArrayInputStream(mockRequest.getBodyAsBytes());
			}
			@Override
			public HttpHeaders getHeaders() {
				return request.getHeaders();
			}
		};
		FormHttpMessageConverter converter = new FormHttpMessageConverter();
		assertEquals("Request content", expectedContent, converter.read(null, inputMessage));
	};
}
 
Example 7
Source Project: spring-boot-chatbot   Source File: RestTemplateFactory.java    License: MIT License 6 votes vote down vote up
public static RestOperations getRestOperations(HttpComponentsClientHttpRequestFactory factory) {
    RestTemplate restTemplate = new RestTemplate(factory);

    StringHttpMessageConverter stringMessageConverter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
    MappingJackson2HttpMessageConverter jackson2Converter = new MappingJackson2HttpMessageConverter();
    ByteArrayHttpMessageConverter byteArrayHttpMessageConverter = new ByteArrayHttpMessageConverter();
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    formHttpMessageConverter.setCharset(Charset.forName("UTF-8"));

    List<HttpMessageConverter<?>> converters = new ArrayList<>();
    converters.add(jackson2Converter);
    converters.add(stringMessageConverter);
    converters.add(byteArrayHttpMessageConverter);
    converters.add(formHttpMessageConverter);

    restTemplate.setMessageConverters(converters);
    return restTemplate;
}
 
Example 8
Source Project: kafka-webview   Source File: UserLoginUtility.java    License: MIT License 6 votes vote down vote up
/**
 * Login to the instance with the given username and password.
 * @param user username to login with.
 * @param password Password to use.
 * @return http session headers.
 */
public HttpHeaders login(final String user, final String password) {
    final HttpHeaders httpHeaders = new HttpHeaders();

    restTemplate.execute(loginPath, HttpMethod.POST,
        request -> {
            request.getHeaders().addAll(getLoginHeaders());
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("email", user);
            map.add("password", password);
            new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
        },
        response -> {
            httpHeaders.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
            return null;
        });

    return httpHeaders;
}
 
Example 9
Source Project: jhipster-registry   Source File: UaaConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@LoadBalanced
public RestTemplate uaaRestTemplate() {
    ClientRegistration clientRegistration = clientRegistrationRepository.findByRegistrationId(CLIENT_REGISTRATION_ID);
    if (null == clientRegistration) {
        throw new IllegalArgumentException("Invalid Client Registration with Id: " + CLIENT_REGISTRATION_ID);
    }

    return restTemplateBuilder
        .messageConverters(
            new FormHttpMessageConverter(),
            new OAuth2AccessTokenResponseHttpMessageConverter())
        .errorHandler(new OAuth2ErrorResponseErrorHandler())
        .basicAuthentication(clientRegistration.getClientId(), clientRegistration.getClientSecret())
        .build();
}
 
Example 10
@SuppressWarnings("unchecked")
@Override
protected void initRestTemplate(RestTemplate restTemplate) {
    super.initRestTemplate(restTemplate);
    restTemplate.setErrorHandler(new DCTMJacksonErrorHandler(restTemplate.getMessageConverters()));
    for(HttpMessageConverter<?> c : restTemplate.getMessageConverters()) {
        if(c instanceof MappingJackson2HttpMessageConverter) {
            ((MappingJackson2HttpMessageConverter)c).getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        } else if(c instanceof FormHttpMessageConverter) {
            try {
                Field pcField = FormHttpMessageConverter.class.getDeclaredField("partConverters");
                pcField.setAccessible(true);
                List<HttpMessageConverter<?>> partConverters = ((List<HttpMessageConverter<?>>)pcField.get(c));
                for(HttpMessageConverter<?> pc : partConverters) {
                    if(pc instanceof MappingJackson2HttpMessageConverter) {
                        ((MappingJackson2HttpMessageConverter)pc).getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
                        break;
                    }
                }
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}
 
Example 11
@BeforeEach
void beforeMethod() {
  MockitoAnnotations.initMocks(this);
  FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
  freeMarkerViewResolver.setSuffix(".ftl");

  when(menuReaderService.findMenuItemPath(MetadataManagerController.METADATA_MANAGER))
      .thenReturn("/test/path");

  when(appSettings.getLanguageCode()).thenReturn("nl");
  User user = mock(User.class);
  when(userAccountService.getCurrentUser()).thenReturn(user);

  MetadataManagerController metadataEditorController =
      new MetadataManagerController(menuReaderService, metadataManagerService);

  mockMvc =
      MockMvcBuilders.standaloneSetup(metadataEditorController)
          .setLocaleResolver(localeResolver)
          .setMessageConverters(new FormHttpMessageConverter(), gsonHttpMessageConverter)
          .build();
}
 
Example 12
@BeforeEach
void beforeMethod() {
  IdentitiesApiController groupRestController =
      new IdentitiesApiController(
          groupValueFactory,
          groupService,
          roleMembershipService,
          roleService,
          userService,
          userPermissionEvaluator);
  mockMvc =
      MockMvcBuilders.standaloneSetup(groupRestController)
          .setMessageConverters(new FormHttpMessageConverter(), gsonHttpMessageConverter)
          .setLocaleResolver(localeResolver)
          .build();
}
 
Example 13
@BeforeEach
private void beforeMethod() {
  RSQLParser rsqlParser = new RSQLParser();
  PermissionsController controller =
      new PermissionsController(
          permissionsService, rsqlParser, objectIdentityService, userRoleTools, entityHelper);
  mockMvc =
      MockMvcBuilders.standaloneSetup(controller)
          .setMessageConverters(new FormHttpMessageConverter(), gsonHttpMessageConverter)
          .build();

  user1 = new PrincipalSid("user1");
  user2 = new PrincipalSid("user2");
  role1 = new GrantedAuthoritySid("ROLE_role1");
  role2 = new GrantedAuthoritySid("ROLE_role2");

  objectIdentity = new ObjectIdentityImpl("typeId", "identifier");
}
 
Example 14
@BeforeEach
void setUp() {
  FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
  freeMarkerViewResolver.setSuffix(".ftl");
  mockMvc =
      MockMvcBuilders.standaloneSetup(authenticationController)
          .setMessageConverters(
              new FormHttpMessageConverter(), new GsonHttpMessageConverter(new Gson()))
          .build();

  reset(authenticationSettings);
  reset(reCaptchaService);
  reset(appSettings);
  when(reCaptchaService.validate("validCaptcha")).thenReturn(true);
  reset(accountService); // mocks in the config class are not resetted after each test
}
 
Example 15
@BeforeEach
private void beforeMethod() {
  when(menuReaderService.findMenuItemPath(QuestionnaireController.ID)).thenReturn("/test/path");

  User user = mock(User.class);
  when(user.isSuperuser()).thenReturn(false);

  when(menuReaderService.getMenu()).thenReturn(Optional.of(menu));
  when(appSettings.getLanguageCode()).thenReturn("en");
  when(userAccountService.getCurrentUser()).thenReturn(user);

  QuestionnaireController questionnaireController =
      new QuestionnaireController(
          questionnaireService, menuReaderService, appSettings, userAccountService);
  Model model = mock(Model.class);
  questionnaireController.initView(model);

  mockMvc =
      MockMvcBuilders.standaloneSetup(questionnaireController)
          .setMessageConverters(new FormHttpMessageConverter(), gsonHttpMessageConverter)
          .build();
}
 
Example 16
Source Project: messaging-app   Source File: SecurityConfig.java    License: Apache License 2.0 5 votes vote down vote up
private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> authorizationCodeTokenResponseClient() {
	OAuth2AccessTokenResponseHttpMessageConverter tokenResponseHttpMessageConverter =
			new OAuth2AccessTokenResponseHttpMessageConverter();
	tokenResponseHttpMessageConverter.setTokenResponseConverter(new CustomAccessTokenResponseConverter());

	RestTemplate restTemplate = new RestTemplate(Arrays.asList(
			new FormHttpMessageConverter(), tokenResponseHttpMessageConverter));
	restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());

	DefaultAuthorizationCodeTokenResponseClient tokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
	tokenResponseClient.setRestOperations(restTemplate);

	return tokenResponseClient;
}
 
Example 17
Source Project: spring-social-wechat   Source File: WechatOAuth2Template.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected RestTemplate createRestTemplate() {
	RestTemplate restTemplate = super.createRestTemplate();
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(3);
	converters.add(new FormHttpMessageConverter());
	converters.add(new FormMapHttpMessageConverter());
	converters.add(new WechatMappingJackson2HttpMessageConverter());
	restTemplate.setMessageConverters(converters);
	restTemplate.setErrorHandler(new WechatErrorHandler());
	return restTemplate;
}
 
Example 18
Source Project: spring-social-wechat   Source File: WechatImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<HttpMessageConverter<?>> getMessageConverters() {
	List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>(3);
	converters.add(new FormHttpMessageConverter());
	converters.add(new FormMapHttpMessageConverter());
	converters.add(new WechatMappingJackson2HttpMessageConverter());
	return converters;
}
 
Example 19
Source Project: java-trader   Source File: TraderUMainConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new StringHttpMessageConverter());
    converters.add(new FormHttpMessageConverter());
    GsonHttpMessageConverter c = new GsonHttpMessageConverter();
    c.setGson(new GsonBuilder().disableHtmlEscaping().create());
    converters.add(c);
    converters.add(new ResourceHttpMessageConverter());
}
 
Example 20
Source Project: java-trader   Source File: TraderMainConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(new StringHttpMessageConverter());
    converters.add(new FormHttpMessageConverter());
    GsonHttpMessageConverter c = new GsonHttpMessageConverter();
    c.setGson(new GsonBuilder().disableHtmlEscaping().create());
    converters.add(c);
    converters.add(new ResourceHttpMessageConverter());
}
 
Example 21
Source Project: spring-credhub   Source File: CredHubRestTemplateFactory.java    License: Apache License 2.0 5 votes vote down vote up
private static RestTemplate createTokenServerRestTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
	RestTemplate restOperations = new RestTemplate(
			Arrays.asList(new FormHttpMessageConverter(), new OAuth2AccessTokenResponseHttpMessageConverter()));
	restOperations.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
	restOperations.setRequestFactory(clientHttpRequestFactory);
	return restOperations;
}
 
Example 22
Source Project: apollo   Source File: CtripMQService.java    License: Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
  restTemplate = new RestTemplate();

  SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate.getRequestFactory();
  rf.setReadTimeout(portalConfig.readTimeout());
  rf.setConnectTimeout(portalConfig.connectTimeout());

  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
  converter.setSupportedMediaTypes(
      Arrays.asList(MediaType.APPLICATION_JSON_UTF8, MediaType.APPLICATION_OCTET_STREAM));

  restTemplate.setMessageConverters(Arrays.asList(converter, new FormHttpMessageConverter()));

}
 
Example 23
Source Project: jhipster-registry   Source File: AuthorizationHeaderUtil.java    License: Apache License 2.0 5 votes vote down vote up
private RestTemplate restTemplate(String clientId, String clientSecret) {
    return restTemplateBuilder
        .additionalMessageConverters(
            new FormHttpMessageConverter(),
            new OAuth2AccessTokenResponseHttpMessageConverter())
        .errorHandler(new OAuth2ErrorResponseErrorHandler())
        .basicAuthentication(clientId, clientSecret)
        .build();
}
 
Example 24
@Override
protected void initRestTemplate(RestTemplate restTemplate) {
    super.initRestTemplate(restTemplate);
    restTemplate.setErrorHandler(new DCTMJaxbErrorHandler(restTemplate.getMessageConverters()));
    for(HttpMessageConverter<?> c : restTemplate.getMessageConverters()) {
        if(c instanceof FormHttpMessageConverter) {
            ((FormHttpMessageConverter)c).addPartConverter(new Jaxb2RootElementHttpMessageConverter());
            break;
        }
    }
}
 
Example 25
Source Project: onboard   Source File: NetServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init() {
    restTemplate = new RestTemplate();

    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
    restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter());
    requestConfig = RequestConfig.custom().setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).build();
}
 
Example 26
Source Project: bearchoke   Source File: QuotesWebSocketIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void loginAndSaveXAuthToken(final String user, final String password,
										   final HttpHeaders headersToUpdate) {

	log.info("Authenticating user before subscribing to web socket");

	String url = "http://dev.bearchoke.com:" + port + "/api/authenticate";

	try {
		new RestTemplate().execute(url, HttpMethod.POST,

				request -> {
					MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
					map.add("username", user);
					map.add("password", password);
					new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
				},

				response -> {
					String xAuthToken = response.getHeaders().getFirst(ServerConstants.X_AUTH_TOKEN);
					log.info("Retrieved x-auth-token: " + xAuthToken);
					headersToUpdate.add(ServerConstants.X_AUTH_TOKEN, xAuthToken);
					return null;
				});
	} catch (Exception ex) {
		log.error(ex.getMessage(), ex);
	}
}
 
Example 27
@BeforeEach
void beforeTest() {
  dataService = mock(DataService.class);
  entityModelWriter = mock(EntityModelWriter.class);
  FairController controller = new FairController(dataService, entityModelWriter);

  mockMvc =
      MockMvcBuilders.standaloneSetup(controller)
          .setMessageConverters(
              new FormHttpMessageConverter(), gsonHttpMessageConverter, new RdfConverter())
          .addFilter(new ForwardedHeaderFilter())
          .build();
}
 
Example 28
@BeforeEach
private void beforeMethod() {
  BeaconController beaconController = new BeaconController(beaconInfoService, beaconQueryService);
  mockMvc =
      MockMvcBuilders.standaloneSetup(beaconController)
          .setMessageConverters(new FormHttpMessageConverter(), gsonHttpMessageConverter)
          .build();
}
 
Example 29
Source Project: spring-analysis-note   Source File: FormContentFilter.java    License: MIT License 4 votes vote down vote up
/**
 * Set the converter to use for parsing form content.
 * <p>By default this is an instance of {@link AllEncompassingFormHttpMessageConverter}.
 */
public void setFormConverter(FormHttpMessageConverter converter) {
	Assert.notNull(converter, "FormHttpMessageConverter is required");
	this.formConverter = converter;
}
 
Example 30
Source Project: spring-analysis-note   Source File: HttpPutFormContentFilter.java    License: MIT License 4 votes vote down vote up
/**
 * Set the converter to use for parsing form content.
 * <p>By default this is an instance of {@link AllEncompassingFormHttpMessageConverter}.
 */
public void setFormConverter(FormHttpMessageConverter converter) {
	Assert.notNull(converter, "FormHttpMessageConverter is required.");
	this.formConverter = converter;
}