1 /*
2  * Copyright 2002-2017 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 module hunt.stomp.converter.StringMessageConverter;
18 
19 import hunt.stomp.converter.AbstractMessageConverter;
20 import hunt.stomp.Message;
21 import hunt.stomp.MessageHeaders;
22 
23 import hunt.util.MimeType;
24 
25 import hunt.text.Charset;
26 import hunt.Exceptions;
27 import hunt.logging;
28 
29 /**
30  * A {@link MessageConverter} that supports MIME type "text/plain" with the
31  * payload converted to and from a string.
32  *
33  * @author Rossen Stoyanchev
34  * @since 4.0
35  */
36 class StringMessageConverter : AbstractMessageConverter {
37 
38 	private Charset defaultCharset;
39 
40 
41 	this() {
42 		this(StandardCharsets.UTF_8);
43 	}
44 
45 	this(Charset defaultCharset) {
46 		super(new MimeType("text/plain", defaultCharset));
47 		assert(defaultCharset !is null, "Default Charset must not be null");
48 		this.defaultCharset = defaultCharset;
49 	}
50 
51 
52 	override
53 	protected bool supports(TypeInfo typeInfo) {
54 		// version(HUNT_DEBUG) tracef("checking message type, expected: %s, actual: %s", 
55 		// 	typeid(string), typeInfo);
56 		return (typeid(string) == typeInfo);
57 	}
58 
59 	// override
60 	// protected Object convertFromInternal(MessageBase message, Class<?> targetClass, Object conversionHint) {
61 	// 	Charset charset = getContentTypeCharset(getMimeType(message.getHeaders()));
62 	// 	Object payload = message.getPayload();
63 	// 	return (payload instanceof string ? payload : new string((byte[]) payload, charset));
64 	// }
65 
66 	// override
67 	// protected Object convertToInternal(
68 	// 		Object payload, MessageHeaders headers, Object conversionHint) {
69 
70 	// 	// trace("xxxxxx=>", typeid(payload));
71 	// 	// TypeInfo rawType = cast(TypeInfo)conversionHint;
72 
73 	// 	// if (byte[].class == getSerializedPayloadClass()) {
74 	// 	// 	Charset charset = getContentTypeCharset(getMimeType(headers));
75 	// 	// 	payload = ((string) payload).getBytes(charset);
76 	// 	// }
77 	// 	return payload;
78 	// }
79 
80 	// private Charset getContentTypeCharset(MimeType mimeType) {
81 	// 	if (mimeType !is null && mimeType.getCharset() !is null) {
82 	// 		return mimeType.getCharset();
83 	// 	}
84 	// 	else {
85 	// 		return this.defaultCharset;
86 	// 	}
87 	// }
88 
89 }