File: ObjectGraphBuilder.java

package info (click to toggle)
eclipselink 2.6.9-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 44,528 kB
  • sloc: java: 475,126; xml: 72; makefile: 21; sh: 10
file content (216 lines) | stat: -rw-r--r-- 8,881 bytes parent folder | download | duplicates (2)
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
/*******************************************************************************
 * Copyright (c) 2014, 2015 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
 * which accompanies this distribution.
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *      Dmitry Kornilov - Initial implementation
 ******************************************************************************/
package org.eclipse.persistence.jpa.rs.util;

import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.internal.weaving.PersistenceWeavedRest;
import org.eclipse.persistence.jaxb.ObjectGraph;
import org.eclipse.persistence.jaxb.Subgraph;
import org.eclipse.persistence.jpa.rs.PersistenceContext;
import org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilter;
import org.eclipse.persistence.jpa.rs.features.fieldsfiltering.FieldsFilterType;
import org.eclipse.persistence.jpa.rs.util.list.PageableCollection;
import org.eclipse.persistence.jpa.rs.util.list.ReadAllQueryResultCollection;
import org.eclipse.persistence.jpa.rs.util.list.ReportQueryResultCollection;
import org.eclipse.persistence.jpa.rs.util.list.SingleResultQueryResult;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.ForeignReferenceMapping;

import javax.xml.bind.JAXBElement;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Builds object graph for JPARS 2.0. Object graph defines the structure of the returned data. It hides some
 * fields which are not suppose to be returned to the client.
 *
 * @author Dmitry Kornilov
 * @since EclipseLink 2.6.0
 */
public class ObjectGraphBuilder {
    private final PersistenceContext context;
    private final List<String> RESERVED_WORDS = Arrays.asList("hasMore", "limit", "offset", "links", "count", "items", "_persistence_links");

    /**
     * Creates an object graph builder.
     *
     * @param context the persistence context
     */
    public ObjectGraphBuilder(PersistenceContext context) {
        this.context = context;
    }

    /**
     * Builds object graph for specified object using given filter.
     *
     * @param object the object to build object graph for. Mandatory.
     * @param filter the filter (included or excluded fields) to use. Optional.
     * @return constructed object graph.
     */
    public ObjectGraph createObjectGraph(Object object, FieldsFilter filter) {
        final Node root = new Node();

        if (PersistenceWeavedRest.class.isAssignableFrom(object.getClass())) {
            createNodeForEntity(object, root);
        } else if (object instanceof SingleResultQueryResult) {
            root.addAttributeNode("links");

            final SingleResultQueryResult singleResultQueryResult = (SingleResultQueryResult)object;
            processFieldsList(root.addSubNode("fields"), singleResultQueryResult.getFields());
        } else if (object instanceof ReadAllQueryResultCollection) {
            createNodeForPageableCollection((PageableCollection) object, root);
        } else {
            return null;
        }

        ObjectGraph objectGraph = context.getJAXBContext().createObjectGraph(object.getClass());
        fillObjectGraphFromNode(objectGraph, root, filter);

        return objectGraph;
    }

    private void createNodeForPageableCollection(PageableCollection collection, Node node) {
        node.addAttributeNode("hasMore");
        node.addAttributeNode("count");
        node.addAttributeNode("offset");
        node.addAttributeNode("limit");
        node.addAttributeNode("links");
        if (collection.getItems() != null && !collection.getItems().isEmpty()) {
            final Node subNode = node.addSubNode("items");
            if (collection instanceof ReportQueryResultCollection) {
                final ReportQueryResultCollection reportQueryResultCollection = (ReportQueryResultCollection)collection;
                processFieldsList(subNode.addSubNode("fields"), reportQueryResultCollection.getItems().get(0).getFields());
            } else {
                createNodeForEntity(collection.getItems().get(0), subNode);
            }
        }
    }

    private void processFieldsList(Node fieldsNode, List<JAXBElement> elements) {
        for (JAXBElement field : elements) {
            if (field.getValue() instanceof PersistenceWeavedRest) {
                final Node subNode = fieldsNode.addSubNode(field.getName().toString());
                subNode.addAttributeNode("_persistence_links");
            } else {
                fieldsNode.addAttributeNode(field.getName().toString());
            }
        }
    }

    private void createNodeForEntity(final Object object, final Node node) {
        final ClassDescriptor classDescriptor = context.getServerSession().getProject().getDescriptors().get(object.getClass());
        if (classDescriptor == null) {
            return;
        }
        node.addAttributeNode("_persistence_links");

        for (final DatabaseMapping mapping : classDescriptor.getMappings()) {
            if (ForeignReferenceMapping.class.isAssignableFrom(mapping.getClass())) {
                final Node subNode = node.addSubNode(mapping.getAttributeName());
                if (mapping.isCollectionMapping()) {
                    // Add CollectionWrapper links and items properties
                    subNode.addAttributeNode("links");
                    final Node itemsSubNode = subNode.addSubNode("items");
                    itemsSubNode.addAttributeNode("_persistence_links");
                } else {
                    // PersistenceWeavedRest._persistence_links
                    subNode.addAttributeNode("_persistence_links");
                }
            } else {
                node.addAttributeNode(mapping.getAttributeName());
            }
        }
    }

    private void fillObjectGraphFromNode(ObjectGraph objectGraph, Node node, FieldsFilter filter) {
        for (final String attribute : node.getNodesMap().keySet()) {
            if (filter != null) {
                if (filter.getType() == FieldsFilterType.INCLUDE) {
                    if (!(RESERVED_WORDS.contains(attribute) || filter.getFields().contains(attribute))) {
                        continue;
                    }
                } else {
                    if (filter.getFields().contains(attribute)) {
                        continue;
                    }
                }
            }

            final Node value = node.get(attribute);
            if (value != null) {
                final Subgraph subgraph = objectGraph.addSubgraph(attribute);
                fillSubgraphFromNode(subgraph, value, filter);
            } else {
                objectGraph.addAttributeNodes(attribute);
            }
        }
    }

    private void fillSubgraphFromNode(Subgraph subgraph, Node node, FieldsFilter filter) {
        for (final String attribute : node.getNodesMap().keySet()) {
            final Node value = node.get(attribute);
            if (filter != null) {
                if (filter.getType() == FieldsFilterType.INCLUDE) {
                    if (!(RESERVED_WORDS.contains(attribute) || filter.getFields().contains(attribute))) {
                        continue;
                    }
                } else {
                    if (filter.getFields().contains(attribute)) {
                        continue;
                    }
                }
            }

            if (value != null) {
                final Subgraph childSubgraph = subgraph.addSubgraph(attribute);
                fillSubgraphFromNode(childSubgraph, value, filter);
            } else {
                subgraph.addAttributeNodes(attribute);
            }
        }
    }

    /**
     * Internal object graph node.
     */
    private static class Node {
        private final Map<String, Node> nodesMap = new HashMap<String, Node>();

        public void addAttributeNode(final String attribute) {
            nodesMap.put(attribute, null);
        }

        public Node addSubNode(final String attribute) {
            final Node subNode = new Node();
            nodesMap.put(attribute, subNode);
            return subNode;
        }

        public Map<String, Node> getNodesMap() {
            return nodesMap;
        }

        public Node get(final String key) {
            return nodesMap.get(key);
        }

        @Override
        public String toString() {
            return "Node{" +
                    "nodesMap=" + nodesMap +
                    '}';
        }
    }
}