Debian Codegraph @

lang/java/src/com/sleepycat/persist/impl/Format.java

raw
1 /*-
2 * See the file LICENSE for redistribution information.
3 *
4 * Copyright (c) 2002, 2013 Oracle and/or its affiliates. All rights reserved.
5 *
6 */
7
8 package com.sleepycat.persist.impl;
9
10 import java.io.Serializable;
11 import java.util.HashSet;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Set;
15
16 import com.sleepycat.compat.DbCompat;
17 import com.sleepycat.persist.evolve.Converter;
18 import com.sleepycat.persist.model.ClassMetadata;
19 import com.sleepycat.persist.model.EntityMetadata;
20 import com.sleepycat.persist.model.EntityModel;
21 import com.sleepycat.persist.model.FieldMetadata;
22 import com.sleepycat.persist.model.PrimaryKeyMetadata;
23 import com.sleepycat.persist.model.SecondaryKeyMetadata;
24 import com.sleepycat.persist.raw.RawField;
25 import com.sleepycat.persist.raw.RawObject;
26 import com.sleepycat.persist.raw.RawType;
27 import java.util.IdentityHashMap;
28
29 /**
30 * The base class for all object formats. Formats are used to define the
31 * stored layout for all persistent classes, including simple types.
32 *
33 * The design documentation below describes the storage format for entities and
34 * its relationship to information stored per format in the catalog.
35 *
36 * Requirements
37 * ------------
38 * + Provides EntityBinding for objects and EntryBinding for keys.
39 * + Provides SecondaryKeyCreator, SecondaryMultiKeyCreator and
40 * SecondaryMultiKeyNullifier (SecondaryKeyNullifier is redundant).
41 * + Works with reflection and bytecode enhancement.
42 * + For reflection only, works with any entity model not just annotations.
43 * + Bindings are usable independently of the persist API.
44 * + Performance is almost equivalent to hand coded tuple bindings.
45 * + Small performance penalty for compatible class changes (new fields,
46 * widening).
47 * + Secondary key create/nullify do not have to deserialize the entire record;
48 * in other words, store secondary keys at the start of the data.
49 *
50 * Class Format
51 * ------------
52 * Every distinct class format is given a unique format ID. Class IDs are not
53 * equivalent to class version numbers (as in the version property of @Entity
54 * and @Persistent) because the format can change when the version number does
55 * not. Changes that cause a unique format ID to be assigned are:
56 *
57 * + Add field.
58 * + Widen field type.
59 * + Change primitive type to primitive wrapper class.
60 * + Add or drop secondary key.
61 * + Any incompatible class change.
62 *
63 * The last item, incompatible class changes, also correspond to a class
64 * version change.
65 *
66 * For each distinct class format the following information is conceptually
67 * stored in the catalog, keyed by format ID.
68 *
69 * - Class name
70 * - Class version number
71 * - Superclass format
72 * - Kind: simple, enum, complex, array
73 * - For kind == simple:
74 * - Primitive class
75 * - For kind == enum:
76 * - Array of constant names, sorted by name.
77 * - For kind == complex:
78 * - Primary key fieldInfo, or null if no primary key is declared
79 * - Array of secondary key fieldInfo, sorted by field name
80 * - Array of other fieldInfo, sorted by field name
81 * - For kind == array:
82 * - Component class format
83 * - Number of array dimensions
84 * - Other metadata for RawType
85 *
86 * Where fieldInfo is:
87 * - Field name
88 * - Field class
89 * - Other metadata for RawField
90 *
91 * Data Layout
92 * -----------
93 * For each entity instance the data layout is as follows:
94 *
95 * instanceData: formatId keyFields... nonKeyFields...
96 * keyFields: fieldValue...
97 * nonKeyFields: fieldValue...
98 *
99 * The formatId is the (positive non-zero) ID of a class format, defined above.
100 * This is ID of the most derived class of the instance. It is stored as a
101 * packed integer.
102 *
103 * Following the format ID, zero or more sets of secondary key field values
104 * appear, followed by zero or more sets of other class field values.
105 *
106 * The keyFields are the sets of secondary key fields for each class in order
107 * of the highest superclass first. Within a class, fields are ordered by
108 * field name.
109 *
110 * The nonKeyFields are the sets of other non-key fields for each class in
111 * order of the highest superclass first. Within a class, fields are ordered
112 * by field name.
113 *
114 * A field value is:
115 *
116 * fieldValue: primitiveValue
117 * | nullId
118 * | instanceRef
119 * | instanceData
120 * | simpleValue
121 * | enumValue
122 * | arrayValue
123 *
124 * For a primitive type, a primitive value is used as defined for tuple
125 * bindings. For float and double, sorted float and sorted double tuple values
126 * are used.
127 *
128 * For a non-primitive type with a null value, a nullId is used that has a zero
129 * (illegal formatId) value. This includes String and other simple reference
130 * types. The formatId is stored as a packed integer, meaning that it is
131 * stored as a single zero byte.
132 *
133 * For a non-primitive type, an instanceRef is used for a non-null instance
134 * that appears earlier in the data byte array. An instanceRef is the negation
135 * of the byte offset of the instanceData that appears earlier. It is stored
136 * as a packed integer.
137 *
138 * The remaining rules apply only to reference types with non-null values that
139 * do not appear earlier in the data array.
140 *
141 * For an array type, an array formatId is used that identifies the component
142 * type and the number of array dimensions. This is followed by an array
143 * length (stored as a packed integer) and zero or more fieldValue elements.
144 * For an array with N+1 dimensions where N is greater than zero, the leftmost
145 * dimension is enumerated such that each fieldValue element is itself an array
146 * of N dimensions or null.
147 *
148 * arrayValue: formatId length fieldValue...
149 *
150 * For an enum type, an enumValue is used, consisting of a formatId that
151 * identifies the enum class and an enumIndex (stored as a packed integer) that
152 * identifies the constant name in the enum constant array of the enum class
153 * format:
154 *
155 * enumValue: formatId enumIndex
156 *
157 * For a simple type, a simpleValue is used. This consists of the formatId
158 * that identifies the class followed by the simple type value. For a
159 * primitive wrapper type the simple type value is the corresponding primitive,
160 * for a Date it is the milliseconds as a long primitive, and for BigInteger or
161 * BigDecimal it is a byte array as defined for tuple bindings of these types.
162 *
163 * simpleValue: formatId value
164 *
165 * For all other complex types, an instanceData is used, which is defined
166 * above.
167 *
168 * Secondary Keys
169 * --------------
170 * For secondary key support we must account for writing and nullifying
171 * specific keys. Rather than instantiating the entity and then performing
172 * the secondary key operation, we strive to perform the secondary key
173 * operation directly on the byte format.
174 *
175 * To create a secondary key we skip over other fields and then copy the bytes
176 * of the embedded key. This approach is very efficient because a) the entity
177 * is not instantiated, and b) the secondary keys are stored at the beginning
178 * of the byte format and can be quickly read.
179 *
180 * To nullify we currently instantiate the raw entity, set the key field to null
181 * (or remove it from the array/collection), and convert the raw entity back to
182 * bytes. Although the performance of this approach is not ideal because it
183 * requires serialization, it avoids the complexity of modifying the packed
184 * serialized format directly, adjusting references to key objects, etc. Plus,
185 * when we nullify a key we are going to write the record, so the serialization
186 * overhead may not be significant. For the record, I tried implementing
187 * nullification of the bytes directly and found it was much too complex.
188 *
189 * Lifecycle
190 * ---------
191 * Format are managed by a Catalog class. Simple formats are managed by
192 * SimpleCatalog, and are copied from the SimpleCatalog by PersistCatalog.
193 * Other formats are managed by PersistCatalog. The lifecycle of a format
194 * instance is:
195 *
196 * - Constructed by the catalog when a format is requested for a Class
197 * that currently has no associated format.
198 *
199 * - The catalog calls setId() and adds the format to its format list
200 * (indexed by format id) and map (keyed by class name).
201 *
202 * - The catalog calls collectRelatedFormats(), where a format can create
203 * additional formats that it needs, or that should also be persistent.
204 *
205 * - The catalog calls initializeIfNeeded(), which calls the initialize()
206 * method of the format class.
207 *
208 * - initialize() should initialize any transient fields in the format.
209 * initialize() can assume that all related formats are available in the
210 * catalog. It may call initializeIfNeeded() for those related formats, if
211 * it needs to interact with an initialized related format; this does not
212 * cause a cycle, because initializeIfNeeded() does nothing for an already
213 * initialized format.
214 *
215 * - The catalog creates a group of related formats at one time, and then
216 * writes its entire list of formats to the catalog DB as a single record.
217 * This grouping reduces the number of writes.
218 *
219 * - When a catalog is opened and the list of existing formats is read. After
220 * a format is deserialized, its initializeIfNeeded() method is called.
221 * setId() and collectRelatedFormats() are not called, since the ID and
222 * related formats are stored in serialized fields.
223 *
224 * - There are two modes for opening an existing catalog: raw mode and normal
225 * mode. In raw mode, the old format is used regardless of whether it
226 * matches the current class definition; in fact the class is not accessed
227 * and does not need to be present.
228 *
229 * - In normal mode, for each existing format that is initialized, a new format
230 * is also created based on the current class and metadata definition. If
231 * the two formats are equal, the new format is discarded. If they are
232 * unequal, the new format becomes the current format and the old format's
233 * evolve() method is called. evolve() is responsible for adjusting the
234 * old format for class evolution. Any number of non-current formats may
235 * exist for a given class, and are setup to evolve the single current format
236 * for the class.
237 *
238 * @author Mark Hayes
239 */
240 public abstract class Format implements Reader, RawType, Serializable {
241
242 private static final long serialVersionUID = 545633644568489850L;
243
244 /** Null reference. */
245 static final int ID_NULL = 0;
246 /** Object */
247 static final int ID_OBJECT = 1;
248 /** Boolean */
249 static final int ID_BOOL = 2;
250 static final int ID_BOOL_W = 3;
251 /** Byte */
252 static final int ID_BYTE = 4;
253 static final int ID_BYTE_W = 5;
254 /** Short */
255 static final int ID_SHORT = 6;
256 static final int ID_SHORT_W = 7;
257 /** Integer */
258 static final int ID_INT = 8;
259 static final int ID_INT_W = 9;
260 /** Long */
261 static final int ID_LONG = 10;
262 static final int ID_LONG_W = 11;
263 /** Float */
264 static final int ID_FLOAT = 12;
265 static final int ID_FLOAT_W = 13;
266 /** Double */
267 static final int ID_DOUBLE = 14;
268 static final int ID_DOUBLE_W = 15;
269 /** Character */
270 static final int ID_CHAR = 16;
271 static final int ID_CHAR_W = 17;
272 /** String */
273 static final int ID_STRING = 18;
274 /** BigInteger */
275 static final int ID_BIGINT = 19;
276 /** BigDecimal */
277 static final int ID_BIGDEC = 20;
278 /** Date */
279 static final int ID_DATE = 21;
280 /** Number */
281 static final int ID_NUMBER = 22;
282
283 /** First simple type. */
284 static final int ID_SIMPLE_MIN = 2;
285 /** Last simple type. */
286 static final int ID_SIMPLE_MAX = 21;
287 /** Last predefined ID, after which dynamic IDs are assigned. */
288 static final int ID_PREDEFINED = 30;
289
290 static boolean isPredefined(Format format) {
291 return format.getId() <= ID_PREDEFINED;
292 }
293
294 private int id;
295 private String className;
296 private Reader reader;
297 private Format superFormat;
298 private Format latestFormat;
299 private Format previousFormat;
300 private Set<String> supertypes;
301 private boolean deleted;
302 private boolean unused;
303 private transient Catalog catalog;
304 private transient Class type;
305 private transient Format proxiedFormat;
306 private transient boolean initialized;
307
308 /**
309 * Creates a new format for a given class.
310 */
311 Format(final Catalog catalog, final Class type) {
312 this(catalog, type.getName());
313 this.type = type;
314 addSupertypes();
315 }
316
317 /**
318 * Creates a format for class evolution when no class may be present.
319 */
320 Format(final Catalog catalog, final String className) {
321 assert catalog != null;
322 assert className != null;
323 this.catalog = catalog;
324 this.className = className;
325 latestFormat = this;
326 supertypes = new HashSet<String>();
327 }
328
329 /**
330 * Special handling for JE 3.0.12 beta formats.
331 */
332 void migrateFromBeta(Map<String, Format> formatMap) {
333 if (latestFormat == null) {
334 latestFormat = this;
335 }
336 }
337
338 /**
339 * Initialize transient catalog field after deserialization. This must
340 * occur before any other usage.
341 */
342 void initCatalog(final Catalog catalog) {
343 assert catalog != null;
344 this.catalog = catalog;
345 }
346
347 final boolean isNew() {
348 return id == 0;
349 }
350
351 final Catalog getCatalog() {
352 return catalog;
353 }
354
355 /**
356 * Returns the format ID.
357 */
358 public final int getId() {
359 return id;
360 }
361
362 /**
363 * Called by the Catalog to set the format ID when a new format is added to
364 * the format list, before calling initializeIfNeeded().
365 */
366 final void setId(int id) {
367 this.id = id;
368 }
369
370 /**
371 * Returns the class that this format represents. This method will return
372 * null in rawAccess mode, or for an unevolved format.
373 */
374 final Class getType() {
375 return type;
376 }
377
378 /**
379 * Called to get the type when it is known to exist for an uninitialized
380 * format.
381 */
382 final Class getExistingType() {
383 assert catalog != null;
384 if (type == null) {
385 try {
386 type = catalog.resolveClass(className);
387 } catch (ClassNotFoundException e) {
388 throw DbCompat.unexpectedException(e);
389 }
390 }
391 return type;
392 }
393
394 /**
395 * Returns the object for reading objects of the latest format. For the
396 * latest version format, 'this' is returned. For prior version formats, a
397 * reader that converts this version to the latest version is returned.
398 */
399 final Reader getReader() {
400
401 /*
402 * For unit testing, record whether any un-evolved formats are
403 * encountered.
404 */
405 if (this != reader) {
406 PersistCatalog.unevolvedFormatsEncountered = true;
407 }
408
409 return reader;
410 }
411
412 /**
413 * Changes the reader during format evolution.
414 */
415 final void setReader(Reader reader) {
416 this.reader = reader;
417 }
418
419 /**
420 * Returns the format of the superclass.
421 */
422 final Format getSuperFormat() {
423 return superFormat;
424 }
425
426 /**
427 * Called to set the format of the superclass during initialize().
428 */
429 final void setSuperFormat(Format superFormat) {
430 this.superFormat = superFormat;
431 }
432
433 /**
434 * Returns the format that is proxied by this format. If non-null is
435 * returned, then this format is a PersistentProxy.
436 */
437 final Format getProxiedFormat() {
438 return proxiedFormat;
439 }
440
441 /**
442 * Called by ProxiedFormat to set the proxied format.
443 */
444 final void setProxiedFormat(Format proxiedFormat) {
445 this.proxiedFormat = proxiedFormat;
446 }
447
448 /**
449 * If this is the latest/evolved format, returns this; otherwise, returns
450 * the current version of this format. Note that this WILL return a
451 * format for a deleted class if the latest format happens to be deleted.
452 */
453 final Format getLatestVersion() {
454 return latestFormat;
455 }
456
457 /**
458 * Returns the previous version of this format in the linked list of
459 * versions, or null if this is the only version.
460 */
461 public final Format getPreviousVersion() {
462 return previousFormat;
463 }
464
465 /**
466 * Called by Evolver to set the latest format when this old format is
467 * evolved.
468 */
469 final void setLatestVersion(Format newFormat) {
470
471 /*
472 * If this old format is the former latest version, link it to the new
473 * latest version. This creates a singly linked list of versions
474 * starting with the latest.
475 */
476 if (latestFormat == this) {
477 newFormat.previousFormat = this;
478 }
479
480 latestFormat = newFormat;
481 }
482
483 /**
484 * Returns whether the class for this format was deleted.
485 */
486 public final boolean isDeleted() {
487 return deleted;
488 }
489
490 /**
491 * Called by the Evolver when applying a Deleter mutation.
492 */
493 final void setDeleted(boolean deleted) {
494 this.deleted = deleted;
495 }
496
497 /**
498 * Called by the Evolver for a format that is never referenced.
499 */
500 final void setUnused(boolean unused) {
501 this.unused = unused;
502 }
503
504 /**
505 * Called by the Evolver with true when an entity format or any of its
506 * nested format were changed. Called by Store.evolve when an entity has
507 * been fully converted. Overridden by ComplexFormat.
508 */
509 void setEvolveNeeded(boolean needed) {
510 throw DbCompat.unexpectedState();
511 }
512
513 /**
514 * Overridden by ComplexFormat.
515 */
516 boolean getEvolveNeeded() {
517 throw DbCompat.unexpectedState();
518 }
519
520 /**
521 * For an entity format, returns whether the entity was written using the
522 * new String format. For a non-entity format, this method should not be
523 * called.
524 *
525 * Overridden by ComplexFormat.
526 */
527 boolean getNewStringFormat() {
528 throw DbCompat.unexpectedState();
529 }
530
531 final boolean isInitialized() {
532 return initialized;
533 }
534
535 /**
536 * Called by the Catalog to initialize a format, and may also be called
537 * during initialize() for a related format to ensure that the related
538 * format is initialized. This latter case is allowed to support
539 * bidirectional dependencies. This method will do nothing if the format
540 * is already intialized.
541 */
542 final void initializeIfNeeded(Catalog catalog, EntityModel model) {
543 assert catalog != null;
544
545 if (!initialized) {
546 initialized = true;
547 this.catalog = catalog;
548
549 /* Initialize objects serialized by an older Format class. */
550 if (latestFormat == null) {
551 latestFormat = this;
552 }
553 if (reader == null) {
554 reader = this;
555 }
556
557 /*
558 * The class is only guaranteed to be available in live (not raw)
559 * mode, for the current version of the format.
560 */
561 if (type == null &&
562 isCurrentVersion() &&
563 (isSimple() || !catalog.isRawAccess())) {
564 getExistingType();
565 }
566
567 /* Perform subclass-specific initialization. */
568 initialize(catalog, model,
569 catalog.getInitVersion(this, false /*forReader*/));
570 reader.initializeReader
571 (catalog, model,
572 catalog.getInitVersion(this, true /*forReader*/),
573 this);
574 }
575 }
576
577 /**
578 * Called to initialize a separate Reader implementation. This method is
579 * called when no separate Reader exists, and does nothing.
580 */
581 public void initializeReader(Catalog catalog,
582 EntityModel model,
583 int initVersion,
584 Format oldFormat) {
585 }
586
587 /**
588 * Adds all interfaces and superclasses to the supertypes set.
589 */
590 private void addSupertypes() {
591 addInterfaces(type);
592 Class stype = type.getSuperclass();
593 while (stype != null && stype != Object.class) {
594 supertypes.add(stype.getName());
595 addInterfaces(stype);
596 stype = stype.getSuperclass();
597 }
598 }
599
600 /**
601 * Recursively adds interfaces to the supertypes set.
602 */
603 private void addInterfaces(Class cls) {
604 Class[] interfaces = cls.getInterfaces();
605 for (Class iface : interfaces) {
606 if (iface != Enhanced.class) {
607 supertypes.add(iface.getName());
608 addInterfaces(iface);
609 }
610 }
611 }
612
613 /**
614 * Certain formats (ProxiedFormat for example) prohibit nested fields that
615 * reference the parent object. [#15815]
616 */
617 boolean areNestedRefsProhibited() {
618 return false;
619 }
620
621 /* -- Start of RawType interface methods. -- */
622
623 public String getClassName() {
624 return className;
625 }
626
627 public int getVersion() {
628 ClassMetadata meta = getClassMetadata();
629 if (meta != null) {
630 return meta.getVersion();
631 } else {
632 return 0;
633 }
634 }
635
636 public Format getSuperType() {
637 return superFormat;
638 }
639
640 /* -- RawType methods that are overridden as needed in subclasses. -- */
641
642 public boolean isSimple() {
643 return false;
644 }
645
646 public boolean isPrimitive() {
647 return false;
648 }
649
650 public boolean isEnum() {
651 return false;
652 }
653
654 public List<String> getEnumConstants() {
655 return null;
656 }
657
658 public boolean isArray() {
659 return false;
660 }
661
662 public int getDimensions() {
663 return 0;
664 }
665
666 public Format getComponentType() {
667 return null;
668 }
669
670 public Map<String, RawField> getFields() {
671 return null;
672 }
673
674 public ClassMetadata getClassMetadata() {
675 return null;
676 }
677
678 public EntityMetadata getEntityMetadata() {
679 return null;
680 }
681
682 /* -- End of RawType methods. -- */
683
684 /* -- Methods that may optionally be overridden by subclasses. -- */
685
686 /**
687 * Called by EntityOutput in rawAccess mode to determine whether an object
688 * type is allowed to be assigned to a given field type.
689 */
690 boolean isAssignableTo(Format format) {
691 if (proxiedFormat != null) {
692 return proxiedFormat.isAssignableTo(format);
693 } else {
694 return format == this ||
695 format.id == ID_OBJECT ||
696 supertypes.contains(format.className);
697 }
698 }
699
700 /**
701 * For primitive types only, returns their associated wrapper type.
702 */
703 Format getWrapperFormat() {
704 return null;
705 }
706
707 /**
708 * Returns whether this format class is an entity class.
709 */
710 boolean isEntity() {
711 return false;
712 }
713
714 /**
715 * Returns whether this class is present in the EntityModel. Returns false
716 * for a simple type, array type, or enum type.
717 */
718 boolean isModelClass() {
719 return false;
720 }
721
722 /**
723 * For an entity class or subclass, returns the base entity class; returns
724 * null in other cases.
725 */
726 ComplexFormat getEntityFormat() {
727 return null;
728 }
729
730 /**
731 * Called for an existing format that may not equal the current format for
732 * the same class.
733 *
734 * <p>If this method returns true, then it must have determined one of two
735 * things:
736 * - that the old and new formats are equal, and it must have called
737 * Evolver.useOldFormat; or
738 * - that the old format can be evolved to the new format, and it must
739 * have called Evolver.useEvolvedFormat.</p>
740 *
741 * <p>If this method returns false, then it must have determined that the
742 * old format could not be evolved to the new format, and it must have
743 * called Evolver.addInvalidMutation, addMissingMutation or
744 * addEvolveError.</p>
745 */
746 abstract boolean evolve(Format newFormat, Evolver evolver);
747
748 /**
749 * Called when a Converter handles evolution of a class, but we may still
750 * need to evolve the metadata.
751 */
752 boolean evolveMetadata(Format newFormat,
753 Converter converter,
754 Evolver evolver) {
755 return true;
756 }
757
758 /**
759 * Returns whether this format is the current format for its class. If
760 * false is returned, this format is setup to evolve to the current format.
761 */
762 final boolean isCurrentVersion() {
763 return latestFormat == this && !deleted;
764 }
765
766 /**
767 * Returns whether this format has the same class as the given format,
768 * irrespective of version changes and renaming.
769 */
770 final boolean isSameClass(Format other) {
771 return latestFormat == other.latestFormat;
772 }
773
774 /* -- Abstract methods that must be implemented by subclasses. -- */
775
776 /**
777 * Initializes an uninitialized format, initializing its related formats
778 * (superclass formats and array component formats) first.
779 */
780 abstract void initialize(Catalog catalog,
781 EntityModel model,
782 int initVersion);
783
784 /**
785 * Calls catalog.createFormat for formats that this format depends on, or
786 * that should also be persistent.
787 */
788 abstract void collectRelatedFormats(Catalog catalog,
789 Map<String, Format> newFormats);
790
791 /*
792 * The remaining methods are used to read objects from data bytes via
793 * EntityInput, and to write objects as data bytes via EntityOutput.
794 * Ultimately these methods call methods in the Accessor interface to
795 * get/set fields in the object. Most methods have a rawAccess parameter
796 * that determines whether the object is a raw object or a real persistent
797 * object.
798 *
799 * The first group of methods are abstract and must be implemented by
800 * format classes. The second group have default implementations that
801 * throw UnsupportedOperationException and may optionally be overridden.
802 */
803
804 /**
805 * Creates an array of the format's class of the given length, as if
806 * Array.newInstance(getType(), len) were called. Formats implement this
807 * method for specific classes, or call the accessor, to avoid the
808 * reflection overhead of Array.newInstance.
809 */
810 abstract Object newArray(int len);
811
812 /**
813 * Creates a new instance of the target class using its default
814 * constructor. Normally this creates an empty object, and readObject() is
815 * called next to fill in the contents. This is done in two steps to allow
816 * the instance to be registered by EntityInput before reading the
817 * contents. This allows the fields in an object or a nested object to
818 * refer to the parent object in a graph.
819 *
820 * Alternatively, this method may read all or the first portion of the
821 * data, rather than that being done by readObject(). This is required for
822 * simple types and enums, where the object cannot be created without
823 * reading the data. In these cases, there is no possibility that the
824 * parent object will be referenced by the child object in the graph. It
825 * should not be done in other cases, or the graph references may not be
826 * maintained faithfully.
827 *
828 * Is public only in order to implement the Reader interface. Note that
829 * this method should only be called directly in raw conversion mode or
830 * during conversion of an old format. Normally it should be called via
831 * the getReader method and the Reader interface.
832 */
833 public abstract Object newInstance(EntityInput input, boolean rawAccess)
834 throws RefreshException;
835
836 /**
837 * Called after newInstance() to read the rest of the data bytes and fill
838 * in the object contents. If the object was read completely by
839 * newInstance(), this method does nothing.
840 *
841 * Is public only in order to implement the Reader interface. Note that
842 * this method should only be called directly in raw conversion mode or
843 * during conversion of an old format. Normally it should be called via
844 * the getReader method and the Reader interface.
845 */
846 public abstract Object readObject(Object o,
847 EntityInput input,
848 boolean rawAccess)
849 throws RefreshException;
850
851 /**
852 * Writes a given instance of the target class to the output data bytes.
853 * This is the complement of the newInstance()/readObject() pair.
854 */
855 abstract void writeObject(Object o, EntityOutput output, boolean rawAccess)
856 throws RefreshException;
857
858 /**
859 * Skips over the object's contents, as if readObject() were called, but
860 * without returning an object. Used for extracting secondary key bytes
861 * without having to instantiate the object. For reference types, the
862 * format ID is read just before calling this method, so this method is
863 * responsible for skipping everything following the format ID.
864 */
865 abstract void skipContents(RecordInput input)
866 throws RefreshException;
867
868 /* -- More methods that may optionally be overridden by subclasses. -- */
869
870 /**
871 * When extracting a secondary key, called to skip over all fields up to
872 * the given secondary key field. Returns the format of the key field
873 * found, or null if the field is not present (nullified) in the object.
874 */
875 Format skipToSecKey(RecordInput input, String keyName)
876 throws RefreshException {
877
878 throw DbCompat.unexpectedState(toString());
879 }
880
881 /**
882 * Called after skipToSecKey() to copy the data bytes of a singular
883 * (XXX_TO_ONE) key field.
884 */
885 void copySecKey(RecordInput input, RecordOutput output) {
886 throw DbCompat.unexpectedState(toString());
887 }
888
889 /**
890 * Called after skipToSecKey() to copy the data bytes of an array or
891 * collection (XXX_TO_MANY) key field.
892 */
893 void copySecMultiKey(RecordInput input, Format keyFormat, Set results)
894 throws RefreshException {
895
896 throw DbCompat.unexpectedState(toString());
897 }
898
899 /**
900 * Nullifies the given key field in the given RawObject -- rawAccess mode
901 * is implied.
902 */
903 boolean nullifySecKey(Catalog catalog,
904 Object entity,
905 String keyName,
906 Object keyElement) {
907 throw DbCompat.unexpectedState(toString());
908 }
909
910 /**
911 * Returns whether the entity's primary key field is null or zero, as
912 * defined for primary keys that are assigned from a sequence.
913 */
914 boolean isPriKeyNullOrZero(Object o, boolean rawAccess) {
915 throw DbCompat.unexpectedState(toString());
916 }
917
918 /**
919 * Gets the primary key field from the given object and writes it to the
920 * given output data bytes. This is a separate operation because the
921 * primary key data bytes are stored separately from the rest of the
922 * record.
923 */
924 void writePriKey(Object o, EntityOutput output, boolean rawAccess)
925 throws RefreshException {
926
927 throw DbCompat.unexpectedState(toString());
928 }
929
930 /**
931 * Reads the primary key from the given input bytes and sets the primary
932 * key field in the given object. This is complement of writePriKey().
933 *
934 * Is public only in order to implement the Reader interface. Note that
935 * this method should only be called directly in raw conversion mode or
936 * during conversion of an old format. Normally it should be called via
937 * the getReader method and the Reader interface.
938 */
939 public void readPriKey(Object o, EntityInput input, boolean rawAccess)
940 throws RefreshException {
941
942 throw DbCompat.unexpectedState(toString());
943 }
944
945 /**
946 * For an entity class or subclass, returns the old key name for the given
947 * key name that has been renamed, or returns the given key name if it has
948 * not been renamed.
949 */
950 public String getOldKeyName(final String keyName) {
951 throw DbCompat.unexpectedState(toString());
952 }
953
954 /**
955 * Validates and returns the simple integer key format for a sequence key
956 * associated with this format.
957 *
958 * For a composite key type, the format of the one and only field is
959 * returned. For a simple integer type, this format is returned.
960 * Otherwise (the default implementation), an IllegalArgumentException is
961 * thrown.
962 */
963 Format getSequenceKeyFormat() {
964 throw new IllegalArgumentException
965 ("Type not allowed for sequence: " + getClassName());
966 }
967
968 /**
969 * Converts a RawObject to a current class object and adds the converted
970 * pair to the converted map.
971 */
972 Object convertRawObject(Catalog catalog,
973 boolean rawAccess,
974 RawObject rawObject,
975 IdentityHashMap converted)
976 throws RefreshException {
977
978 throw DbCompat.unexpectedState(toString());
979 }
980
981 /**
982 * Currently, only FBigDec will return true. It is a workaround for reading
983 * the BigDecimal data stored by BigDecimal proxy before je4.1.
984 */
985 public boolean allowEvolveFromProxy() {
986 return false;
987 }
988
989 public Accessor getAccessor(boolean rawAccess) {
990 return null;
991 }
992
993 @Override
994 public String toString() {
995 final String INDENT = " ";
996 final String INDENT2 = INDENT + " ";
997 StringBuilder buf = new StringBuilder(500);
998 if (isSimple()) {
999 addTypeHeader(buf, "SimpleType");
1000 buf.append(" primitive=\"");
1001 buf.append(isPrimitive());
1002 buf.append("\"/>\n");
1003 } else if (isEnum()) {
1004 addTypeHeader(buf, "EnumType");
1005 buf.append(">\n");
1006 for (String constant : getEnumConstants()) {
1007 buf.append(INDENT);
1008 buf.append("<Constant>");
1009 buf.append(constant);
1010 buf.append("</Constant>\n");
1011 }
1012 buf.append("</EnumType>\n");
1013 } else if (isArray()) {
1014 addTypeHeader(buf, "ArrayType");
1015 buf.append(" componentId=\"");
1016 buf.append(getComponentType().getVersion());
1017 buf.append("\" componentClass=\"");
1018 buf.append(getComponentType().getClassName());
1019 buf.append("\" dimensions=\"");
1020 buf.append(getDimensions());
1021 buf.append("\"/>\n");
1022 } else {
1023 addTypeHeader(buf, "ComplexType");
1024 Format superType = getSuperType();
1025 if (superType != null) {
1026 buf.append(" superTypeId=\"");
1027 buf.append(superType.getId());
1028 buf.append("\" superTypeClass=\"");
1029 buf.append(superType.getClassName());
1030 buf.append('"');
1031 }
1032 Format proxiedFormat = getProxiedFormat();
1033 if (proxiedFormat != null) {
1034 buf.append(" proxiedTypeId=\"");
1035 buf.append(proxiedFormat.getId());
1036 buf.append("\" proxiedTypeClass=\"");
1037 buf.append(proxiedFormat.getClassName());
1038 buf.append('"');
1039 }
1040 PrimaryKeyMetadata priMeta = null;
1041 Map<String, SecondaryKeyMetadata> secondaryKeys = null;
1042 List<FieldMetadata> compositeKeyFields = null;
1043 ClassMetadata clsMeta = getClassMetadata();
1044 if (clsMeta != null) {
1045 compositeKeyFields = clsMeta.getCompositeKeyFields();
1046 priMeta = clsMeta.getPrimaryKey();
1047 secondaryKeys = clsMeta.getSecondaryKeys();
1048 }
1049 buf.append(" kind=\"");
1050 buf.append(isEntity() ? "entity" :
1051 ((compositeKeyFields != null) ? "compositeKey" :
1052 "persistent"));
1053 buf.append("\">\n");
1054 Map<String, RawField> fields = getFields();
1055 if (fields != null) {
1056 for (RawField field : fields.values()) {
1057 String name = field.getName();
1058 RawType type = field.getType();
1059 buf.append(INDENT);
1060 buf.append("<Field");
1061 buf.append(" name=\"");
1062 buf.append(name);
1063 buf.append("\" typeId=\"");
1064 buf.append(type.getId());
1065 buf.append("\" typeClass=\"");
1066 buf.append(type.getClassName());
1067 buf.append('"');
1068 if (priMeta != null &&
1069 priMeta.getName().equals(name)) {
1070 buf.append(" primaryKey=\"true\"");
1071 if (priMeta.getSequenceName() != null) {
1072 buf.append(" sequence=\"");
1073 buf.append(priMeta.getSequenceName());
1074 buf.append('"');
1075 }
1076 }
1077 if (secondaryKeys != null) {
1078 SecondaryKeyMetadata secMeta =
1079 ComplexFormat.getSecondaryKeyMetadataByFieldName
1080 (secondaryKeys, name);
1081 if (secMeta != null) {
1082 buf.append(" secondaryKey=\"true\" keyName=\"");
1083 buf.append(secMeta.getKeyName());
1084 buf.append("\" relate=\"");
1085 buf.append(secMeta.getRelationship());
1086 buf.append('"');
1087 String related = secMeta.getRelatedEntity();
1088 if (related != null) {
1089 buf.append("\" relatedEntity=\"");
1090 buf.append(related);
1091 buf.append("\" onRelatedEntityDelete=\"");
1092 buf.append(secMeta.getDeleteAction());
1093 buf.append('"');
1094 }
1095 }
1096 }
1097 if (compositeKeyFields != null) {
1098 int nFields = compositeKeyFields.size();
1099 for (int i = 0; i < nFields; i += 1) {
1100 FieldMetadata fldMeta = compositeKeyFields.get(i);
1101 if (fldMeta.getName().equals(name)) {
1102 buf.append(" compositeKeyField=\"");
1103 buf.append(i + 1);
1104 buf.append('"');
1105 }
1106 }
1107 }
1108 buf.append("/>\n");
1109 }
1110 EntityMetadata entMeta = getEntityMetadata();
1111 if (entMeta != null) {
1112 buf.append(INDENT);
1113 buf.append("<EntityKeys>\n");
1114 priMeta = entMeta.getPrimaryKey();
1115 if (priMeta != null) {
1116 buf.append(INDENT2);
1117 buf.append("<Primary class=\"");
1118 buf.append(priMeta.getDeclaringClassName());
1119 buf.append("\" field=\"");
1120 buf.append(priMeta.getName());
1121 buf.append("\"/>\n");
1122 }
1123 secondaryKeys = entMeta.getSecondaryKeys();
1124 if (secondaryKeys != null) {
1125 for (SecondaryKeyMetadata secMeta :
1126 secondaryKeys.values()) {
1127 buf.append(INDENT2);
1128 buf.append("<Secondary class=\"");
1129 buf.append(secMeta.getDeclaringClassName());
1130 buf.append("\" field=\"");
1131 buf.append(secMeta.getName());
1132 buf.append("\"/>\n");
1133 }
1134 }
1135 buf.append("</EntityKeys>\n");
1136 }
1137 }
1138 buf.append("</ComplexType>\n");
1139 }
1140 return buf.toString();
1141 }
1142
1143 private void addTypeHeader(StringBuilder buf, String elemName) {
1144 buf.append('<');
1145 buf.append(elemName);
1146 buf.append(" id=\"");
1147 buf.append(getId());
1148 buf.append("\" class=\"");
1149 buf.append(getClassName());
1150 buf.append("\" version=\"");
1151 buf.append(getVersion());
1152 buf.append('"');
1153 Format currVersion = getLatestVersion();
1154 if (currVersion != null) {
1155 buf.append(" currentVersionId=\"");
1156 buf.append(currVersion.getId());
1157 buf.append('"');
1158 }
1159 Format prevVersion = getPreviousVersion();
1160 if (prevVersion != null) {
1161 buf.append(" previousVersionId=\"");
1162 buf.append(prevVersion.getId());
1163 buf.append('"');
1164 }
1165 }
1166 }