Source Code Cross Referenced for CmpJpaConversion.java in  » J2EE » openejb3 » org » apache » openejb » config » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » J2EE » openejb3 » org.apache.openejb.config 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /**
002:         * Licensed to the Apache Software Foundation (ASF) under one or more
003:         * contributor license agreements.  See the NOTICE file distributed with
004:         * this work for additional information regarding copyright ownership.
005:         * The ASF licenses this file to You under the Apache License, Version 2.0
006:         * (the "License"); you may not use this file except in compliance with
007:         * the License.  You may obtain a copy of the License at
008:         *
009:         *     http://www.apache.org/licenses/LICENSE-2.0
010:         *
011:         *  Unless required by applicable law or agreed to in writing, software
012:         *  distributed under the License is distributed on an "AS IS" BASIS,
013:         *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014:         *  See the License for the specific language governing permissions and
015:         *  limitations under the License.
016:         */package org.apache.openejb.config;
017:
018:        import org.apache.openejb.OpenEJBException;
019:        import org.apache.openejb.core.cmp.jpa.JpaCmpEngine;
020:        import org.apache.openejb.core.cmp.CmpUtil;
021:        import org.apache.openejb.jee.CmpField;
022:        import org.apache.openejb.jee.CmpVersion;
023:        import org.apache.openejb.jee.EjbJar;
024:        import org.apache.openejb.jee.EjbRelation;
025:        import org.apache.openejb.jee.EjbRelationshipRole;
026:        import org.apache.openejb.jee.EntityBean;
027:        import org.apache.openejb.jee.Multiplicity;
028:        import org.apache.openejb.jee.PersistenceContextRef;
029:        import org.apache.openejb.jee.PersistenceType;
030:        import org.apache.openejb.jee.RelationshipRoleSource;
031:        import org.apache.openejb.jee.Relationships;
032:        import org.apache.openejb.jee.Query;
033:        import org.apache.openejb.jee.QueryMethod;
034:        import org.apache.openejb.jee.EnterpriseBean;
035:        import org.apache.openejb.jee.oejb3.OpenejbJar;
036:        import org.apache.openejb.jee.oejb3.EjbDeployment;
037:        import org.apache.openejb.jee.jpa.Basic;
038:        import org.apache.openejb.jee.jpa.CascadeType;
039:        import org.apache.openejb.jee.jpa.Entity;
040:        import org.apache.openejb.jee.jpa.EntityMappings;
041:        import org.apache.openejb.jee.jpa.Id;
042:        import org.apache.openejb.jee.jpa.ManyToMany;
043:        import org.apache.openejb.jee.jpa.ManyToOne;
044:        import org.apache.openejb.jee.jpa.OneToMany;
045:        import org.apache.openejb.jee.jpa.OneToOne;
046:        import org.apache.openejb.jee.jpa.RelationField;
047:        import org.apache.openejb.jee.jpa.Transient;
048:        import org.apache.openejb.jee.jpa.MappedSuperclass;
049:        import org.apache.openejb.jee.jpa.Mapping;
050:        import org.apache.openejb.jee.jpa.AttributeOverride;
051:        import org.apache.openejb.jee.jpa.Field;
052:        import org.apache.openejb.jee.jpa.NamedQuery;
053:        import org.apache.openejb.jee.jpa.IdClass;
054:        import org.apache.openejb.jee.jpa.GeneratedValue;
055:        import org.apache.openejb.jee.jpa.GenerationType;
056:        import org.apache.openejb.jee.jpa.unit.Persistence;
057:        import org.apache.openejb.jee.jpa.unit.PersistenceUnit;
058:        import org.apache.openejb.jee.jpa.unit.TransactionType;
059:        import org.apache.openejb.jee.jpa.unit.Properties;
060:
061:        import java.util.List;
062:        import java.util.Map;
063:        import java.util.Set;
064:        import java.util.TreeSet;
065:        import java.util.HashSet;
066:        import java.util.Collection;
067:        import java.util.Collections;
068:        import java.util.Arrays;
069:        import java.util.TreeMap;
070:        import java.lang.reflect.Modifier;
071:
072:        public class CmpJpaConversion implements  DynamicDeployer {
073:            private static final String CMP_PERSISTENCE_UNIT_NAME = "cmp";
074:
075:            private static final Set<String> ENHANCEED_FIELDS = Collections
076:                    .unmodifiableSet(new TreeSet<String>(
077:                            Arrays
078:                                    .asList(
079:                                            "pcInheritedFieldCount",
080:                                            "pcFieldNames",
081:                                            "pcFieldTypes",
082:                                            "pcFieldFlags",
083:                                            "pcPCSuperclass",
084:                                            "pcStateManager",
085:                                            "class$Ljava$lang$String",
086:                                            "class$Ljava$lang$Integer",
087:                                            "class$Lcom$sun$ts$tests$common$ejb$wrappers$CMP11Wrapper",
088:                                            "pcDetachedState",
089:                                            "serialVersionUID")));
090:
091:            public AppModule deploy(AppModule appModule)
092:                    throws OpenEJBException {
093:
094:                if (!hasCmpEntities(appModule))
095:                    return appModule;
096:
097:                // search for the cmp persistence unit
098:                PersistenceUnit persistenceUnit = null;
099:                for (PersistenceModule persistenceModule : appModule
100:                        .getPersistenceModules()) {
101:                    Persistence persistence = persistenceModule
102:                            .getPersistence();
103:                    for (PersistenceUnit unit : persistence
104:                            .getPersistenceUnit()) {
105:                        if (CMP_PERSISTENCE_UNIT_NAME.equals(unit.getName())) {
106:                            persistenceUnit = unit;
107:                            break;
108:                        }
109:
110:                    }
111:                }
112:
113:                // todo scan existing persistence module for all entity mappings and don't generate mappings for them
114:
115:                // create mappings
116:                EntityMappings cmpMappings = appModule.getCmpMappings();
117:                if (cmpMappings == null) {
118:                    cmpMappings = new EntityMappings();
119:                    cmpMappings.setVersion("1.0");
120:                    appModule.setCmpMappings(cmpMappings);
121:                }
122:
123:                for (EjbModule ejbModule : appModule.getEjbModules()) {
124:                    generateEntityMappings(ejbModule, cmpMappings);
125:                }
126:
127:                if (!cmpMappings.getEntity().isEmpty()) {
128:                    // if not found create one
129:                    if (persistenceUnit == null) {
130:                        persistenceUnit = new PersistenceUnit();
131:                        persistenceUnit.setName(CMP_PERSISTENCE_UNIT_NAME);
132:                        persistenceUnit.setTransactionType(TransactionType.JTA);
133:                        persistenceUnit
134:                                .setJtaDataSource("java:openejb/Resource/Default JDBC Database");
135:                        persistenceUnit
136:                                .setNonJtaDataSource("java:openejb/Resource/Default Unmanaged JDBC Database");
137:                        // todo paramterize this
138:                        Properties properties = new Properties();
139:                        properties
140:                                .setProperty(
141:                                        "openjpa.jdbc.SynchronizeMappings",
142:                                        "buildSchema(ForeignKeys=true, Indexes=false, IgnoreErrors=true)");
143:                        // properties.setProperty("openjpa.DataCache", "false");
144:                        // properties.setProperty("openjpa.Log", "DefaultLevel=TRACE");
145:                        persistenceUnit.setProperties(properties);
146:
147:                        Persistence persistence = new Persistence();
148:                        persistence.setVersion("1.0");
149:                        persistence.getPersistenceUnit().add(persistenceUnit);
150:
151:                        PersistenceModule persistenceModule = new PersistenceModule(
152:                                appModule.getModuleId(), persistence);
153:                        appModule.getPersistenceModules()
154:                                .add(persistenceModule);
155:                    }
156:                    persistenceUnit.getMappingFile().add(
157:                            "META-INF/openejb-cmp-generated-orm.xml");
158:                    for (Entity entity : cmpMappings.getEntity()) {
159:                        persistenceUnit.getClazz().add(entity.getClazz());
160:                    }
161:                }
162:
163:                return appModule;
164:            }
165:
166:            private boolean hasCmpEntities(AppModule appModule) {
167:                for (EjbModule ejbModule : appModule.getEjbModules()) {
168:                    for (EnterpriseBean bean : ejbModule.getEjbJar()
169:                            .getEnterpriseBeans()) {
170:                        if (bean instanceof  EntityBean) {
171:                            EntityBean entityBean = (EntityBean) bean;
172:                            if (entityBean.getPersistenceType() == PersistenceType.CONTAINER)
173:                                return true;
174:                        }
175:                    }
176:                }
177:                return false;
178:            }
179:
180:            public EntityMappings generateEntityMappings(EjbModule ejbModule)
181:                    throws OpenEJBException {
182:                AppModule appModule = new AppModule(ejbModule.getClassLoader(),
183:                        ejbModule.getJarLocation());
184:                appModule.getEjbModules().add(ejbModule);
185:
186:                EntityMappings entityMappings = new EntityMappings();
187:                generateEntityMappings(ejbModule, entityMappings);
188:                return entityMappings;
189:            }
190:
191:            public void generateEntityMappings(EjbModule ejbModule,
192:                    EntityMappings entityMappings) throws OpenEJBException {
193:                EjbJar ejbJar = ejbModule.getEjbJar();
194:                OpenejbJar openejbJar = ejbModule.getOpenejbJar();
195:                ClassLoader classLoader = ejbModule.getClassLoader();
196:
197:                Map<String, MappedSuperclass> mappedSuperclassByClass = new TreeMap<String, MappedSuperclass>();
198:                for (MappedSuperclass mappedSuperclass : entityMappings
199:                        .getMappedSuperclass()) {
200:                    mappedSuperclassByClass.put(mappedSuperclass.getClazz(),
201:                            mappedSuperclass);
202:                }
203:
204:                Map<String, Entity> entitiesByName = new TreeMap<String, Entity>();
205:                for (Entity entity : entityMappings.getEntity()) {
206:                    entitiesByName.put(entity.getName(), entity);
207:                }
208:
209:                for (org.apache.openejb.jee.EnterpriseBean enterpriseBean : ejbJar
210:                        .getEnterpriseBeans()) {
211:                    // skip all non-CMP beans
212:                    if (!(enterpriseBean instanceof  EntityBean)
213:                            || ((EntityBean) enterpriseBean)
214:                                    .getPersistenceType() != PersistenceType.CONTAINER) {
215:                        continue;
216:                    }
217:                    EntityBean bean = (EntityBean) enterpriseBean;
218:
219:                    // Always set the abstract schema name
220:                    if (bean.getAbstractSchemaName() == null) {
221:                        String abstractSchemaName = bean.getEjbName().trim()
222:                                .replaceAll("[ \\t\\n\\r-]+", "_");
223:                        if (entitiesByName.containsKey(abstractSchemaName)) {
224:                            int i = 2;
225:                            while (entitiesByName
226:                                    .containsKey(abstractSchemaName + i)) {
227:                                i++;
228:                            }
229:                            abstractSchemaName = abstractSchemaName + i;
230:                        }
231:                        bean.setAbstractSchemaName(abstractSchemaName);
232:                    }
233:
234:                    // try to add a new persistence-context-ref for cmp
235:                    if (!addPersistenceContextRef(bean)) {
236:                        // Bean already has a persistence-context-ref for cmp
237:                        // which means it has a mapping, so skip this bean
238:                        continue;
239:                    }
240:
241:                    Entity entity = new Entity();
242:
243:                    // description: contains the name of the entity bean
244:                    entity.setDescription(ejbModule.getModuleId() + "#"
245:                            + bean.getEjbName());
246:
247:                    // name: the name of the entity in queries
248:                    String entityName = bean.getAbstractSchemaName();
249:                    entity.setName(entityName);
250:
251:                    // class: impl class name
252:                    String cmpImplClassName = CmpUtil.getCmpImplClassName(bean
253:                            .getAbstractSchemaName(), bean.getEjbClass());
254:                    entity.setClazz(cmpImplClassName);
255:
256:                    // add the entity
257:                    entityMappings.getEntity().add(entity);
258:                    entitiesByName.put(bean.getEjbName(), entity);
259:
260:                    if (bean.getCmpVersion() == CmpVersion.CMP2) {
261:                        mapClass2x(entity, bean, classLoader);
262:                    } else {
263:                        // map the cmp class, but if we are using a mapped super class, generate attribute-override instead of id and basic
264:                        Collection<MappedSuperclass> mappedSuperclasses = mapClass1x(
265:                                bean.getEjbClass(), entity, bean, classLoader);
266:                        for (MappedSuperclass mappedSuperclass : mappedSuperclasses) {
267:                            mappedSuperclassByClass.put(mappedSuperclass
268:                                    .getClazz(), mappedSuperclass);
269:                        }
270:                    }
271:
272:                    // process queries
273:                    for (Query query : bean.getQuery()) {
274:                        NamedQuery namedQuery = new NamedQuery();
275:                        QueryMethod queryMethod = query.getQueryMethod();
276:
277:                        // todo deployment id could change in one of the later conversions... use entity name instead, but we need to save it off
278:                        StringBuilder name = new StringBuilder();
279:                        name.append(entityName).append(".").append(
280:                                queryMethod.getMethodName());
281:                        if (queryMethod.getMethodParams() != null
282:                                && !queryMethod.getMethodParams()
283:                                        .getMethodParam().isEmpty()) {
284:                            name.append('(');
285:                            boolean first = true;
286:                            for (String methodParam : queryMethod
287:                                    .getMethodParams().getMethodParam()) {
288:                                if (!first)
289:                                    name.append(",");
290:                                name.append(methodParam);
291:                                first = false;
292:                            }
293:                            name.append(')');
294:                        }
295:                        namedQuery.setName(name.toString());
296:
297:                        namedQuery.setQuery(query.getEjbQl());
298:                        entity.getNamedQuery().add(namedQuery);
299:                    }
300:                    // todo: there should be a common interface between ejb query object and openejb query object
301:                    EjbDeployment ejbDeployment = openejbJar
302:                            .getDeploymentsByEjbName().get(bean.getEjbName());
303:                    if (ejbDeployment != null) {
304:                        for (org.apache.openejb.jee.oejb3.Query query : ejbDeployment
305:                                .getQuery()) {
306:                            NamedQuery namedQuery = new NamedQuery();
307:                            org.apache.openejb.jee.oejb3.QueryMethod queryMethod = query
308:                                    .getQueryMethod();
309:
310:                            // todo deployment id could change in one of the later conversions... use entity name instead, but we need to save it off
311:                            StringBuilder name = new StringBuilder();
312:                            name.append(entityName).append(".").append(
313:                                    queryMethod.getMethodName());
314:                            if (queryMethod.getMethodParams() != null
315:                                    && !queryMethod.getMethodParams()
316:                                            .getMethodParam().isEmpty()) {
317:                                name.append('(');
318:                                boolean first = true;
319:                                for (String methodParam : queryMethod
320:                                        .getMethodParams().getMethodParam()) {
321:                                    if (!first)
322:                                        name.append(",");
323:                                    name.append(methodParam);
324:                                    first = false;
325:                                }
326:                                name.append(')');
327:                            }
328:                            namedQuery.setName(name.toString());
329:
330:                            namedQuery.setQuery(query.getObjectQl());
331:                            entity.getNamedQuery().add(namedQuery);
332:                        }
333:                    }
334:                }
335:                entityMappings.getMappedSuperclass().addAll(
336:                        mappedSuperclassByClass.values());
337:
338:                Relationships relationships = ejbJar.getRelationships();
339:                if (relationships != null) {
340:                    for (EjbRelation relation : relationships.getEjbRelation()) {
341:                        List<EjbRelationshipRole> roles = relation
342:                                .getEjbRelationshipRole();
343:                        // if we don't have two roles, the relation is bad so we skip it
344:                        if (roles.size() != 2) {
345:                            continue;
346:                        }
347:
348:                        // get left entity
349:                        EjbRelationshipRole leftRole = roles.get(0);
350:                        RelationshipRoleSource leftRoleSource = leftRole
351:                                .getRelationshipRoleSource();
352:                        String leftEjbName = leftRoleSource == null ? null
353:                                : leftRoleSource.getEjbName();
354:                        Entity leftEntity = entitiesByName.get(leftEjbName);
355:
356:                        // get right entity
357:                        EjbRelationshipRole rightRole = roles.get(1);
358:                        RelationshipRoleSource rightRoleSource = rightRole
359:                                .getRelationshipRoleSource();
360:                        String rightEjbName = rightRoleSource == null ? null
361:                                : rightRoleSource.getEjbName();
362:                        Entity rightEntity = entitiesByName.get(rightEjbName);
363:
364:                        // neither left or right have a mapping which is fine
365:                        if (leftEntity == null && rightEntity == null) {
366:                            continue;
367:                        }
368:                        // left not found?
369:                        if (leftEntity == null) {
370:                            throw new OpenEJBException("Role source "
371:                                    + leftEjbName
372:                                    + " defined in relationship role "
373:                                    + relation.getEjbRelationName() + "::"
374:                                    + leftRole.getEjbRelationshipRoleName()
375:                                    + " not found");
376:                        }
377:                        // right not found?
378:                        if (rightEntity == null) {
379:                            throw new OpenEJBException("Role source "
380:                                    + rightEjbName
381:                                    + " defined in relationship role "
382:                                    + relation.getEjbRelationName() + "::"
383:                                    + rightRole.getEjbRelationshipRoleName()
384:                                    + " not found");
385:                        }
386:
387:                        String leftFieldName = null;
388:                        boolean leftSynthetic = false;
389:                        if (leftRole.getCmrField() != null) {
390:                            leftFieldName = leftRole.getCmrField()
391:                                    .getCmrFieldName();
392:                        } else {
393:                            leftFieldName = rightEntity.getName() + "_"
394:                                    + rightRole.getCmrField().getCmrFieldName();
395:                            leftSynthetic = true;
396:                        }
397:                        boolean leftIsOne = leftRole.getMultiplicity() == Multiplicity.ONE;
398:
399:                        String rightFieldName = null;
400:                        boolean rightSynthetic = false;
401:                        if (rightRole.getCmrField() != null) {
402:                            rightFieldName = rightRole.getCmrField()
403:                                    .getCmrFieldName();
404:                        } else {
405:                            rightFieldName = leftEntity.getName() + "_"
406:                                    + leftRole.getCmrField().getCmrFieldName();
407:                            rightSynthetic = true;
408:                        }
409:                        boolean rightIsOne = rightRole.getMultiplicity() == Multiplicity.ONE;
410:
411:                        if (leftIsOne && rightIsOne) {
412:                            //
413:                            // one-to-one
414:                            //
415:
416:                            // left
417:                            OneToOne leftOneToOne = null;
418:                            leftOneToOne = new OneToOne();
419:                            leftOneToOne.setName(leftFieldName);
420:                            leftOneToOne.setSyntheticField(leftSynthetic);
421:                            setCascade(rightRole, leftOneToOne);
422:                            leftEntity.getAttributes().getOneToOne().add(
423:                                    leftOneToOne);
424:
425:                            // right
426:                            OneToOne rightOneToOne = null;
427:                            rightOneToOne = new OneToOne();
428:                            rightOneToOne.setName(rightFieldName);
429:                            rightOneToOne.setSyntheticField(rightSynthetic);
430:                            rightOneToOne.setMappedBy(leftFieldName);
431:                            setCascade(leftRole, rightOneToOne);
432:                            rightEntity.getAttributes().getOneToOne().add(
433:                                    rightOneToOne);
434:
435:                            // link
436:                            leftOneToOne.setRelatedField(rightOneToOne);
437:                            rightOneToOne.setRelatedField(leftOneToOne);
438:                        } else if (leftIsOne && !rightIsOne) {
439:                            //
440:                            // one-to-many
441:                            //
442:
443:                            // left
444:                            OneToMany leftOneToMany = null;
445:                            leftOneToMany = new OneToMany();
446:                            leftOneToMany.setName(leftFieldName);
447:                            leftOneToMany.setSyntheticField(leftSynthetic);
448:                            leftOneToMany.setMappedBy(rightFieldName);
449:                            setCascade(rightRole, leftOneToMany);
450:                            leftEntity.getAttributes().getOneToMany().add(
451:                                    leftOneToMany);
452:
453:                            // right
454:                            ManyToOne rightManyToOne = null;
455:                            rightManyToOne = new ManyToOne();
456:                            rightManyToOne.setName(rightFieldName);
457:                            rightManyToOne.setSyntheticField(rightSynthetic);
458:                            setCascade(leftRole, rightManyToOne);
459:                            rightEntity.getAttributes().getManyToOne().add(
460:                                    rightManyToOne);
461:
462:                            // link
463:                            leftOneToMany.setRelatedField(rightManyToOne);
464:                            rightManyToOne.setRelatedField(leftOneToMany);
465:                        } else if (!leftIsOne && rightIsOne) {
466:                            //
467:                            // many-to-one
468:                            //
469:
470:                            // left
471:                            ManyToOne leftManyToOne = null;
472:                            leftManyToOne = new ManyToOne();
473:                            leftManyToOne.setName(leftFieldName);
474:                            leftManyToOne.setSyntheticField(leftSynthetic);
475:                            setCascade(rightRole, leftManyToOne);
476:                            leftEntity.getAttributes().getManyToOne().add(
477:                                    leftManyToOne);
478:
479:                            // right
480:                            OneToMany rightOneToMany = null;
481:                            rightOneToMany = new OneToMany();
482:                            rightOneToMany.setName(rightFieldName);
483:                            rightOneToMany.setSyntheticField(rightSynthetic);
484:                            rightOneToMany.setMappedBy(leftFieldName);
485:                            setCascade(leftRole, rightOneToMany);
486:                            rightEntity.getAttributes().getOneToMany().add(
487:                                    rightOneToMany);
488:
489:                            // link
490:                            leftManyToOne.setRelatedField(rightOneToMany);
491:                            rightOneToMany.setRelatedField(leftManyToOne);
492:                        } else if (!leftIsOne && !rightIsOne) {
493:                            //
494:                            // many-to-many
495:                            //
496:
497:                            // left
498:                            ManyToMany leftManyToMany = null;
499:                            leftManyToMany = new ManyToMany();
500:                            leftManyToMany.setName(leftFieldName);
501:                            leftManyToMany.setSyntheticField(leftSynthetic);
502:                            setCascade(rightRole, leftManyToMany);
503:                            leftEntity.getAttributes().getManyToMany().add(
504:                                    leftManyToMany);
505:
506:                            // right
507:                            ManyToMany rightManyToMany = null;
508:                            rightManyToMany = new ManyToMany();
509:                            rightManyToMany.setName(rightFieldName);
510:                            rightManyToMany.setSyntheticField(rightSynthetic);
511:                            rightManyToMany.setMappedBy(leftFieldName);
512:                            setCascade(leftRole, rightManyToMany);
513:                            rightEntity.getAttributes().getManyToMany().add(
514:                                    rightManyToMany);
515:
516:                            // link
517:                            leftManyToMany.setRelatedField(rightManyToMany);
518:                            rightManyToMany.setRelatedField(leftManyToMany);
519:                        }
520:                    }
521:                }
522:            }
523:
524:            private void mapClass2x(Mapping mapping, EntityBean bean,
525:                    ClassLoader classLoader) {
526:                Set<String> allFields = new TreeSet<String>();
527:                for (CmpField cmpField : bean.getCmpField()) {
528:                    allFields.add(cmpField.getFieldName());
529:                }
530:
531:                //
532:                // id: the primary key
533:                //
534:                Set<String> primaryKeyFields = new HashSet<String>();
535:                if (bean.getPrimkeyField() != null) {
536:                    String fieldName = bean.getPrimkeyField();
537:                    Field field = new Id(fieldName);
538:                    mapping.addField(field);
539:                    primaryKeyFields.add(fieldName);
540:                } else if ("java.lang.Object".equals(bean.getPrimKeyClass())) {
541:                    String fieldName = "OpenEJB_pk";
542:                    Id field = new Id(fieldName);
543:                    field.setGeneratedValue(new GeneratedValue(
544:                            GenerationType.AUTO));
545:                    mapping.addField(field);
546:                    primaryKeyFields.add(fieldName);
547:                } else if (bean.getPrimKeyClass() != null) {
548:                    Class<?> pkClass = null;
549:                    try {
550:                        pkClass = classLoader.loadClass(bean.getPrimKeyClass());
551:                        mapping.setIdClass(new IdClass(bean.getPrimKeyClass()));
552:                        for (java.lang.reflect.Field pkField : pkClass
553:                                .getFields()) {
554:                            String pkFieldName = pkField.getName();
555:                            int modifiers = pkField.getModifiers();
556:                            if (Modifier.isPublic(modifiers)
557:                                    && !Modifier.isStatic(modifiers)
558:                                    && allFields.contains(pkFieldName)) {
559:                                Field field = new Id(pkFieldName);
560:                                mapping.addField(field);
561:                                primaryKeyFields.add(pkFieldName);
562:                            }
563:                        }
564:                    } catch (ClassNotFoundException e) {
565:                        // todo throw exception
566:                    }
567:                }
568:
569:                //
570:                // basic: cmp-fields
571:                //
572:                for (CmpField cmpField : bean.getCmpField()) {
573:                    if (!primaryKeyFields.contains(cmpField.getFieldName())) {
574:                        Field field = new Basic(cmpField.getFieldName());
575:                        mapping.addField(field);
576:                    }
577:                }
578:            }
579:
580:            private Collection<MappedSuperclass> mapClass1x(
581:                    String ejbClassName, Mapping mapping, EntityBean bean,
582:                    ClassLoader classLoader) {
583:                Class ejbClass = null;
584:                try {
585:                    ejbClass = classLoader.loadClass(ejbClassName);
586:                } catch (ClassNotFoundException e) {
587:                    throw new IllegalArgumentException(e);
588:                }
589:
590:                // build a set of all field names
591:                Set<String> allFields = new TreeSet<String>();
592:                for (CmpField cmpField : bean.getCmpField()) {
593:                    allFields.add(cmpField.getFieldName());
594:                }
595:
596:                // build a map from the field name to the super class that contains that field
597:                Map<String, MappedSuperclass> super classByField = mapFields(
598:                        ejbClass, allFields);
599:                //
600:                // id: the primary key
601:                //
602:                Set<String> primaryKeyFields = new HashSet<String>();
603:                if (bean.getPrimkeyField() != null) {
604:                    String fieldName = bean.getPrimkeyField();
605:                    MappedSuperclass super class = super classByField
606:                            .get(fieldName);
607:                    if (super class == null) {
608:                        throw new IllegalStateException("Primary key field "
609:                                + fieldName + " is not defined in class "
610:                                + ejbClassName + " or any super classes");
611:                    }
612:                    super class.addField(new Id(fieldName));
613:                    mapping.addField(new AttributeOverride(fieldName));
614:                    primaryKeyFields.add(fieldName);
615:                } else if ("java.lang.Object".equals(bean.getPrimKeyClass())) {
616:                    String fieldName = "OpenEJB_pk";
617:                    Id field = new Id(fieldName);
618:                    field.setGeneratedValue(new GeneratedValue(
619:                            GenerationType.AUTO));
620:                    mapping.addField(field);
621:                } else if (bean.getPrimKeyClass() != null) {
622:                    Class<?> pkClass = null;
623:                    try {
624:                        pkClass = classLoader.loadClass(bean.getPrimKeyClass());
625:                        MappedSuperclass super class = null;
626:                        for (java.lang.reflect.Field pkField : pkClass
627:                                .getFields()) {
628:                            String fieldName = pkField.getName();
629:                            int modifiers = pkField.getModifiers();
630:                            if (Modifier.isPublic(modifiers)
631:                                    && !Modifier.isStatic(modifiers)
632:                                    && allFields.contains(fieldName)) {
633:                                super class = super classByField.get(fieldName);
634:                                if (super class == null) {
635:                                    throw new IllegalStateException(
636:                                            "Primary key field "
637:                                                    + fieldName
638:                                                    + " is not defined in class "
639:                                                    + ejbClassName
640:                                                    + " or any super classes");
641:                                }
642:                                super class.addField(new Id(fieldName));
643:                                mapping.addField(new AttributeOverride(
644:                                        fieldName));
645:                                primaryKeyFields.add(fieldName);
646:                            }
647:                        }
648:                        if (super class != null) {
649:                            super class.setIdClass(new IdClass(bean
650:                                    .getPrimKeyClass()));
651:                        }
652:                    } catch (ClassNotFoundException e) {
653:                        // todo throw exception
654:                    }
655:                }
656:
657:                //
658:                // basic: cmp-fields
659:                //
660:                for (CmpField cmpField : bean.getCmpField()) {
661:                    String fieldName = cmpField.getFieldName();
662:                    if (!primaryKeyFields.contains(fieldName)) {
663:                        MappedSuperclass super class = super classByField
664:                                .get(fieldName);
665:                        if (super class == null) {
666:                            throw new IllegalStateException(
667:                                    "Primary key field " + fieldName
668:                                            + " is not defined in class "
669:                                            + ejbClassName
670:                                            + " or any super classes");
671:                        }
672:                        super class.addField(new Basic(fieldName));
673:                        mapping.addField(new AttributeOverride(fieldName));
674:                    }
675:                }
676:
677:                return new HashSet<MappedSuperclass>(super classByField.values());
678:            }
679:
680:            private Map<String, MappedSuperclass> mapFields(Class clazz,
681:                    Set<String> persistantFields) {
682:                persistantFields = new TreeSet<String>(persistantFields);
683:                Map<String, MappedSuperclass> fields = new TreeMap<String, MappedSuperclass>();
684:
685:                while (!persistantFields.isEmpty()
686:                        && !clazz.equals(Object.class)) {
687:                    MappedSuperclass super class = new MappedSuperclass(clazz
688:                            .getName());
689:                    for (java.lang.reflect.Field field : clazz
690:                            .getDeclaredFields()) {
691:                        String fieldName = field.getName();
692:                        if (persistantFields.contains(fieldName)) {
693:                            fields.put(fieldName, super class);
694:                            persistantFields.remove(fieldName);
695:                        } else if (!ENHANCEED_FIELDS.contains(fieldName)) {
696:                            Transient transientField = new Transient(fieldName);
697:                            super class.addField(transientField);
698:                        }
699:                    }
700:                    clazz = clazz.getSuperclass();
701:                }
702:
703:                return fields;
704:            }
705:
706:            private boolean addPersistenceContextRef(EntityBean bean) {
707:                // if a ref is already defined, skip this bean
708:                if (bean.getPersistenceContextRefMap().containsKey(
709:                        JpaCmpEngine.CMP_PERSISTENCE_CONTEXT_REF_NAME))
710:                    return false;
711:
712:                PersistenceContextRef persistenceContextRef = new PersistenceContextRef();
713:                persistenceContextRef
714:                        .setName(JpaCmpEngine.CMP_PERSISTENCE_CONTEXT_REF_NAME);
715:                persistenceContextRef
716:                        .setPersistenceUnitName(CMP_PERSISTENCE_UNIT_NAME);
717:                bean.getPersistenceContextRef().add(persistenceContextRef);
718:                return true;
719:            }
720:
721:            private void setCascade(EjbRelationshipRole role,
722:                    RelationField field) {
723:                if (role.getCascadeDelete()) {
724:                    CascadeType cascadeType = new CascadeType();
725:                    cascadeType.setCascadeAll(true);
726:                    field.setCascade(cascadeType);
727:                }
728:            }
729:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.