summaryrefslogtreecommitdiff
path: root/src/main/java/com/amazon/carbonado/info/ChainedProperty.java
blob: ab01c5fe416df1e8cab0328bf9828bcfa7b25bd8 (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
/*
 * Copyright 2006 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.info;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.cojen.util.WeakCanonicalSet;

import com.amazon.carbonado.Storable;
import com.amazon.carbonado.util.Appender;

/**
 * Represents a property to query against or to order by. Properties may be
 * specified in a simple form, like "firstName", or in a chained form, like
 * "address.state". In both forms, the first property is the "prime"
 * property. All properties that follow are chained.
 *
 * @author Brian S O'Neill
 */
public class ChainedProperty<S extends Storable> implements Appender {
    static WeakCanonicalSet cCanonical = new WeakCanonicalSet();

    /**
     * Returns a canonical instance which has no chain.
     *
     * @throws IllegalArgumentException if prime is null
     */
    @SuppressWarnings("unchecked")
    public static <S extends Storable> ChainedProperty<S> get(StorableProperty<S> prime) {
        return (ChainedProperty<S>) cCanonical.put(new ChainedProperty<S>(prime, null));
    }

    /**
     * Returns a canonical instance.
     *
     * @throws IllegalArgumentException if prime is null or if chained
     * properties are not formed properly
     */
    @SuppressWarnings("unchecked")
    public static <S extends Storable> ChainedProperty<S> get(StorableProperty<S> prime,
                                                              StorableProperty<?>... chain) {
        return (ChainedProperty<S>) cCanonical.put(new ChainedProperty<S>(prime, chain));
    }

    /**
     * Parses a chained property.
     *
     * @param info Info for Storable type containing property
     * @param str string to parse
     * @throws IllegalArgumentException if any parameter is null or string
     * format is incorrect
     */
    @SuppressWarnings("unchecked")
    public static <S extends Storable> ChainedProperty<S> parse(StorableInfo<S> info, String str)
        throws IllegalArgumentException
    {
        if (info == null || str == null) {
            throw new IllegalArgumentException();
        }

        int pos = 0;
        int dot = str.indexOf('.', pos);

        String name;
        if (dot < 0) {
            name = str;
        } else {
            name = str.substring(pos, dot);
            pos = dot + 1;
        }

        StorableProperty<S> prime = info.getAllProperties().get(name);

        if (prime == null) {
            throw new IllegalArgumentException
                ("Property \"" + name + "\" not found for type: \"" +
                 info.getStorableType().getName() + '"');
        }

        if (pos <= 0) {
            return get(prime);
        }

        List<StorableProperty<?>> chain = new ArrayList<StorableProperty<?>>(4);
        Class<?> type = prime.isJoin() ? prime.getJoinedType() : prime.getType();

        while (pos > 0) {
            dot = str.indexOf('.', pos);
            if (dot < 0) {
                name = str.substring(pos);
                pos = -1;
            } else {
                name = str.substring(pos, dot);
                pos = dot + 1;
            }
            if (Storable.class.isAssignableFrom(type)) {
                StorableInfo propInfo =
                    StorableIntrospector.examine((Class<? extends Storable>) type);
                Map<String, ? extends StorableProperty<?>> props = propInfo.getAllProperties();
                StorableProperty<?> prop = props.get(name);
                if (prop == null) {
                    throw new IllegalArgumentException
                        ("Property \"" + name + "\" not found for type: \"" +
                         type.getName() + '"');
                }
                chain.add(prop);
                type = prop.isJoin() ? prop.getJoinedType() : prop.getType();
            } else {
                throw new IllegalArgumentException
                    ("Property \"" + name + "\" not found for type \"" +
                     type.getName() + "\" because type has no properties");
            }
        }

        return get(prime,
                   (StorableProperty<?>[]) chain.toArray(new StorableProperty[chain.size()]));
    }

    private final StorableProperty<S> mPrime;
    private final StorableProperty<?>[] mChain;

    /**
     * @param prime must not be null
     * @param chain can be null if none
     * @throws IllegalArgumentException if prime is null
     */
    private ChainedProperty(StorableProperty<S> prime, StorableProperty<?>[] chain) {
        if (prime == null) {
            throw new IllegalArgumentException();
        }
        mPrime = prime;
        mChain = (chain == null || chain.length == 0) ? null : chain.clone();
    }

    public StorableProperty<S> getPrimeProperty() {
        return mPrime;
    }

    /**
     * Returns the type of the last property in the chain, or of the prime
     * property if the chain is empty.
     */
    public Class<?> getType() {
        return getLastProperty().getType();
    }

    /**
     * Returns true if any property in the chain can be null.
     *
     * @see com.amazon.carbonado.Nullable
     */
    public boolean isNullable() {
        if (mPrime.isNullable()) {
            return true;
        }
        if (mChain != null) {
            for (StorableProperty<?> prop : mChain) {
                if (prop.isNullable()) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Returns the last property in the chain, or the prime property if chain
     * is empty.
     */
    public StorableProperty<?> getLastProperty() {
        return mChain == null ? mPrime : mChain[mChain.length - 1];
    }

    /**
     * Returns amount of properties chained from prime property, which may be
     * zero.
     */
    public int getChainCount() {
        return mChain == null ? 0 : mChain.length;
    }

    public StorableProperty<?> getChainedProperty(int index) throws IndexOutOfBoundsException {
        if (mChain == null) {
            throw new IndexOutOfBoundsException();
        } else {
            return mChain[index];
        }
    }

    /**
     * Returns a new ChainedProperty with another property appended.
     */
    public ChainedProperty<S> append(StorableProperty<?> property) {
        StorableProperty<?>[] newChain = new StorableProperty[getChainCount() + 1];
        if (newChain.length > 1) {
            System.arraycopy(mChain, 0, newChain, 0, mChain.length);
        }
        newChain[newChain.length - 1] = property;
        return get(mPrime, newChain);
    }

    /**
     * Returns a new ChainedProperty with another property appended.
     */
    public ChainedProperty<S> append(ChainedProperty<?> property) {
        final int propChainCount = property.getChainCount();
        if (propChainCount == 0) {
            return append(property.getPrimeProperty());
        }

        StorableProperty<?>[] newChain =
            new StorableProperty[getChainCount() + 1 + propChainCount];

        int pos = 0;
        if (getChainCount() > 0) {
            System.arraycopy(mChain, 0, newChain, 0, mChain.length);
            pos = mChain.length;
        }

        newChain[pos++] = property.getPrimeProperty();
        for (int i=0; i<propChainCount; i++) {
            newChain[pos++] = property.getChainedProperty(i);
        }

        return get(mPrime, newChain);
    }

    /**
     * Returns a new ChainedProperty with the last property in the chain removed.
     *
     * @throws IllegalStateException if chain count is zero
     */
    public ChainedProperty<S> trim() {
        if (getChainCount() == 0) {
            throw new IllegalStateException();
        }
        if (getChainCount() == 1) {
            return get(mPrime);
        }
        StorableProperty<?>[] newChain = new StorableProperty[getChainCount() - 1];
        System.arraycopy(mChain, 0, newChain, 0, newChain.length);
        return get(mPrime, newChain);
    }

    /**
     * Returns a new ChainedProperty which contains everything that follows
     * this ChainedProperty's prime property.
     *
     * @throws IllegalStateException if chain count is zero
     */
    public ChainedProperty<?> tail() {
        if (getChainCount() == 0) {
            throw new IllegalStateException();
        }
        if (getChainCount() == 1) {
            return get(mChain[0]);
        }
        StorableProperty<?>[] newChain = new StorableProperty[getChainCount() - 1];
        System.arraycopy(mChain, 1, newChain, 0, newChain.length);
        return get(mChain[0], newChain);
    }

    @Override
    public int hashCode() {
        int hash = mPrime.hashCode();
        StorableProperty<?>[] chain = mChain;
        if (chain != null) {
            for (int i=chain.length; --i>=0; ) {
                hash = hash * 31 + chain[i].hashCode();
            }
        }
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof ChainedProperty) {
            ChainedProperty<?> other = (ChainedProperty<?>) obj;
            if (getType() == other.getType() && mPrime.equals(other.mPrime)) {
                if (mChain == null) {
                    return other.mChain == null;
                }
                if (other.mChain != null) {
                    return Arrays.equals(mChain, other.mChain);
                }
            }
        }
        return false;
    }

    /**
     * Returns the chained property in a parseable form. The format is
     * "name.subname.subsubname".
     */
    @Override
    public String toString() {
        if (mChain == null) {
            return mPrime.getName();
        }
        StringBuilder buf = new StringBuilder();
        try {
            appendTo(buf);
        } catch (IOException e) {
            // Not gonna happen.
        }
        return buf.toString();
    }

    /**
     * Appends the chained property in a parseable form. The format is
     * "name.subname.subsubname".
     */
    public void appendTo(Appendable app) throws IOException {
        app.append(mPrime.getName());
        StorableProperty<?>[] chain = mChain;
        if (chain != null) {
            app.append('.');
            for (int i=0; i<chain.length; i++) {
                if (i > 0) {
                    app.append('.');
                }
                app.append(chain[i].getName());
            }
        }
    }
}