summaryrefslogtreecommitdiff
path: root/qpid/java/broker/src/main/java/org/apache/qpid/server/configuration/store/MemoryConfigurationEntryStore.java
blob: 5944adaa99f7161bc02369284dd6bac5ffd55f2b (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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.qpid.server.configuration.store;

import static org.apache.qpid.server.configuration.ConfigurationEntry.ATTRIBUTE_NAME;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;

import org.apache.qpid.server.configuration.ConfigurationEntry;
import org.apache.qpid.server.configuration.ConfigurationEntryStore;
import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.model.Broker;
import org.apache.qpid.server.model.ConfiguredObject;
import org.apache.qpid.server.model.Model;
import org.apache.qpid.server.model.UUIDGenerator;
import org.apache.qpid.util.Strings;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.node.ArrayNode;

public class MemoryConfigurationEntryStore implements ConfigurationEntryStore
{
    public static final String STORE_TYPE = "memory";

    private static final String DEFAULT_BROKER_NAME = "Broker";
    private static final String ID = "id";
    private static final String TYPE = "@type";

    private static final int STORE_VERSION = 1;

    private final ObjectMapper _objectMapper;
    private final Map<UUID, ConfigurationEntry> _entries;
    private final Map<String, Class<? extends ConfiguredObject>> _relationshipClasses;

    private String _storeLocation;
    private UUID _rootId;

    protected MemoryConfigurationEntryStore()
    {
        _objectMapper = new ObjectMapper();
        _objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        _objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        _entries = new HashMap<UUID, ConfigurationEntry>();
        _relationshipClasses = buildRelationshipClassMap();
    }

    MemoryConfigurationEntryStore(String json)
    {
        this();
        if (json == null || "".equals(json))
        {
            createRootEntry();
        }
        else
        {
            loadFromJson(json);
        }
    }

    public MemoryConfigurationEntryStore(String initialStoreLocation, ConfigurationEntryStore initialStore)
    {
        this();
        if (initialStore == null && (initialStoreLocation == null || "".equals(initialStoreLocation) ))
        {
            throw new IllegalConfigurationException("Cannot instantiate the memory broker store as neither initial store nor initial store location is provided");
        }

        if (initialStore != null)
        {
            if (initialStore instanceof MemoryConfigurationEntryStore)
            {
                _storeLocation = initialStore.getStoreLocation();
            }
            _rootId = initialStore.getRootEntry().getId();
            copyEntry(_rootId, initialStore, _entries);
        }
        else
        {
            _storeLocation = initialStoreLocation;
            load(toURL(_storeLocation));
        }
    }

    @Override
    public synchronized UUID[] remove(UUID... entryIds)
    {
        List<UUID> removedIds = new ArrayList<UUID>();
        for (UUID uuid : entryIds)
        {
            if (_rootId.equals(uuid))
            {
                throw new IllegalConfigurationException("Cannot remove root entry");
            }
        }
        for (UUID uuid : entryIds)
        {
            if (removeInternal(uuid))
            {
                // remove references to the entry from parent entries
                for (ConfigurationEntry entry : _entries.values())
                {
                    if (entry.hasChild(uuid))
                    {
                        Set<UUID> children = new HashSet<UUID>(entry.getChildrenIds());
                        children.remove(uuid);
                        ConfigurationEntry referal = new ConfigurationEntry(entry.getId(), entry.getType(),
                                entry.getAttributes(), children, this);
                        _entries.put(entry.getId(), referal);
                    }
                }
                removedIds.add(uuid);
            }
        }

        return removedIds.toArray(new UUID[removedIds.size()]);
    }

    @Override
    public synchronized void save(ConfigurationEntry... entries)
    {
        replaceEntries(entries);
    }

    @Override
    public ConfigurationEntry getRootEntry()
    {
        return getEntry(_rootId);
    }

    @Override
    public synchronized ConfigurationEntry getEntry(UUID id)
    {
        return _entries.get(id);
    }

    @Override
    public void copyTo(String copyLocation)
    {
        File file = new File(copyLocation);
        if (!file.exists())
        {
            createFileIfNotExist(file);
        }
        saveAsTree(file);
    }

    @Override
    public String getStoreLocation()
    {
        return _storeLocation;
    }

    @Override
    public int getVersion()
    {
        return STORE_VERSION;
    }

    @Override
    public String getType()
    {
        return STORE_TYPE;
    }

    @Override
    public String toString()
    {
        return "MemoryConfigurationEntryStore [_rootId=" + _rootId + "]";
    }

    protected boolean replaceEntries(ConfigurationEntry... entries)
    {
        boolean anySaved = false;
        for (ConfigurationEntry entry : entries)
        {
            ConfigurationEntry oldEntry = _entries.put(entry.getId(), entry);
            if (!entry.equals(oldEntry))
            {
                anySaved = true;
            }
        }
        return anySaved;
    }

    protected ObjectMapper getObjectMapper()
    {
        return _objectMapper;
    }

    protected void saveAsTree(File file)
    {
        saveAsTree(_rootId, _entries, _objectMapper, file, STORE_VERSION);
    }

    protected void saveAsTree(UUID rootId, Map<UUID, ConfigurationEntry> entries, ObjectMapper mapper, File file, int version)
    {
        Map<String, Object> tree = toTree(rootId, entries);
        tree.put(Broker.STORE_VERSION, version);
        try
        {
            mapper.writeValue(file, tree);
        }
        catch (JsonGenerationException e)
        {
            throw new IllegalConfigurationException("Cannot generate json!", e);
        }
        catch (JsonMappingException e)
        {
            throw new IllegalConfigurationException("Cannot map objects for json serialization!", e);
        }
        catch (IOException e)
        {
            throw new IllegalConfigurationException("Cannot save configuration into " + file + "!", e);
        }
    }

    protected void load(URL url)
    {
        InputStream is = null;
        try
        {
            is = url.openStream();
            JsonNode node = loadJsonNodes(is, _objectMapper);
            ConfigurationEntry brokerEntry = toEntry(node, Broker.class, _entries);
            _rootId = brokerEntry.getId();
        }
        catch (IOException e)
        {
           throw new IllegalConfigurationException("Cannot load store from: " + url, e);
        }
        finally
        {
            if (is != null)
            {
                if (is != null)
                {
                    try
                    {
                        is.close();
                    }
                    catch (IOException e)
                    {
                        throw new IllegalConfigurationException("Cannot close input stream for: " + url, e);
                    }
                }
            }
        }
    }

    protected URL toURL(String location)
    {
        URL url = null;
        try
        {
            url = new URL(location);
        }
        catch (MalformedURLException e)
        {
            File locationFile = new File(location);
            url = fileToURL(locationFile);
        }
        return url;
    }

    protected void createFileIfNotExist(File file)
    {
        File parent = file.getParentFile();
        if (!parent.exists())
        {
            if (!parent.mkdirs())
            {
                throw new IllegalConfigurationException("Cannot create folders " + parent);
            }
        }
        try
        {
            file.createNewFile();
        }
        catch (IOException e)
        {
            throw new IllegalConfigurationException("Cannot create file " + file, e);
        }
    }

    protected void copyEntry(UUID entryId, ConfigurationEntryStore initialStore, Map<UUID,ConfigurationEntry> entries)
    {
        ConfigurationEntry entry = initialStore.getEntry(entryId);
        if (entry != null)
        {
            if (entries.containsKey(entryId))
            {
                throw new IllegalConfigurationException("Duplicate id is found: " + entryId
                        + "! The following configuration entries have the same id: " + entries.get(entryId) + ", " + entry);
            }

            Set<UUID> children = entry.getChildrenIds();
            Set<UUID> childrenCopy = children == null? null : new HashSet<UUID>(children);
            ConfigurationEntry copy = new ConfigurationEntry(entryId, entry.getType(), new HashMap<String, Object>(entry.getAttributes()), childrenCopy, this);
            entries.put(entryId, copy);
            if (children != null)
            {
                for (UUID uuid : children)
                {
                    copyEntry(uuid, initialStore, entries);
                }
            }
        }
    }

    protected URL fileToURL(File storeFile)
    {
        URL storeURL = null;
        try
        {
            storeURL = storeFile.toURI().toURL();
        }
        catch (MalformedURLException e)
        {
            throw new IllegalConfigurationException("Cannot create URL for file " + storeFile, e);
        }
        return storeURL;
    }

    private void loadFromJson(String json)
    {
        ByteArrayInputStream bais = null;
        try
        {
            byte[] bytes = json.getBytes("UTF-8");
            bais = new ByteArrayInputStream(bytes);
            JsonNode node = loadJsonNodes(bais, _objectMapper);
            ConfigurationEntry brokerEntry = toEntry(node, Broker.class, _entries);
            _rootId = brokerEntry.getId();
        }
        catch(Exception e)
        {
            throw new IllegalConfigurationException("Cannot create store from json:" + json);
        }
        finally
        {
            if (bais != null)
            {
                try
                {
                    bais.close();
                }
                catch (IOException e)
                {
                    // ByteArrayInputStream#close() is an empty method
                }
            }
        }
    }

    private void createRootEntry()
    {
        ConfigurationEntry brokerEntry = new ConfigurationEntry(UUIDGenerator.generateRandomUUID(),
                Broker.class.getSimpleName(), Collections.<String, Object> emptyMap(), Collections.<UUID> emptySet(), this);
        _rootId = brokerEntry.getId();
        _entries.put(_rootId, brokerEntry);
    }

    private Map<String, Object> toTree(UUID rootId, Map<UUID, ConfigurationEntry> entries)
    {
        ConfigurationEntry entry = entries.get(rootId);
        if (entry == null || !entry.getId().equals(rootId))
        {
            throw new IllegalConfigurationException("Cannot find entry with id " + rootId + "!");
        }
        Map<String, Object> tree = new TreeMap<String, Object>();
        Map<String, Object> attributes = entry.getAttributes();
        if (attributes != null)
        {
            tree.putAll(attributes);
        }
        tree.put(ID, entry.getId());
        Set<UUID> childrenIds = entry.getChildrenIds();
        if (childrenIds != null && !childrenIds.isEmpty())
        {
            for (UUID relationship : childrenIds)
            {
                ConfigurationEntry child = entries.get(relationship);
                if (child != null)
                {
                    String relationshipName = child.getType().toLowerCase() + "s";

                    @SuppressWarnings("unchecked")
                    Collection<Map<String, Object>> children = (Collection<Map<String, Object>>) tree.get(relationshipName);
                    if (children == null)
                    {
                        children = new ArrayList<Map<String, Object>>();
                        tree.put(relationshipName, children);
                    }
                    Map<String, Object> childAsMap = toTree(relationship, entries);
                    children.add(childAsMap);
                }
            }
        }
        return tree;
    }

    private Map<String, Class<? extends ConfiguredObject>> buildRelationshipClassMap()
    {
        Map<String, Class<? extends ConfiguredObject>> relationships = new HashMap<String, Class<? extends ConfiguredObject>>();

        Collection<Class<? extends ConfiguredObject>> children = Model.getInstance().getChildTypes(Broker.class);
        for (Class<? extends ConfiguredObject> childClass : children)
        {
            String name = childClass.getSimpleName().toLowerCase();
            String relationshipName = name + (name.endsWith("s") ? "es" : "s");
            relationships.put(relationshipName, childClass);
        }
        return relationships;
    }

    private boolean removeInternal(UUID entryId)
    {
        ConfigurationEntry oldEntry = _entries.remove(entryId);
        if (oldEntry != null)
        {
            Set<UUID> children = oldEntry.getChildrenIds();
            if (children != null && !children.isEmpty())
            {
                for (UUID childId : children)
                {
                    removeInternal(childId);
                }
            }
            return true;
        }
        return false;
    }

    private JsonNode loadJsonNodes(InputStream is, ObjectMapper mapper)
    {
        JsonNode root = null;
        try
        {
            root = mapper.readTree(is);
        }
        catch (JsonProcessingException e)
        {
            throw new IllegalConfigurationException("Cannot parse json", e);
        }
        catch (IOException e)
        {
            throw new IllegalConfigurationException("Cannot read json", e);
        }
        return root;
    }

    private ConfigurationEntry toEntry(JsonNode parent, Class<? extends ConfiguredObject> expectedConfiguredObjectClass, Map<UUID, ConfigurationEntry> entries)
    {
        Map<String, Object> attributes = null;
        Set<UUID> childrenIds = new TreeSet<UUID>();
        Iterator<String> fieldNames = parent.getFieldNames();
        String type = null;
        String idAsString = null;
        while (fieldNames.hasNext())
        {
            String fieldName = fieldNames.next();
            JsonNode fieldNode = parent.get(fieldName);
            if (fieldName.equals(ID))
            {
                idAsString = fieldNode.asText();
            }
            else if (fieldName.equals(TYPE))
            {
                type = fieldNode.asText();
            }
            else if (fieldNode.isArray())
            {
                // array containing either broker children or attribute values
                Iterator<JsonNode> elements = fieldNode.getElements();
                List<Object> fieldValues = null;
                while (elements.hasNext())
                {
                    JsonNode element = elements.next();
                    if (element.isObject())
                    {
                        Class<? extends ConfiguredObject> expectedChildConfiguredObjectClass = _relationshipClasses.get(fieldName);
                        // assuming it is a child node
                        ConfigurationEntry entry = toEntry(element, expectedChildConfiguredObjectClass, entries);
                        childrenIds.add(entry.getId());
                    }
                    else
                    {
                        if (fieldValues == null)
                        {
                            fieldValues = new ArrayList<Object>();
                        }
                        fieldValues.add(toObject(element));
                    }
                }
                if (fieldValues != null)
                {
                    Object[] array = fieldValues.toArray(new Object[fieldValues.size()]);
                    attributes.put(fieldName, array);
                }
            }
            else if (fieldNode.isObject())
            {
                // ignore, in-line objects are not supported yet
            }
            else
            {
                // primitive attribute
                Object value = toObject(fieldNode);
                if (attributes == null)
                {
                    attributes = new HashMap<String, Object>();
                }
                attributes.put(fieldName, value);
            }
        }

        if (type == null)
        {
            if (expectedConfiguredObjectClass == null)
            {
                throw new IllegalConfigurationException("Type attribute is not provided for configuration entry " + parent);
            }
            else
            {
                type = expectedConfiguredObjectClass.getSimpleName();
            }
        }
        String name = null;
        if (attributes != null)
        {
            name = (String) attributes.get(ATTRIBUTE_NAME);
        }
        if ((name == null || "".equals(name)))
        {
            if (expectedConfiguredObjectClass == Broker.class)
            {
                name = DEFAULT_BROKER_NAME;
            }
            else
            {
                throw new IllegalConfigurationException("Name attribute is not provided for configuration entry " + parent);
            }
        }
        UUID id = null;
        if (idAsString == null)
        {
            if (expectedConfiguredObjectClass == Broker.class)
            {
                id = UUIDGenerator.generateRandomUUID();
            }
            else
            {
                id = UUIDGenerator.generateBrokerChildUUID(type, name);
            }
        }
        else
        {
            try
            {
                id = UUID.fromString(idAsString);
            }
            catch (Exception e)
            {
                throw new IllegalConfigurationException(
                        "ID attribute value does not conform to UUID format for configuration entry " + parent);
            }
        }
        ConfigurationEntry entry = new ConfigurationEntry(id, type, attributes, childrenIds, this);
        if (entries.containsKey(id))
        {
            throw new IllegalConfigurationException("Duplicate id is found: " + id
                    + "! The following configuration entries have the same id: " + entries.get(id) + ", " + entry);
        }
        entries.put(id, entry);
        return entry;
    }

    private Object toObject(JsonNode node)
    {
        if (node.isValueNode())
        {
            if (node.isBoolean())
            {
                return node.asBoolean();
            }
            else if (node.isDouble())
            {
                return node.asDouble();
            }
            else if (node.isInt())
            {
                return node.asInt();
            }
            else if (node.isLong())
            {
                return node.asLong();
            }
            else if (node.isNull())
            {
                return null;
            }
            else
            {
                return Strings.expand(node.asText());
            }
        }
        else if (node.isArray())
        {
            return toArray(node);
        }
        else if (node.isObject())
        {
            return toMap(node);
        }
        else
        {
            throw new IllegalConfigurationException("Unexpected node: " + node);
        }
    }

    private Map<String, Object> toMap(JsonNode node)
    {
        Map<String, Object> object = new TreeMap<String, Object>();
        Iterator<String> fieldNames = node.getFieldNames();
        while (fieldNames.hasNext())
        {
            String name = fieldNames.next();
            Object value = toObject(node.get(name));
            object.put(name, value);
        }
        return object;
    }

    private Object toArray(JsonNode node)
    {
        ArrayNode arrayNode = (ArrayNode) node;
        Object[] array = new Object[arrayNode.size()];
        Iterator<JsonNode> elements = arrayNode.getElements();
        for (int i = 0; i < array.length; i++)
        {
            array[i] = toObject(elements.next());
        }
        return array;
    }

}