View Javadoc
1   package com.foxinmy.weixin4j.http.message;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   import java.nio.charset.Charset;
6   import java.util.ArrayList;
7   import java.util.Arrays;
8   import java.util.Collections;
9   import java.util.List;
10  
11  import com.foxinmy.weixin4j.http.HttpResponse;
12  import com.foxinmy.weixin4j.http.MimeType;
13  import com.foxinmy.weixin4j.util.Consts;
14  
15  public abstract class AbstractMessageConverter implements MessageConverter {
16  
17  	protected Charset charset = Consts.UTF_8;
18  
19  	private List<MimeType> supportedMimeTypes;
20  
21  	protected AbstractMessageConverter() {
22  		this.supportedMimeTypes = Collections.emptyList();
23  	}
24  
25  	protected AbstractMessageConverter(MimeType supportedMimeType) {
26  		setSupportedMediaTypes(Collections.singletonList(supportedMimeType));
27  	}
28  
29  	protected AbstractMessageConverter(MimeType... supportedMimeTypes) {
30  		setSupportedMediaTypes(Arrays.asList(supportedMimeTypes));
31  	}
32  
33  	public void setSupportedMediaTypes(List<MimeType> supportedMimeTypes) {
34  		this.supportedMimeTypes = new ArrayList<MimeType>(supportedMimeTypes);
35  	}
36  
37  	public Charset getCharset() {
38  		return charset;
39  	}
40  
41  	public void setCharset(Charset charset) {
42  		this.charset = charset;
43  	}
44  
45  	@Override
46  	public List<MimeType> supportedMimeTypes() {
47  		return Collections.unmodifiableList(this.supportedMimeTypes);
48  	}
49  
50  	@Override
51  	public boolean canConvert(Class<?> clazz, HttpResponse response) {
52  		MimeType mimeType = MimeType.valueOf(response.getHeaders().getContentType());
53  		byte[] content = response.getContent();
54  		return supports(clazz, mimeType) || supports(clazz, content);
55  	}
56  
57  	/**
58  	 * 满足其中一个supports
59  	 * 
60  	 * @param clazz
61  	 *            转换类型
62  	 * @param mimeType
63  	 *            媒体类型
64  	 * @return 支持标识
65  	 */
66  	protected boolean supports(Class<?> clazz, MimeType mimeType) {
67  		if (mimeType == null) {
68  			return true;
69  		}
70  		for (MimeType supportedMediaType : supportedMimeTypes()) {
71  			if (supportedMediaType.includes(mimeType)) {
72  				return true;
73  			}
74  		}
75  		return false;
76  	}
77  
78  	/**
79  	 * 满足其中一个supports
80  	 * 
81  	 * @param clazz
82  	 *            转换类型
83  	 * @param content
84  	 *            内容数据
85  	 * @return 支持标识
86  	 */
87  	protected abstract boolean supports(Class<?> clazz, byte[] content);
88  
89  	@Override
90  	public <T> T convert(Class<? extends T> clazz, HttpResponse response) throws IOException {
91  		return convertInternal(clazz, response.getBody());
92  	}
93  
94  	protected abstract <T> T convertInternal(Class<? extends T> clazz, InputStream body) throws IOException;
95  }