001 /* 002 * Copyright 2008-2009 the original author or authors. 003 * The contents of this file are subject to the Mozilla Public License 004 * Version 1.1 (the "License"); you may not use this file except in 005 * compliance with the License. You may obtain a copy of the License at 006 * http://www.mozilla.org/MPL/ 007 * 008 * Software distributed under the License is distributed on an "AS IS" 009 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 010 * License for the specific language governing rights and limitations 011 * under the License. 012 */ 013 014 package com.mtgi.analytics; 015 016 import java.text.SimpleDateFormat; 017 018 import javax.xml.stream.XMLStreamException; 019 import javax.xml.stream.XMLStreamWriter; 020 021 import com.mtgi.xml.XmlDateFormat; 022 023 public class BehaviorEventSerializer { 024 025 private static final EventDataElementSerializer dataSerializer = new EventDataElementSerializer(null); 026 027 /** date output format that conforms with XSD dateTime formatting conventions */ 028 private SimpleDateFormat XS_DATE_FORMAT = new XmlDateFormat(); 029 030 public void serialize(XMLStreamWriter writer, BehaviorEvent event) throws XMLStreamException { 031 writer.writeStartElement("event"); 032 writer.writeAttribute("id", event.getId().toString()); 033 034 BehaviorEvent parent = event.getParent(); 035 if (parent != null) 036 writer.writeAttribute("parent-id", parent.getId().toString()); 037 038 writeEventAttribute(writer, "type", event.getType()); 039 writeEventAttribute(writer, "name", event.getName()); 040 writeEventAttribute(writer, "application", event.getApplication()); 041 writeEventAttribute(writer, "start", XS_DATE_FORMAT.format(event.getStart())); 042 writeEventAttribute(writer, "duration-ms", event.getDuration().toString()); 043 writeEventAttribute(writer, "user-id", event.getUserId()); 044 writeEventAttribute(writer, "session-id", event.getSessionId()); 045 writeEventAttribute(writer, "error", event.getError()); 046 047 EventDataElement data = event.getData(); 048 dataSerializer.serializeElement(writer, data); 049 050 writer.writeEndElement(); 051 } 052 053 private static final void writeEventAttribute(XMLStreamWriter writer, String name, String value) throws XMLStreamException { 054 if (value != null) { 055 writer.writeStartElement(name); 056 writer.writeCharacters(value); 057 writer.writeEndElement(); 058 } 059 } 060 }