View Javadoc

1   /*
2    *  Copyright 2006 Simon Raess
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  package net.sf.beep4j.internal.message;
17  
18  import java.io.ByteArrayOutputStream;
19  import java.io.OutputStream;
20  import java.io.OutputStreamWriter;
21  import java.io.Writer;
22  import java.nio.ByteBuffer;
23  import java.nio.charset.Charset;
24  
25  import net.sf.beep4j.Message;
26  import net.sf.beep4j.MessageBuilder;
27  
28  public class DefaultMessageBuilder implements MessageBuilder {
29  	
30  	private final MessageHeader header;
31  	
32  	private final ByteArrayOutputStream target;
33  	
34  	private ByteBuffer buffer;
35  	
36  	private String charset;
37  	
38  	public DefaultMessageBuilder() {
39  		header = new MessageHeader();
40  		target = new ByteArrayOutputStream();
41  	}
42  	
43  	public void addHeader(String name, String value) {
44  		header.addHeader(name, value);
45  	}
46  	
47  	public void setCharsetName(String charset) {
48  		this.charset = charset;
49  		header.setCharset(charset);
50  	}
51  	
52  	public void setContentType(String type, String subtype) {
53  		header.setContentType(type, subtype);
54  	}
55  
56  	public OutputStream getOutputStream() {
57  		return target;
58  	}
59  
60  	public Writer getWriter() {
61  		Charset charset = Charset.forName(this.charset);
62  		Writer writer = new OutputStreamWriter(getOutputStream(), charset);
63  		return writer;
64  	}
65  	
66  	public ByteBuffer getContentBuffer(int size) {
67  		buffer = ByteBuffer.allocate(size);
68  		return buffer;
69  	}
70  	
71  	public Message getMessage() {
72  		if (buffer == null) {
73  			return new DefaultMessage(header, ByteBuffer.wrap(target.toByteArray()));
74  		} else {
75  			buffer.flip();
76  			return new DefaultMessage(header, buffer.asReadOnlyBuffer());
77  		}
78  	}
79  
80  }