001/*-------------------------------------------------------------------------+ 002| | 003| Copyright 2005-2011 the ConQAT Project | 004| | 005| Licensed under the Apache License, Version 2.0 (the "License"); | 006| you may not use this file except in compliance with the License. | 007| You may obtain a copy of the License at | 008| | 009| http://www.apache.org/licenses/LICENSE-2.0 | 010| | 011| Unless required by applicable law or agreed to in writing, software | 012| distributed under the License is distributed on an "AS IS" BASIS, | 013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 014| See the License for the specific language governing permissions and | 015| limitations under the License. | 016+-------------------------------------------------------------------------*/ 017package org.conqat.lib.commons.serialization; 018 019import java.io.DataOutputStream; 020import java.io.IOException; 021 022/** 023 * Base class for anything that is part of a serialized stream (objects, 024 * classes, etc.). 025 */ 026public abstract class SerializedEntityBase { 027 028 /** The handle of this entity. */ 029 protected final int handle; 030 031 /** The pool this entity is registered at. */ 032 protected final SerializedEntityPool pool; 033 034 /** 035 * Constructor. This also registers the entity with the pool. The reason 036 * that this happens here is that adding to the pool also defines the handle 037 * of the entity (handle counter in the pool). Thus we must be sure that 038 * obtaining the handle happens before any other (child) entities are added. 039 */ 040 protected SerializedEntityBase(SerializedEntityPool pool) { 041 this.handle = pool.addEntity(this); 042 this.pool = pool; 043 } 044 045 /** Returns the handle for this entity. */ 046 public int getHandle() { 047 return handle; 048 } 049 050 /** Serializes the entity on an output stream. */ 051 public void serialize(DataOutputStream dos, SerializedEntitySerializer serializer) throws IOException { 052 if (serializer.writeReference(this)) { 053 return; 054 } 055 056 serializeContent(dos, serializer); 057 } 058 059 /** 060 * Serializes the content of the entity (no reference) on an output stream. 061 */ 062 protected abstract void serializeContent(DataOutputStream dos, SerializedEntitySerializer serializer) 063 throws IOException; 064}