summaryrefslogtreecommitdiff
path: root/src/main/java/com/amazon/carbonado/layout/Layout.java
blob: df20f3ff07bc07448ff21ad422d0f6249ff51bea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/*
 * Copyright 2006-2012 Amazon Technologies, Inc. or its affiliates.
 * Amazon, Amazon.com and Carbonado are trademarks or registered trademarks
 * of Amazon Technologies, Inc. or its affiliates.  All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.amazon.carbonado.layout;

import java.io.IOException;
import java.io.OutputStream;

import java.net.InetAddress;
import java.net.UnknownHostException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;

import org.apache.commons.logging.LogFactory;

import com.amazon.carbonado.CorruptEncodingException;
import com.amazon.carbonado.Cursor;
import com.amazon.carbonado.FetchException;
import com.amazon.carbonado.FetchNoneException;
import com.amazon.carbonado.PersistException;
import com.amazon.carbonado.Query;
import com.amazon.carbonado.RepositoryException;
import com.amazon.carbonado.Storable;
import com.amazon.carbonado.SupportException;
import com.amazon.carbonado.UniqueConstraintException;
import com.amazon.carbonado.info.StorableInfo;
import com.amazon.carbonado.info.StorableProperty;
import com.amazon.carbonado.synthetic.SyntheticKey;
import com.amazon.carbonado.synthetic.SyntheticProperty;
import com.amazon.carbonado.synthetic.SyntheticStorableBuilder;
import com.amazon.carbonado.util.AnnotationDescPrinter;
import com.amazon.carbonado.util.SoftValuedCache;

import com.amazon.carbonado.capability.ResyncCapability;

/**
 * Describes the layout of a specific generation of a storable.
 *
 * @author Brian S O'Neill
 * @see LayoutFactory
 */
public class Layout {
    private static SoftValuedCache<Long, Class<? extends Storable>> cReconstructed;

    static {
        cReconstructed = SoftValuedCache.newCache(7);
    }

    static Class<? extends Storable> reconstruct(final Layout layout, ClassLoader loader)
        throws FetchException, SupportException
    {
        synchronized (cReconstructed) {
            Long key = layout.getLayoutID();
            Class<? extends Storable> clazz = cReconstructed.get(key);
            if (clazz != null) {
                return clazz;
            }

            SyntheticStorableBuilder builder =
                new SyntheticStorableBuilder(layout.getStorableTypeName(), loader);

            // Make sure reconstructed class encodes the same as before.
            builder.setEvolvable(true);

            builder.setClassNameProvider(new SyntheticStorableBuilder.ClassNameProvider() {
                public String getName() {
                    return layout.getStorableTypeName();
                }

                // The name of the auto-generated class should not be made with
                // createExplicit. Otherwise, property type changes will
                // conflict, since the reconstructed class name is the same.
                public boolean isExplicit() {
                    return false;
                }
            });

            SyntheticKey primaryKey = builder.addPrimaryKey();

            for (LayoutProperty property : layout.getAllProperties()) {
                Class propClass = property.getPropertyType(loader);
                if (Query.class.isAssignableFrom(propClass) ||
                    Storable.class.isAssignableFrom(propClass)) {
                    // Accidentally stored join property in layout, caused by a
                    // bug in a previous version of Layout. Move on.
                    continue;
                }

                SyntheticProperty synthProp =
                    builder.addProperty(property.getPropertyName(), propClass);

                synthProp.setIsNullable(property.isNullable());
                synthProp.setIsVersion(property.isVersion());

                if (property.isPrimaryKeyMember()) {
                    primaryKey.addProperty(property.getPropertyName());
                }

                if (property.getAdapterTypeName() != null) {
                    String desc = property.getAdapterParams();
                    if (desc == null) {
                        desc = AnnotationDescPrinter
                            .makePlainDescriptor(property.getAdapterTypeName());
                    }
                    synthProp.addAccessorAnnotationDescriptor(desc);
                }
            }

            clazz = builder.build();

            cReconstructed.put(key, clazz);
            return clazz;
        }
    }

