package org.simantics.db.common; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.TreeMap; import org.simantics.db.Session; import org.simantics.db.common.utils.Logger; import org.simantics.db.common.utils.Serializers; public class UndoMetadata extends ACommentMetadata { private boolean redo; // False if this was a undo operation. private long begin; // Identifies first change set that was reverted. private long end; // Identifies last change set that was reverted. public UndoMetadata(byte[] comments, boolean redo, long begin, long end) { super(comments); this.redo = redo; this.begin = begin; this.end = end; } public UndoMetadata(TreeMap metadata) { super((byte[])null); if (null != metadata) { byte[] data = metadata.get(UndoMetadata.class.getName()); initialize(data); } } public UndoMetadata(byte[] data) { super((byte[])null); initialize(data); } private void initialize(byte[] data) { if (null != data) { try { UndoMetadata um = deserialise(null, data); comments = um.comments; redo = um.redo; begin = um.begin; end = um.end; } catch (Exception e) { Logger.defaultLogError(e); } } } @Override public byte[] serialise(Session session) { try { ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(os); byte[] bytes = Serializers.serializeStrings(comments.toArray(new String[comments.size()])); oos.writeInt(bytes.length); oos.write(bytes); oos.writeBoolean(redo); oos.writeLong(begin); oos.writeLong(end); oos.close(); return os.toByteArray(); } catch (Exception e) { if (DEBUG) e.printStackTrace(); Logger.defaultLogError(e.toString()); } return new byte[0]; } public static UndoMetadata deserialise(Session session, byte[] input) { try { if (null == input) return new UndoMetadata(null, false, 0, 0); ByteArrayInputStream is = new ByteArrayInputStream(input); ObjectInputStream ois = new ObjectInputStream(is); int len = ois.readInt(); if (len < 0) throw new Error("Deserialisation error. Illegal string length=" + len); byte[] bytes = new byte[len]; ois.readFully(bytes); boolean redo = ois.readBoolean(); long begin = ois.readLong(); long end = ois.readLong(); ois.close(); return new UndoMetadata(bytes, redo, begin, end); } catch (Throwable e) { Logger.defaultLogError(e); } return new UndoMetadata(null, false, 0, 0); } public boolean isRedo() { return redo; } public long getBeginCSId() { return begin; } public long getEndCSId() { return end; } public void setTypeAndRange(UndoMetadata um) { redo = ! um.redo; begin = um.begin; end = um.end; } public void setTypeAndRange(boolean redo, long begin, long end) { this.redo = redo; this.begin = begin; this.end = end; } public String getType() { return redo ? "Redo" : "Undo"; } public String getRange() { return "[" + begin + "," + end + "]"; } public String getHeader() { return getType() + getRange(); } }