A Feign's form encoder. @author Artem Labazin
| 40 | * @author Artem Labazin |
| 41 | */ |
| 42 | @FieldDefaults(level = PRIVATE, makeFinal = true) |
| 43 | public class FormEncoder implements Encoder { |
| 44 | |
| 45 | private static final String CONTENT_TYPE_HEADER; |
| 46 | |
| 47 | private static final Pattern CHARSET_PATTERN; |
| 48 | |
| 49 | static { |
| 50 | CONTENT_TYPE_HEADER = "Content-Type"; |
| 51 | CHARSET_PATTERN = Pattern.compile("(?<=charset=)([\\w\\-]+)"); |
| 52 | } |
| 53 | |
| 54 | Encoder delegate; |
| 55 | |
| 56 | Map<ContentType, ContentProcessor> processors; |
| 57 | |
| 58 | /** Constructor with the default Feign's encoder as a delegate. */ |
| 59 | public FormEncoder() { |
| 60 | this(new DefaultEncoder()); |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Constructor with specified delegate encoder. |
| 65 | * |
| 66 | * @param delegate delegate encoder, if this encoder couldn't encode object. |
| 67 | */ |
| 68 | public FormEncoder(Encoder delegate) { |
| 69 | this.delegate = delegate; |
| 70 | |
| 71 | val list = |
| 72 | asList(new MultipartFormContentProcessor(delegate), new UrlencodedFormContentProcessor()); |
| 73 | |
| 74 | processors = new HashMap<ContentType, ContentProcessor>(list.size(), 1.F); |
| 75 | for (ContentProcessor processor : list) { |
| 76 | processors.put(processor.getSupportedContentType(), processor); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | @Override |
| 81 | @SuppressWarnings("unchecked") |
| 82 | public void encode(Object object, Type bodyType, RequestTemplate template) |
| 83 | throws EncodeException { |
| 84 | String contentTypeValue = getContentTypeValue(template.headers()); |
| 85 | val contentType = ContentType.of(contentTypeValue); |
| 86 | if (processors.containsKey(contentType) == false) { |
| 87 | delegate.encode(object, bodyType, template); |
| 88 | return; |
| 89 | } |
| 90 | |
| 91 | Map<String, Object> data; |
| 92 | if (object instanceof Map) { |
| 93 | data = (Map<String, Object>) object; |
| 94 | } else if (isUserPojo(bodyType)) { |
| 95 | data = toMap(object); |
| 96 | } else { |
| 97 | delegate.encode(object, bodyType, template); |
| 98 | return; |
| 99 | } |
nothing calls this directly
no outgoing calls
no test coverage detected