    private final LayoutFactory mLayoutFactory;
    private final StoredLayout mStoredLayout;
    private final LayoutOptions mOptions;

    private volatile List<LayoutProperty> mAllProperties;

    /**
     * Creates a Layout around an existing storable.
     */
    Layout(LayoutFactory factory, StoredLayout storedLayout) throws CorruptEncodingException {
        mLayoutFactory = factory;
        mStoredLayout = storedLayout;

        byte[] extra = storedLayout.getExtraData();
        if (extra == null) {
            mOptions = null;
        } else {
            mOptions = new LayoutOptions();
            try {
                mOptions.decode(extra);
            } catch (IOException e) {
                throw new CorruptEncodingException(e);
            }
            mOptions.readOnly();
        }
    }

    /**
     * Copies layout information into freshly prepared storables. Call insert
     * (on this class) to persist them.
     */
    Layout(LayoutFactory factory, StorableInfo<?> info, LayoutOptions options, long layoutID) {
        mLayoutFactory = factory;

        StoredLayout storedLayout = factory.mLayoutStorage.prepare();
        mStoredLayout = storedLayout;

        storedLayout.setLayoutID(layoutID);
        storedLayout.setStorableTypeName(info.getStorableType().getName());
        storedLayout.setCreationTimestamp(System.currentTimeMillis());
        try {
            storedLayout.setCreationUser(System.getProperty("user.name"));
        } catch (SecurityException e) {
            // Can't get user, no big deal.
        }
        try {
            storedLayout.setCreationHost(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            // Can't get host, no big deal.
        } catch (SecurityException e) {
            // Can't get host, no big deal.
        }

        if (options == null) {
            mOptions = null;
        } else {
            options.readOnly();
            storedLayout.setExtraData(options.encode());
            mOptions = options;
        }

        Collection<? extends StorableProperty<?>> properties = info.getAllProperties().values();
        List<LayoutProperty> list = new ArrayList<LayoutProperty>(properties.size());
        int ordinal = 0;
        for (StorableProperty<?> property : properties) {
            if (property.isDerived() || property.isJoin()) {
                continue;
            }
            StoredLayoutProperty storedLayoutProperty = mLayoutFactory.mPropertyStorage.prepare();
            list.add(new LayoutProperty(storedLayoutProperty, property, layoutID, ordinal));
            ordinal++;
        }

        mAllProperties = Collections.unmodifiableList(list);
    }

    /**
     * Returns a unique identifier for this layout.
     */
    public long getLayoutID() {
        return mStoredLayout.getLayoutID();
    }

    /**
     * Storable type name is a fully qualified Java class name.
     */
    public String getStorableTypeName() {
        return mStoredLayout.getStorableTypeName();
    }

    /**
     * Returns the generation of this layout, where zero represents the first
     * generation.
     */
    public int getGeneration() {
        return mStoredLayout.getGeneration();
    }

    /**
     * Returns all the non-primary key properties of this layout, in their
     * proper order.
     */
    public List<LayoutProperty> getDataProperties() throws FetchException {
        List<LayoutProperty> all = getAllProperties();
        List<LayoutProperty> data = new ArrayList<LayoutProperty>(all.size() - 1);
        for (LayoutProperty property : all) {
            if (!property.isPrimaryKeyMember()) {
                data.add(property);
            }
        }
        return Collections.unmodifiableList(data);
    }

    /**
     * Returns all the properties of this layout, in their proper order.
     */
    public List<LayoutProperty> getAllProperties() throws FetchException {
        List<LayoutProperty> all = mAllProperties;

        if (all == null) {
            Cursor <StoredLayoutProperty> cursor = mLayoutFactory.mPropertyStorage
                .query("layoutID = ?")
                .with(mStoredLayout.getLayoutID())
                .orderBy("ordinal")
                .fetch();

            try {
                List<LayoutProperty> list = new ArrayList<LayoutProperty>();

                while (cursor.hasNext()) {
                    list.add(new LayoutProperty(cursor.next()));
                }

                mAllProperties = all = Collections.unmodifiableList(list);
            } finally {
                cursor.close();
            }
        }

        return all;
    }

    /**
     * Returns the date and time for when this layout generation was created.
     */
    public DateTime getCreationDateTime() {
        return new DateTime(mStoredLayout.getCreationTimestamp());
    }

    /**
     * Returns the user that created this layout generation.
     */
    public String getCreationUser() {
        return mStoredLayout.getCreationUser();
    }

    /**
     * Returns the host machine that created this generation.
     */
    public String getCreationHost() {
        return mStoredLayout.getCreationHost();
    }

    /**
     * Returns additional options, or null if none.
     *
     * @return read-only object or null
     */
    public LayoutOptions getOptions() {
        return mOptions;
    }

    /**
     * Returns the layout for a particular generation of this layout's type.
     *
     * @throws FetchNoneException if generation not found
     */
    public Layout getGeneration(int generation) throws FetchNoneException, FetchException {
        final String filter = "storableTypeName = ? & generation = ?";

        StoredLayout storedLayout;
        try {
            storedLayout = mLayoutFactory.mLayoutStorage
                .query(filter)
                .with(getStorableTypeName()).with(generation)
                .loadOne();
        } catch (FetchNoneException e) {
            // Try to resync with a master.
            ResyncCapability cap =
                mLayoutFactory.mRepository.getCapability(ResyncCapability.class);

            if (cap == null) {
                throw e;
            }

            try {
                cap.resync(mLayoutFactory.mLayoutStorage.getStorableType(), 1.0,
                           filter, getStorableTypeName(), generation);
            } catch (RepositoryException e2) {
                // Uh oh, double trouble. Log this one and throw original exception.
                LogFactory.getLog(Layout.class).error("Unable to resync layout", e2);
                throw e;
            }

            storedLayout = mLayoutFactory.mLayoutStorage
                .query(filter)
                .with(getStorableTypeName()).with(generation)
                .loadOne();

            // Make sure all the properties are re-sync'd too.
            try {
                cap.resync(mLayoutFactory.mPropertyStorage.getStorableType(), 1.0,
                           "layoutID = ?", storedLayout.getLayoutID());
            } catch (RepositoryException e2) {
                // Uh oh, double trouble. Log this one and throw original exception.
                LogFactory.getLog(Layout.class).error("Unable to resync layout", e2);
                throw e;
            }
        }

        return new Layout(mLayoutFactory, storedLayout);
    }

    /**
     * Returns the previous known generation of the storable's layout, or null
     * if none.
     *
     * @return a layout with a lower generation, or null if none
     */
    public Layout previousGeneration() throws FetchException {
        Cursor<StoredLayout> cursor = mLayoutFactory.mLayoutStorage
            .query("storableTypeName = ? & generation < ?")
            .with(getStorableTypeName()).with(getGeneration())
            .orderBy("-generation")
            .fetch();

        try {
            if (cursor.hasNext()) {
                return new Layout(mLayoutFactory, cursor.next());
            }
        } finally {
            cursor.close();
        }

        return null;
    }

    /**
     * Returns the next known generation of the storable's layout, or null
     * if none.
     *
     * @return a layout with a higher generation, or null if none
     */
    public Layout nextGeneration() throws FetchException {
        Cursor<StoredLayout> cursor =
            mLayoutFactory.mLayoutStorage.query("storableTypeName = ? & generation > ?")
            .with(getStorableTypeName()).with(getGeneration())
            .orderBy("+generation")
            .fetch();

        try {
            if (cursor.hasNext()) {
                return new Layout(mLayoutFactory, cursor.next());
            }
        } finally {
            cursor.close();
        }

        return null;
    }

    /**
     * Reconstructs the storable type defined by this layout by returning an
     * auto-generated class. The reconstructed storable type will not contain
     * everything in the original, but rather the minimum required to decode
     * persisted instances.
     */
    public Class<? extends Storable> reconstruct() throws FetchException, SupportException {
        return reconstruct(null);
    }

    /**
     * Reconstructs the storable type defined by this layout by returning an
     * auto-generated class. The reconstructed storable type will not contain
     * everything in the original, but rather the minimum required to decode
     * persisted instances.
     *
     * @param loader optional ClassLoader to load reconstruct class into, if it
     * has not been loaded yet
     */
    public Class<? extends Storable> reconstruct(ClassLoader loader)
        throws FetchException, SupportException
    {
        Class<? extends Storable> reconstructed = reconstruct(this, loader);
        mLayoutFactory.registerReconstructed(reconstructed, this);
        return reconstructed;
    }

    @Override
    public int hashCode() {
        long id = getLayoutID();
        return ((int) id) ^ (int) (id >> 32);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Layout) {
            Layout other = (Layout) obj;
            try {
                return mStoredLayout.equals(other.mStoredLayout) && equalLayouts(other);
            } catch (FetchException e) {
                return false;
            }
        }
        return false;
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder();
        b.append("Layout {type=").append(getStorableTypeName());
        b.append(", generation=").append(getGeneration());
        b.append(", properties={");
        try {
            List<LayoutProperty> props = getAllProperties();
            for (int i=0; i<props.size(); i++) {
                if (i > 0) {
                    b.append(", ");
                }
                b.append(props.get(i));
            }
        } catch (FetchException e) {
            b.append(e.toString());
        }
        b.append("}}");
        return b.toString();
    }

