001: /*
002: * Copyright (C) 2006 Joe Walnes.
003: * Copyright (C) 2006, 2007 XStream Committers.
004: * All rights reserved.
005: *
006: * The software in this package is published under the terms of the BSD
007: * style license a copy of which has been included with this distribution in
008: * the LICENSE.txt file.
009: *
010: * Created on 04. June 2006 by Joe Walnes
011: */
012: package com.thoughtworks.xstream.io.binary;
013:
014: import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
015: import com.thoughtworks.xstream.io.StreamException;
016: import com.thoughtworks.xstream.io.ExtendedHierarchicalStreamWriter;
017:
018: import java.io.DataOutputStream;
019: import java.io.OutputStream;
020: import java.io.IOException;
021: import java.util.Map;
022: import java.util.HashMap;
023:
024: /**
025: * @since 1.2
026: */
027: public class BinaryStreamWriter implements
028: ExtendedHierarchicalStreamWriter {
029:
030: private final IdRegistry idRegistry = new IdRegistry();
031: private final DataOutputStream out;
032: private final Token.Formatter tokenFormatter = new Token.Formatter();
033:
034: public BinaryStreamWriter(OutputStream outputStream) {
035: out = new DataOutputStream(outputStream);
036: }
037:
038: public void startNode(String name) {
039: write(new Token.StartNode(idRegistry.getId(name)));
040: }
041:
042: public void startNode(String name, Class clazz) {
043: startNode(name);
044: }
045:
046: public void addAttribute(String name, String value) {
047: write(new Token.Attribute(idRegistry.getId(name), value));
048: }
049:
050: public void setValue(String text) {
051: write(new Token.Value(text));
052: }
053:
054: public void endNode() {
055: write(new Token.EndNode());
056: }
057:
058: public void flush() {
059: try {
060: out.flush();
061: } catch (IOException e) {
062: throw new StreamException(e);
063: }
064: }
065:
066: public void close() {
067: try {
068: out.close();
069: } catch (IOException e) {
070: throw new StreamException(e);
071: }
072: }
073:
074: public HierarchicalStreamWriter underlyingWriter() {
075: return this ;
076: }
077:
078: private void write(Token token) {
079: try {
080: tokenFormatter.write(out, token);
081: } catch (IOException e) {
082: throw new StreamException(e);
083: }
084: }
085:
086: private class IdRegistry {
087:
088: private long nextId = 0;
089: private Map ids = new HashMap();
090:
091: public long getId(String value) {
092: Long id = (Long) ids.get(value);
093: if (id == null) {
094: id = new Long(++nextId);
095: ids.put(value, id);
096: write(new Token.MapIdToValue(id.longValue(), value));
097: }
098: return id.longValue();
099: }
100:
101: }
102: }
|