1
2
3
4
5
6
7
8
9
10
11
12
13 package org.springframework.security.oauth2.http.converter;
14
15 import java.io.IOException;
16 import java.util.Collections;
17 import java.util.List;
18 import java.util.Map;
19
20 import org.springframework.http.HttpInputMessage;
21 import org.springframework.http.HttpOutputMessage;
22 import org.springframework.http.MediaType;
23 import org.springframework.http.converter.FormHttpMessageConverter;
24 import org.springframework.http.converter.HttpMessageConverter;
25 import org.springframework.http.converter.HttpMessageNotReadableException;
26 import org.springframework.http.converter.HttpMessageNotWritableException;
27 import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
28 import org.springframework.util.LinkedMultiValueMap;
29 import org.springframework.util.MultiValueMap;
30
31
32
33
34
35
36
37
38
39 public final class FormOAuth2ExceptionHttpMessageConverter implements HttpMessageConverter<OAuth2Exception> {
40
41 private static final List<MediaType> SUPPORTED_MEDIA = Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED);
42
43 private final FormHttpMessageConverter delegateMessageConverter = new FormHttpMessageConverter();
44
45 public boolean canRead(Class<?> clazz, MediaType mediaType) {
46 return OAuth2Exception.class.equals(clazz) && MediaType.APPLICATION_FORM_URLENCODED.equals(mediaType);
47 }
48
49 public boolean canWrite(Class<?> clazz, MediaType mediaType) {
50 return OAuth2Exception.class.equals(clazz) && MediaType.APPLICATION_FORM_URLENCODED.equals(mediaType);
51 }
52
53 public List<MediaType> getSupportedMediaTypes() {
54 return SUPPORTED_MEDIA;
55 }
56
57 public OAuth2Exception read(Class<? extends OAuth2Exception> clazz, HttpInputMessage inputMessage)
58 throws IOException, HttpMessageNotReadableException {
59 MultiValueMap<String, String> data = delegateMessageConverter.read(null, inputMessage);
60 Map<String,String> flattenedData = data.toSingleValueMap();
61 return OAuth2Exception.valueOf(flattenedData);
62 }
63
64 public void write(OAuth2Exception t, MediaType contentType, HttpOutputMessage outputMessage) throws IOException,
65 HttpMessageNotWritableException {
66 MultiValueMap<String, String> data = new LinkedMultiValueMap<String, String>();
67 data.add(OAuth2Exception.ERROR, t.getOAuth2ErrorCode());
68 data.add(OAuth2Exception.DESCRIPTION, t.getMessage());
69 Map<String, String> additionalInformation = t.getAdditionalInformation();
70 if(additionalInformation != null) {
71 for(Map.Entry<String,String> entry : additionalInformation.entrySet()) {
72 data.add(entry.getKey(), entry.getValue());
73 }
74 }
75 delegateMessageConverter.write(data, contentType, outputMessage);
76 }
77
78 }