    /**
     * Returns true if the given layout matches this one. Layout ID,
     * generation, and creation info is not considered in the comparison.
     */
    public boolean equalLayouts(Layout layout) throws FetchException {
        if (this == layout) {
            return true;
        }
        return getStorableTypeName().equals(layout.getStorableTypeName())
            && getAllProperties().equals(layout.getAllProperties())
            && Arrays.equals(mStoredLayout.getExtraData(), layout.mStoredLayout.getExtraData());
    }

    /**
     * Write a layout to be read by {@link LayoutFactory#readLayoutFrom}.
     *
     * @since 1.2.2
     */
    public void writeTo(OutputStream out) throws IOException, RepositoryException {
        mStoredLayout.writeTo(out);

        Cursor <StoredLayoutProperty> cursor = mLayoutFactory.mPropertyStorage
            .query("layoutID = ?")
            .with(mStoredLayout.getLayoutID())
            .fetch();

        try {
            while (cursor.hasNext()) {
                StoredLayoutProperty prop = cursor.next();
                // Write 1 to indicate that this was not the last property.
                out.write(1);
                prop.writeTo(out);
            }
        } finally {
            cursor.close();
        }

        out.write(0);
    }

    // Assumes caller is in a transaction.
    void insert(boolean readOnly, int generation) throws PersistException {
        if (mAllProperties == null) {
            throw new IllegalStateException();
        }

        mStoredLayout.setGeneration(generation);

        if (readOnly) {
            return;
        }

        try {
            mStoredLayout.insert();
        } catch (UniqueConstraintException e) {
            // If existing record logically matches, update to allow replication.
            StoredLayout existing = mStoredLayout.prepare();
            mStoredLayout.copyPrimaryKeyProperties(existing);
            try {
                existing.load();
            } catch (FetchException e2) {
                throw e2.toPersistException();
            }
            if (existing.getGeneration() != generation ||
                !existing.getStorableTypeName().equals(getStorableTypeName()) ||
                !Arrays.equals(existing.getExtraData(), mStoredLayout.getExtraData()))
            {
                throw e;
            }
            mStoredLayout.setVersionNumber(existing.getVersionNumber());
            mStoredLayout.update();
        }

        for (LayoutProperty property : mAllProperties) {
            property.insert();
        }
    }
}