summaryrefslogtreecommitdiffstats
path: root/das-java/branches/das-java-beta2/rdb/src/main/java/org/apache/tuscany/das/rdb/impl/ChangeSummarizer.java
blob: 9858e4c9724e0c7a66f915d6d0ba34d2fd65825d (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
/*
 * 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.tuscany.das.rdb.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.tuscany.das.rdb.Command;
import org.apache.tuscany.das.rdb.config.Column;
import org.apache.tuscany.das.rdb.config.Relationship;
import org.apache.tuscany.das.rdb.config.Table;
import org.apache.tuscany.das.rdb.config.wrapper.MappingWrapper;
import org.apache.tuscany.das.rdb.config.wrapper.RelationshipWrapper;
import org.apache.tuscany.das.rdb.config.wrapper.TableWrapper;
import org.apache.tuscany.das.rdb.util.CollectionsUtil;
import org.apache.tuscany.sdo.impl.ChangeSummaryImpl;

import commonj.sdo.ChangeSummary;
import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.Type;

public class ChangeSummarizer {

    private final Logger logger = Logger.getLogger(ChangeSummarizer.class);

    private Changes changes = new Changes();

    private FactoryRegistry registry;

    private MappingWrapper mapping = new MappingWrapper();

    private ConnectionImpl connection;

    private Map generatedKeys = new HashMap();

    public ChangeSummarizer() {
        // Empty Constructor
    }

    public Changes loadChanges(DataObject root) {
        ChangeSummary changeSummary = root.getDataGraph().getChangeSummary();
        if (changeSummary.isLogging()) {
            ((ChangeSummaryImpl) changeSummary).summarize();
        }

        List changedObjects = changeSummary.getChangedDataObjects();

        if (this.logger.isDebugEnabled()) {
            this.logger.debug("List of changed objects contains " + changedObjects.size() + " object(s)");
        }

        changes.setInsertOrder(mapping.getInsertOrder());
        changes.setDeleteOrder(mapping.getDeleteOrder());

        Iterator i = changedObjects.iterator();
        while (i.hasNext()) {
            DataObject o = (DataObject) i.next();

            if (!(o.equals(root))) {
                createChange(changeSummary, o);
            }
        }

        return changes;
    }

    public void createChange(ChangeSummary changeSummary, DataObject changedObject) {

        if (changeSummary.isCreated(changedObject)) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Change is a create");
            }
            if (!changeSummary.isDeleted(changedObject)) {
                ChangeFactory factory = getRegistry().getFactory(changedObject.getType());
                String propagatedID = (String) generatedKeys.get(changedObject.getType().getName());
                changes.addInsert(factory.createInsertOperation(changedObject, propagatedID));
            }
        } else if (changeSummary.isDeleted(changedObject)) {
            ChangeFactory factory = getRegistry().getFactory(changedObject.getType());
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Change is a delete");
            }
            changes.addDelete(factory.createDeleteOperation(changedObject));
        } else {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Change is a modify");
            }
            List attrList = changeSummary.getOldValues(changedObject);
            if (hasAttributeChange(attrList)) {
                ChangeFactory factory = getRegistry().getFactory(changedObject.getType());
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Attribute Change for " + changedObject.getType().getName());
                }
                String propagatedID = (String) generatedKeys.get(changedObject.getType().getName());
                changes.addUpdate(factory.createUpdateOperation(changedObject, propagatedID));
            } else {
                List values = changeSummary.getOldValues(changedObject);
                Iterator i = values.iterator();
                while (i.hasNext()) {
                    ChangeSummary.Setting setting = (ChangeSummary.Setting) i.next();
                    if (!setting.getProperty().getType().isDataType()) {
                        if (this.logger.isDebugEnabled()) {
                            this.logger.debug("Reference change for " + changedObject.getType().getName());
                        }
                        Property ref = setting.getProperty();
                        if (this.logger.isDebugEnabled()) {
                            this.logger.debug(ref.getName());
                        }
                        if (hasState(ref, changedObject)) {
                            ChangeFactory factory = getRegistry().getFactory(changedObject.getType());
                            changes.addUpdate(factory.createUpdateOperation(changedObject));
                        }
                    }
                }
            }
        }

    }

    private boolean hasState(Property ref, DataObject changedObject) {
        if (ref.getOpposite().isMany()) {
            return true;
        } 

        MappingWrapper mw = this.mapping;
        if (mw.getConfig() == null) {
            mw = registry.getFactory(changedObject.getType()).getConfig();
        }
        if (mw.getConfig() == null) {
            return false;
        }

        Relationship rel = mw.getRelationshipByReference(ref);

        if (!rel.isMany()) {
            if (rel.isKeyRestricted()) {
                throw new RuntimeException("Can not modify a one to one relationship that is key restricted");
            }
            // This is a one-one relationship
            Table t = mapping.getTableByTypeName(changedObject.getType().getName());
            TableWrapper tw = new TableWrapper(t);
            RelationshipWrapper rw = new RelationshipWrapper(rel);
            if ((rel.getForeignKeyTable().equals(t.getTableName())) 
                    && (CollectionsUtil.disjoint(tw.getPrimaryKeyProperties(), rw.getForeignKeys()))) {
                return true;
            }

        }

        return false;
    }

    private boolean hasAttributeChange(List theChanges) {
        Iterator i = theChanges.iterator();
        while (i.hasNext()) {
            ChangeSummary.Setting setting = (ChangeSummary.Setting) i.next();
            if (setting.getProperty().getType().isDataType()) {
                return true;
            }
        }
        return false;
    }

    public void addCreateCommand(Type type, Command cmd) {
        ChangeFactory cf = getRegistry().getFactory(type);
        cf.setCreateCommand((InsertCommandImpl) cmd);
        ((CommandImpl) cmd).setConnection(connection);
    }

    public void addUpdateCommand(Type type, Command cmd) {
        ChangeFactory cf = getRegistry().getFactory(type);
        cf.setUpdateCommand((UpdateCommandImpl) cmd);
        ((CommandImpl) cmd).setConnection(connection);
    }

    public void addDeleteCommand(Type type, Command cmd) {
        ChangeFactory cf = getRegistry().getFactory(type);
        cf.setDeleteCommand((DeleteCommandImpl) cmd);
        ((CommandImpl) cmd).setConnection(connection);

    }

    private FactoryRegistry getRegistry() {
        if (this.registry == null) {
            this.registry = new FactoryRegistry(mapping, connection);
        }
        return this.registry;
    }

    public void setConnection(ConnectionImpl connection) {
        this.connection = connection;
    }

    public void setMapping(MappingWrapper map) {
        this.mapping = map;

        if (mapping.getConfig() == null) {
            return;
        }

        Iterator i = mapping.getConfig().getTable().iterator();
        while (i.hasNext()) {
            Table t = (Table) i.next();
            Iterator columns = t.getColumn().iterator();
            while (columns.hasNext()) {
                Column c = (Column) columns.next();
                if (c.isPrimaryKey() && c.isGenerated()) {
                    if (this.logger.isDebugEnabled()) {
                        this.logger.debug("adding generated key " + t.getTableName() + "." + c.getColumnName());
                    }

                    generatedKeys.put(t.getTableName(), c.getColumnName());
                }
            }
        }
    }

    public ConnectionImpl getConnection() {
        return this.connection;
    }
}