aboutsummaryrefslogtreecommitdiffstats
path: root/src/de/gultsch/chat/xml/TagWriter.java
blob: 844f5253e7d956728a6a39d93174b4d0d5af24d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package de.gultsch.chat.xml;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.concurrent.LinkedBlockingQueue;

import android.util.Log;

public class TagWriter {
	
	private OutputStreamWriter outputStream;
	private LinkedBlockingQueue<String> writeQueue = new LinkedBlockingQueue<String>();
	private Thread writer = new Thread() {
		public boolean shouldStop = false;
		@Override
		public void run() {
			while(!shouldStop) {
				try {
					String output = writeQueue.take();
					outputStream.write(output);
					outputStream.flush();
				} catch (IOException e) {
					Log.d("xmppService", "error writing to stream");
				} catch (InterruptedException e) {
					
				}
			}
		}
	};
	
	
	public TagWriter() {
		
	}
	
	public TagWriter(OutputStream out) {
		this.setOutputStream(out);
		writer.start();
	}
	
	public void setOutputStream(OutputStream out) {
		this.outputStream = new OutputStreamWriter(out);
		if (!writer.isAlive()) writer.start();
	}
	
	public TagWriter beginDocument() {
		writeQueue.add("<?xml version='1.0'?>");
		return this;
	}
	
	public TagWriter writeTag(Tag tag) {
		writeQueue.add(tag.toString());
		return this;
	}

	public void writeString(String string) {
		writeQueue.add(string);
	}

	public void writeElement(Element element) {
		writeQueue.add(element.toString());
	}
}