KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > web > jsf > wizards > JSFClientGenerator


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.web.jsf.wizards;
21
22 import java.io.BufferedWriter JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.OutputStreamWriter JavaDoc;
25 import java.lang.reflect.Modifier JavaDoc;
26 import java.text.MessageFormat JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Collections JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.HashSet JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import javax.swing.JEditorPane JavaDoc;
34 import javax.swing.text.BadLocationException JavaDoc;
35 import org.netbeans.api.project.Project;
36 import org.netbeans.api.project.SourceGroup;
37 import org.netbeans.api.project.Sources;
38 import org.netbeans.editor.BaseDocument;
39 import org.netbeans.modules.web.api.webmodule.WebModule;
40 import org.netbeans.modules.web.api.webmodule.WebProjectConstants;
41 import org.netbeans.modules.web.jsf.JSFConfigDataObject;
42 import org.netbeans.modules.web.jsf.JSFConfigUtilities;
43 import org.netbeans.modules.web.jsf.JSFFrameworkProvider;
44 import org.netbeans.modules.web.jsf.palette.items.JsfForm;
45 import org.netbeans.modules.web.jsf.palette.items.JsfTable;
46 import org.openide.ErrorManager;
47 import org.openide.filesystems.FileLock;
48 import org.openide.filesystems.FileObject;
49 import org.openide.filesystems.FileSystem;
50 import org.openide.filesystems.FileUtil;
51 import org.openide.loaders.DataObject;
52 import org.openide.util.Utilities;
53
54 /**
55  *
56  * @author Pavel Buzek
57  */

58 public class JSFClientGenerator {
59     
60     private static String JavaDoc INDEX_PAGE = "index.jsp";
61   //TODO: RETOUCHE
62
public static void generateJSFPages(Project project, String JavaDoc entityClass, String JavaDoc jsfFolder, String JavaDoc controllerClass, FileObject pkg) throws IOException JavaDoc {
63 // boolean isInjection = Util.isSupportedJavaEEVersion(project);
64

65         String JavaDoc simpleControllerName = simpleClassName(controllerClass);
66         String JavaDoc simpleEntityName = simpleClassName(entityClass);
67         if (jsfFolder.startsWith("/")) {
68             jsfFolder = jsfFolder.substring(1);
69         }
70         
71         Sources srcs = (Sources) project.getLookup().lookup(Sources.class);
72         String JavaDoc pkgName = controllerClass.substring(0, controllerClass.lastIndexOf('.'));
73         
74         String JavaDoc persistenceUnit = null;
75 // PersistenceScope persistenceScopes[] = PersistenceUtils.getPersistenceScopes(project);
76
// if (persistenceScopes.length > 0) {
77
// FileObject persXml = persistenceScopes[0].getPersistenceXml();
78
// if (persXml != null) {
79
// Persistence persistence = PersistenceMetadata.getDefault().getRoot(persXml);
80
// PersistenceUnit units[] = persistence.getPersistenceUnit();
81
// if (units.length > 0) {
82
// persistenceUnit = units[0].getName();
83
// }
84
// }
85
// }
86
// SourceGroup sgWeb[] = srcs.getSourceGroups(WebProjectConstants.TYPE_DOC_ROOT);
87
// final FileObject jsfRoot = FileUtil.createFolder(sgWeb[0].getRootFolder(), jsfFolder);
88
//
89
// String simpleConverterName = simpleEntityName + "Converter"; //NOI18N
90
// String converterName = pkgName + "." + simpleConverterName;
91
// String fieldName = fieldFromClassName(simpleEntityName);
92
//
93
// //detect access type
94
// JavaClass jc = JsfForm.resolveJavaClass(pkg, entityClass);
95
// boolean fieldAccess = JsfForm.isFieldAccess(jc);
96
//
97
// Method methods [] = JsfForm.getEntityMethods(jc);
98
// String idProperty = "Cannot Detect @Id Property";
99
// String idGetter = "Cannot Detect @Id Property";
100
// String idPropertyType = "int";
101
// List toOneRelMethods = new ArrayList();
102
// List toManyRelMethods = new ArrayList();
103
// for (int i = 0; i < methods.length; i++) {
104
// if (methods[i].getName().startsWith("get")) {
105
// Feature f = fieldAccess ? JsfForm.guessField(methods[i]) : methods[i];
106
// if (f != null) {
107
// for (Iterator it = f.getAnnotations().iterator(); it.hasNext();) {
108
// Annotation ann = (Annotation) it.next();
109
// if (ann.getType() == null) {
110
// //cannot resolve type, invalid code
111
// continue;
112
// }
113
// String annName = ann.getType().getName();
114
// if ("javax.persistence.Id".equals(annName) ||
115
// "javax.persistence.EmbeddedId".equals(annName)) {
116
// String name = methods[i].getName().substring(3);
117
// idGetter = methods[i].getName();
118
// idProperty = getPropNameFromMethod(methods[i].getName());
119
// idPropertyType = methods[i].getType().getName();
120
// } else if ("javax.persistence.OneToOne".equals(annName) ||
121
// "javax.persistence.ManyToOne".equals(annName)) {
122
// toOneRelMethods.add(methods[i]);
123
// } else if ("javax.persistence.OneToMany".equals(annName) ||
124
// "javax.persistence.ManyToMany".equals(annName)) {
125
// toManyRelMethods.add(methods[i]);
126
// }
127
// }
128
// }
129
// }
130
// }
131
//
132
// JEditorPane ep = new JEditorPane("text/x-jsp", "");
133
// BaseDocument doc = new BaseDocument(ep.getEditorKit().getClass(), false);
134
// WebModule wm = WebModule.getWebModule(jsfRoot);
135
// boolean addLinksToIndex = false;
136
//
137
// //automatically add JSF framework if it is not added
138
// JSFFrameworkProvider fp = new JSFFrameworkProvider();
139
// if (!fp.isInWebModule(wm)) {
140
// fp.extend(wm);
141
// }
142
//
143
// boolean rollback = true;
144
//
145
// JavaModel.getJavaRepository().beginTrans(true);
146
// try {
147
// JMIGenerationUtil.addInterface(jc, "java.io.Serializable"); //NOI18N
148
// rollback = false;
149
// } catch (Exception e) {
150
// e.printStackTrace();
151
// } finally {
152
// JavaModel.getJavaRepository().endTrans(rollback);
153
// }
154
//
155
// JavaClass javaClass = generateControllerClass(fieldName, pkg, idProperty, idGetter, persistenceUnit, simpleControllerName, entityClass, idPropertyType, simpleEntityName, toOneRelMethods, toManyRelMethods, isInjection, fieldAccess);
156
//
157
// String managedBean = getManagedBeanName(simpleEntityName);
158
// JavaClass converter = generateConverter(pkg, simpleConverterName, controllerClass, simpleControllerName, entityClass, simpleEntityName, idPropertyType, idGetter, managedBean, isInjection);
159
//
160
// // <editor-fold desc=" Add link to List.jsp into index.jsp ">
161
//
162
// FileObject documentBase = wm.getDocumentBase();
163
// FileObject indexjsp = documentBase.getFileObject(INDEX_PAGE); //NOI18N
164
// if (indexjsp != null){
165
//
166
// String content = JSFFrameworkProvider.readResource(indexjsp.getInputStream(), "UTF-8"); //NO18N
167
//
168
// // what find
169
// String find = "<h1>JSP Page</h1>"; // NOI18N
170
// String endLine = System.getProperty("line.separator"); //NOI18N
171
// if ( content.indexOf(find) > 0){
172
// addLinksToIndex = true;
173
// StringBuffer replace = new StringBuffer();
174
// replace.append(find);
175
// replace.append(endLine);
176
// replace.append(" <br/>"); //NOI18N
177
// replace.append(endLine);
178
// replace.append(" <a HREF=\"."); //NOI18N
179
// replace.append(JSFConfigUtilities.translateURI(JSFConfigUtilities.getActionServletMapping(wm.getDeploymentDescriptor()),"/" + jsfFolder + "/List.jsp")); //NOI18N
180
// replace.append("\">"); //NOI18N
181
// replace.append("List of " + simpleEntityName);
182
// replace.append("</a>"); //NOI18N
183
// content = content.replaceFirst(find, new String (replace.toString().getBytes("UTF8"), "UTF-8")); //NOI18N
184
// JSFFrameworkProvider.createFile(indexjsp, content, "UTF-8"); //NOI18N
185
// }
186
// }
187
//
188
// // </editor-fold>
189
//
190
// String linkToIndex = addLinksToIndex ? "<br>\n<a HREF=\"" + wm.getContextPath() + "/" + INDEX_PAGE + "\">Back to index</a>\n" : "";
191
// // <editor-fold desc=" Generate List.jsp ">
192
// FileSystem fs = jsfRoot.getFileSystem();
193
// StringBuffer listSb = new StringBuffer();
194
// listSb.append("<%@page contentType=\"text/html\"%>\n<%@page pageEncoding=\"UTF-8\"%>\n"
195
// + "<%@taglib uri=\"http://java.sun.com/jsf/core\" prefix=\"f\" %>\n"
196
// + "<%@taglib uri=\"http://java.sun.com/jsf/html\" prefix=\"h\" %>\n"
197
// + "<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
198
// + "<title>List " + simpleEntityName + "</title>\n"
199
// + "</head>\n<body>\n<f:view>\n <h:messages errorStyle=\"color: red\" infoStyle=\"color: green\" layout=\"table\"/>\n ");
200
// listSb.append("<h1>Listing " + simpleEntityName + "s</h1>\n");
201
// listSb.append("<h:form>\n");
202
// listSb.append("<h:commandLink action=\"#{" + managedBean + ".createSetup}\" value=\"New " + simpleEntityName + "\"/>\n"
203
// + linkToIndex + "<br>\n");
204
// listSb.append(MessageFormat.format("<h:outputText value=\"Item #'{'{0}.firstItem + 1'}'..#'{'{0}.lastItem'}' of #'{'{0}.itemCount}\"/>"
205
// + "&nbsp;\n"
206
// + "<h:commandLink action=\"#'{'{0}.prev'}'\" value=\"Previous #'{'{0}.batchSize'}'\" rendered=\"#'{'{0}.firstItem >= {0}.batchSize'}'\"/>"
207
// + "&nbsp;\n"
208
// + "<h:commandLink action=\"#'{'{0}.next'}'\" value=\"Next #'{'{0}.batchSize'}'\" rendered=\"#'{'{0}.lastItem + {0}.batchSize <= {0}.itemCount}\"/>"
209
// + "&nbsp;\n"
210
// + "<h:commandLink action=\"#'{'{0}.next'}'\" value=\"Remaining #'{'{0}.itemCount - {0}.lastItem'}'\"\n"
211
// + "rendered=\"#'{'{0}.lastItem < {0}.itemCount && {0}.lastItem + {0}.batchSize > {0}.itemCount'}'\"/>\n", managedBean));
212
// listSb.append("<h:dataTable value='#{" + managedBean + "." + fieldName + "s}' var='item' border=\"1\" cellpadding=\"2\" cellspacing=\"0\">\n");
213
// String commands = "<h:column>\n <h:commandLink value=\"Destroy\" action=\"#'{'" + managedBean + ".destroy'}'\">\n"
214
// + "<f:param name=\"" + idProperty +"\" value=\"#'{'{0}." + idProperty + "'}'\"/>\n"
215
// + "</h:commandLink>\n <h:outputText value=\" \"/>\n"
216
// + " <h:commandLink value=\"Edit\" action=\"#'{'" + managedBean + ".editSetup'}'\">\n"
217
// + "<f:param name=\"" + idProperty +"\" value=\"#'{'{0}." + idProperty + "'}'\"/>\n"
218
// + "</h:commandLink>\n </h:column>\n";
219
// JsfTable.createTable(JMIUtils.findClass(entityClass), managedBean + "." + fieldName, listSb, commands, "detailSetup");
220
// listSb.append("</h:dataTable>\n </h:form>\n</f:view>\n</body>\n</html>\n");
221
//
222
// try {
223
// doc.remove(0, doc.getLength());
224
// doc.insertString(0, listSb.toString(), null);
225
// doc.getFormatter().reformat(doc, 0, doc.getLength());
226
// listSb.replace(0, listSb.length(), doc.getText(0, doc.getLength()));
227
// } catch (BadLocationException e) {
228
// ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
229
// }
230
//
231
// final String listText = listSb.toString();
232
//
233
// fs.runAtomicAction(new FileSystem.AtomicAction() {
234
// public void run() throws IOException {
235
// FileObject list = FileUtil.createData(jsfRoot, "List.jsp");//NOI18N
236
// FileLock lock = list.lock();
237
// try {
238
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(list.getOutputStream(lock)));
239
// bw.write(listText);
240
// bw.close();
241
// }
242
// finally {
243
// lock.releaseLock();
244
// }
245
// }
246
// });
247
//
248
// // </editor-fold>
249
//
250
// // <editor-fold desc=" Generate New.jsp ">
251
//
252
// StringBuffer newSb = new StringBuffer();
253
// newSb.append("<%@page contentType=\"text/html\"%>\n<%@page pageEncoding=\"UTF-8\"%>\n"
254
// + "<%@taglib uri=\"http://java.sun.com/jsf/core\" prefix=\"f\" %>\n"
255
// + "<%@taglib uri=\"http://java.sun.com/jsf/html\" prefix=\"h\" %>\n"
256
// + "<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
257
// + "<title>New " + simpleEntityName + "</title>\n"
258
// + "</head>\n<body>\n<f:view>\n <h:messages errorStyle=\"color: red\" infoStyle=\"color: green\" layout=\"table\"/>\n ");
259
// newSb.append("<h1>New " + managedBean + "</h1>\n");
260
// newSb.append("<h:form>\n <h:panelGrid columns=\"2\">\n");
261
//
262
// JsfForm.createForm(JMIUtils.findClass(entityClass), JsfForm.FORM_TYPE_NEW, managedBean + "." + fieldName, newSb, true);
263
// newSb.append("</h:panelGrid>\n");
264
//
265
// List<String> classNames = new ArrayList<String>();
266
// List<String> idProperties = new ArrayList<String>();
267
// for(Iterator it = toOneRelMethods.iterator(); it.hasNext();) {
268
// Method m = (Method) it.next();
269
// Method otherSide = JsfForm.getOtherSideOfRelation(m, fieldAccess);
270
// if (otherSide != null) {
271
// JavaClass relClass = (JavaClass) otherSide.getDeclaringClass();
272
// classNames.add(simpleClassName(relClass.getName()));
273
// idProperties.add(getPropNameFromMethod(m.getName()));
274
// }
275
// }
276
//
277
//// <h:commandLink action="#{comment.createFromPost}" value="Create" rendered="#{comment.comment.postId != null}"/>
278
// StringBuffer newRenderDefaultOption = new StringBuffer();
279
// for(int i = 0; i < classNames.size(); i++) {
280
// StringBuffer negativeCondition = new StringBuffer();
281
// if (classNames.size() > 0) {
282
// for(int j = 0; j < classNames.size(); j++) {
283
// if (i != j) {
284
// negativeCondition.append(" and " + managedBean + "." + fieldName + "." + idProperties.get(j) + " == null");
285
// }
286
// }
287
// }
288
// newSb.append("<h:commandLink action=\"#{" + managedBean + ".createFrom" +
289
// classNames.get(i) + "}\" value=\"Create\" rendered=\"#{" + managedBean + "." + fieldName + "." + idProperties.get(i) + " != null" + negativeCondition.toString() + "}\"/>\n");
290
// if (i > 0) {
291
// newRenderDefaultOption.append(" and ");
292
// }
293
// newRenderDefaultOption.append(managedBean + "." + fieldName + "." + idProperties.get(i) + " == null");
294
//
295
// }
296
//
297
//// <h:commandLink action="#{comment.create}" value="Create" rendered="#{comment.comment.postId == null}"/>
298
// if (classNames.size() == 0) {
299
// newSb.append("<h:commandLink action=\"#{" + managedBean + ".create}\" value=\"Create\"/>\n<br>\n");
300
// } else {
301
// newSb.append("<h:commandLink action=\"#{" + managedBean + ".create}\" value=\"Create\" rendered=\"#{" + newRenderDefaultOption.toString() + "}\"/>\n<br>\n");
302
// }
303
//
304
// newSb.append("<h:commandLink action=\"" + fieldName + "_list\" value=\"Show All " + simpleEntityName + "\"/>\n " + linkToIndex
305
// + "</h:form>\n </f:view>\n</body>\n</html>\n");
306
//
307
// try {
308
// doc.remove(0, doc.getLength());
309
// doc.insertString(0, newSb.toString(), null);
310
// doc.getFormatter().reformat(doc, 0, doc.getLength());
311
// newSb.replace(0, newSb.length(), doc.getText(0, doc.getLength()));
312
// } catch (BadLocationException e) {
313
// ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
314
// }
315
// final String newText = newSb.toString();
316
//
317
// fs.runAtomicAction(new FileSystem.AtomicAction() {
318
// public void run() throws IOException {
319
// FileObject newForm = FileUtil.createData(jsfRoot, "New.jsp");//NOI18N
320
// FileLock lock = newForm.lock();
321
// try {
322
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(newForm.getOutputStream(lock)));
323
// bw.write(newText);
324
// bw.close();
325
// }
326
// finally {
327
// lock.releaseLock();
328
// }
329
// }
330
// });
331
//
332
// // </editor-fold>
333
//
334
// // <editor-fold desc=" Generate Edit.jsp ">
335
//
336
// StringBuffer editSb = new StringBuffer();
337
// editSb.append("<%@page contentType=\"text/html\"%>\n<%@page pageEncoding=\"UTF-8\"%>\n"
338
// + "<%@taglib uri=\"http://java.sun.com/jsf/core\" prefix=\"f\" %>\n"
339
// + "<%@taglib uri=\"http://java.sun.com/jsf/html\" prefix=\"h\" %>\n"
340
// + "<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
341
// + "<title>Edit " + simpleEntityName + "</title>\n"
342
// + "</head>\n<body>\n<f:view>\n <h:messages errorStyle=\"color: red\" infoStyle=\"color: green\" layout=\"table\"/>\n ");
343
// editSb.append("<h1>Edit " + managedBean + "</h1>\n");
344
// editSb.append("<h:form>\n <h:inputHidden value=\"#{" + managedBean + "." + fieldName + "}\" immediate=\"true\"/>\n"
345
// + "<h:panelGrid columns=\"2\">\n");
346
//
347
// JsfForm.createForm(JMIUtils.findClass(entityClass), JsfForm.FORM_TYPE_EDIT, managedBean + "." + fieldName, editSb, true);
348
// editSb.append("</h:panelGrid>\n<h:commandLink action=\"#{" + managedBean + ".edit}\" value=\"Save\"/>\n<br>\n"
349
// + "<h:commandLink action=\"" + fieldName + "_list\" value=\"Show All " + simpleEntityName + "\"/>\n" + linkToIndex
350
// + "</h:form>\n </f:view>\n</body>\n</html>\n");
351
//
352
// try {
353
// doc.remove(0, doc.getLength());
354
// doc.insertString(0, editSb.toString(), null);
355
// doc.getFormatter().reformat(doc, 0, doc.getLength());
356
// editSb.replace(0, editSb.length(), doc.getText(0, doc.getLength()));
357
// } catch (BadLocationException e) {
358
// ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
359
// }
360
//
361
// final String editText = editSb.toString();
362
//
363
// fs.runAtomicAction(new FileSystem.AtomicAction() {
364
// public void run() throws IOException {
365
// FileObject editForm = FileUtil.createData(jsfRoot, "Edit.jsp");//NOI18N
366
// FileLock lock = editForm.lock();
367
// try {
368
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(editForm.getOutputStream(lock)));
369
// bw.write(editText);
370
// bw.close();
371
// }
372
// finally {
373
// lock.releaseLock();
374
// }
375
// }
376
// });
377
//
378
// // </editor-fold>
379
//
380
// // <editor-fold desc=" Generate Detail.jsp ">
381
//
382
// StringBuffer detailSb = new StringBuffer();
383
// detailSb.append("<%@page contentType=\"text/html\"%>\n<%@page pageEncoding=\"UTF-8\"%>\n"
384
// + "<%@taglib uri=\"http://java.sun.com/jsf/core\" prefix=\"f\" %>\n"
385
// + "<%@taglib uri=\"http://java.sun.com/jsf/html\" prefix=\"h\" %>\n"
386
// + "<html>\n<head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n"
387
// + "<title>Detail of " + simpleEntityName + "</title>\n"
388
// + "</head>\n<body>\n<f:view>\n <h:messages errorStyle=\"color: red\" infoStyle=\"color: green\" layout=\"table\"/>\n ");
389
// detailSb.append("<h1>Detail of " + managedBean + "</h1>\n");
390
// detailSb.append("<h:form>\n <h:panelGrid columns=\"2\">\n");
391
//
392
// JsfForm.createForm(JMIUtils.findClass(entityClass), JsfForm.FORM_TYPE_DETAIL, managedBean + "." + fieldName, detailSb, true);
393
// detailSb.append("</h:panelGrid>\n");
394
// JsfForm.createTablesForRelated(JMIUtils.findClass(entityClass), JsfForm.FORM_TYPE_DETAIL, managedBean + "." + fieldName, idProperty, isInjection, detailSb);
395
// detailSb.append("<h:commandLink action=\"" + fieldName + "_edit\" value=\"Edit\" />\n<br>\n"
396
// + "<h:commandLink action=\"" + fieldName + "_list\" value=\"Show All " + simpleEntityName + "\"/>\n" + linkToIndex
397
// + "</h:form>\n </f:view>\n</body>\n</html>\n");
398
//
399
// try {
400
// doc.remove(0, doc.getLength());
401
// doc.insertString(0, detailSb.toString(), null);
402
// doc.getFormatter().reformat(doc, 0, doc.getLength());
403
// detailSb.replace(0, detailSb.length(), doc.getText(0, doc.getLength()));
404
// } catch (BadLocationException e) {
405
// ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
406
// }
407
//
408
// final String detailText = detailSb.toString();
409
//
410
// fs.runAtomicAction(new FileSystem.AtomicAction() {
411
// public void run() throws IOException {
412
// FileObject detailForm = FileUtil.createData(jsfRoot, "Detail.jsp");//NOI18N
413
// FileLock lock = detailForm.lock();
414
// try {
415
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(detailForm.getOutputStream(lock)));
416
// bw.write(detailText);
417
// bw.close();
418
// }
419
// finally {
420
// lock.releaseLock();
421
// }
422
// }
423
// });
424
//
425
// // </editor-fold>
426
//
427
// // <editor-fold desc=" Add managed bean, converters and navigation rules into faces-config.xml ">
428
//
429
// String[] configFiles = JSFConfigUtilities.getConfigFiles(wm.getDeploymentDescriptor());
430
// if (configFiles.length > 0) {
431
// FileObject fo = wm.getDocumentBase().getFileObject(configFiles[0]);
432
// try {
433
// JSFConfigDataObject configDO = (JSFConfigDataObject)DataObject.find(fo);
434
// FacesConfig config= configDO.getFacesConfig();
435
// ManagedBean mb = config.newManagedBean();
436
// mb.setManagedBeanName(managedBean);
437
// mb.setManagedBeanClass(controllerClass);
438
// mb.setManagedBeanScope("session");
439
// config.addManagedBean(mb);
440
//
441
// Converter cv = config.newConverter();
442
// cv.setConverterForClass(entityClass);
443
// cv.setConverterClass(converterName);
444
// config.addConverter(cv);
445
//
446
// Type idType = JMIUtils.resolveType(idPropertyType);
447
// if (idType instanceof JavaClass) {
448
// JavaClass idClass = (JavaClass) idType;
449
// if (JsfForm.isEmbeddableClass(idClass)) {
450
// cv = config.newConverter();
451
// cv.setConverterForClass(idPropertyType);
452
// cv.setConverterClass((pkgName.length() > 0 ? pkgName + "." : "") + simpleClassName(idPropertyType) + "Converter");
453
// config.addConverter(cv);
454
// }
455
// }
456
//
457
// NavigationRule nr = config.newNavigationRule();
458
// NavigationCase nc = nr.newNavigationCase();
459
// nc.setFromOutcome(fieldName + "_create");
460
// nc.setToViewId("/" + jsfFolder + "/New.jsp");
461
// nr.addNavigationCase(nc);
462
// config.addNavigationRule(nr);
463
//
464
// nr = config.newNavigationRule();
465
// nc = nr.newNavigationCase();
466
// nc.setFromOutcome(fieldName + "_list");
467
// nc.setToViewId("/" + jsfFolder + "/List.jsp");
468
// nr.addNavigationCase(nc);
469
// config.addNavigationRule(nr);
470
//
471
// nr = config.newNavigationRule();
472
// nc = nr.newNavigationCase();
473
// nc.setFromOutcome(fieldName + "_edit");
474
// nc.setToViewId("/" + jsfFolder + "/Edit.jsp");
475
// nr.addNavigationCase(nc);
476
// config.addNavigationRule(nr);
477
//
478
// nr = config.newNavigationRule();
479
// nc = nr.newNavigationCase();
480
// nc.setFromOutcome(fieldName + "_detail");
481
// nc.setToViewId("/" + jsfFolder + "/Detail.jsp");
482
// nr.addNavigationCase(nc);
483
// config.addNavigationRule(nr);
484
//
485
// configDO.write(config);
486
// } catch (IOException ioex) {
487
// ErrorManager.getDefault().notify(ioex);
488
// }
489
// }
490
// // </editor-fold>
491

492     }
493     
494 // private static JavaClass generateConverter(
495
// final FileObject pkg,
496
// final String simpleConverterName,
497
// final String controllerClass,
498
// final String simpleControllerName,
499
// final String entityClass,
500
// final String simpleEntityName,
501
// final String idPropertyType,
502
// final String idGetter,
503
// final String managedBeanName,
504
// final boolean isInjection) {
505
// JavaClass javaClass = null;
506
// boolean rollback = true;
507
//
508
// JavaModel.getJavaRepository().beginTrans(true);
509
// try {
510
// JavaClass idClass = null;
511
// Type idType = JMIUtils.resolveType(idPropertyType);
512
// if (idType instanceof JavaClass) {
513
// idClass = (JavaClass) idType;
514
// }
515
// boolean embeddable = idClass != null && JsfForm.isEmbeddableClass(idClass);
516
// JavaClass idConverter = null;
517
// Parameter p;
518
// Method getAsObjectE = null;
519
// Method getAsStringE = null;
520
//
521
// if (embeddable) {
522
// idConverter = JMIGenerationUtil.createClass(pkg, simpleClassName(idPropertyType) + "Converter"); //NOI18N
523
// JMIGenerationUtil.addInterface(idConverter, "javax.faces.convert.Converter");
524
// getAsObjectE = JMIGenerationUtil.createMethod(idConverter, "getAsObject", Modifier.PUBLIC, "java.lang.Object"); //NOI18N
525
// p = JMIGenerationUtil.createParameter(idConverter, "facesContext", "javax.faces.context.FacesContext"); //NOI18N
526
// getAsObjectE.getParameters().add(p);
527
// p = JMIGenerationUtil.createParameter(idConverter, "uIComponent", "javax.faces.component.UIComponent"); //NOI18N
528
// getAsObjectE.getParameters().add(p);
529
// p = JMIGenerationUtil.createParameter(idConverter, "string", "java.lang.String"); //NOI18N
530
// getAsObjectE.getParameters().add(p);
531
//
532
// getAsStringE = JMIGenerationUtil.createMethod(idConverter, "getAsString", Modifier.PUBLIC, "java.lang.String"); //NOI18N
533
// p = JMIGenerationUtil.createParameter(idConverter, "facesContext", "javax.faces.context.FacesContext"); //NOI18N
534
// getAsStringE.getParameters().add(p);
535
// p = JMIGenerationUtil.createParameter(idConverter, "uIComponent", "javax.faces.component.UIComponent"); //NOI18N
536
// getAsStringE.getParameters().add(p);
537
// p = JMIGenerationUtil.createParameter(idConverter, "object", "java.lang.Object"); //NOI18N
538
// getAsStringE.getParameters().add(p);
539
// }
540
//
541
// javaClass = JMIGenerationUtil.createClass(pkg, simpleConverterName);
542
// JMIGenerationUtil.addInterface(javaClass, "javax.faces.convert.Converter");
543
//
544
// Method getAsObject = JMIGenerationUtil.createMethod(javaClass, "getAsObject", Modifier.PUBLIC, "java.lang.Object"); //NOI18N
545
// p = JMIGenerationUtil.createParameter(javaClass, "facesContext", "javax.faces.context.FacesContext"); //NOI18N
546
// getAsObject.getParameters().add(p);
547
// p = JMIGenerationUtil.createParameter(javaClass, "uIComponent", "javax.faces.component.UIComponent"); //NOI18N
548
// getAsObject.getParameters().add(p);
549
// p = JMIGenerationUtil.createParameter(javaClass, "string", "java.lang.String"); //NOI18N
550
// getAsObject.getParameters().add(p);
551
//
552
// String controllerReferenceName = JMIGenerationUtil.createImport(javaClass, controllerClass).getName();
553
// StringBuffer getAsObjectBody = new StringBuffer();
554
// getAsObjectBody.append("if (string == null) {\n return null;\n }\n");
555
//
556
// String controllerVariable;
557
// if (isInjection) {
558
// controllerVariable= controllerReferenceName + " controller = ("
559
// + controllerReferenceName
560
// + ") facesContext.getApplication().getELResolver().getValue(\nfacesContext.getELContext(), null, \""
561
// + managedBeanName +"\");\n";
562
// } else {
563
// controllerVariable = controllerReferenceName + " controller = ("
564
// + controllerReferenceName
565
// + ") facesContext.getApplication().getVariableResolver().resolveVariable(\nfacesContext, \""
566
// + managedBeanName +"\");\n";
567
// }
568
// ArrayList<Method> paramSetters = new ArrayList<Method>();
569
// if (embeddable) {
570
// getAsObjectBody.append(idPropertyType + " id = new "
571
// + idPropertyType + "();\n");
572
// Method methods [] = JMIUtils.getMethods(idClass);
573
// boolean fieldAccess = JsfForm.isFieldAccess(idClass);
574
// JMIGenerationUtil.createImport(javaClass, "java.util.StringTokenizer");
575
// JMIGenerationUtil.createImport(idConverter, "java.util.StringTokenizer");
576
// getAsObjectBody.append("StringTokenizer idTokens = new StringTokenizer(string, \";\");\n");
577
// for (int i = 0; i < methods.length; i++) {
578
// if (methods[i].getName().startsWith("get")) {
579
// paramSetters.add(methods[i]);
580
// }
581
// }
582
// int params = paramSetters.size();
583
// getAsObjectBody.append("String params[] = new String[" + params + "];\n"
584
// + "int i = 0;\n while(idTokens.hasMoreTokens()) {\n"
585
// + "params[i++] = idTokens.nextToken();\n }\n"
586
// + "if (i != " + params + ") {\n"
587
// + "throw new IllegalArgumentException(\"Expected format of parameter string is a set of "
588
// + params + " IDs delimited by ;\");\n }\n");
589
// for (int i = 0; i < paramSetters.size(); i++) {
590
// getAsObjectBody.append("id.s" + paramSetters.get(i).getName().substring(1) + "("
591
// + createIdFieldInitialization(paramSetters.get(i).getType().getName(), "params[" + i + "]") + ");\n");
592
// }
593
// getAsObjectE.setBodyText(getAsObjectBody.toString() + "return id;\n");
594
// idConverter.getFeatures().add(getAsObjectE);
595
// getAsObjectBody.append(controllerVariable + "\n return controller.find" + simpleEntityName + "(id);");
596
// } else {
597
// getAsObjectBody.append(createIdFieldDeclaration(idPropertyType, "string") + "\n"
598
// + controllerVariable
599
// + "\n return controller.find" + simpleEntityName + "(id);");
600
// }
601
// getAsObject.setBodyText(getAsObjectBody.toString());
602
// javaClass.getFeatures().add(getAsObject);
603
//
604
// Method getAsString = JMIGenerationUtil.createMethod(javaClass, "getAsString", Modifier.PUBLIC, "java.lang.String"); //NOI18N
605
// p = JMIGenerationUtil.createParameter(javaClass, "facesContext", "javax.faces.context.FacesContext"); //NOI18N
606
// getAsString.getParameters().add(p);
607
// p = JMIGenerationUtil.createParameter(javaClass, "uIComponent", "javax.faces.component.UIComponent"); //NOI18N
608
// getAsString.getParameters().add(p);
609
// p = JMIGenerationUtil.createParameter(javaClass, "object", "java.lang.Object"); //NOI18N
610
// getAsString.getParameters().add(p);
611
//
612
// String entityReferenceName = JMIGenerationUtil.createImport(javaClass, entityClass).getName();
613
// String idPropertyTypeRefName = null;
614
// StringBuffer getAsStringBody = new StringBuffer();
615
// StringBuffer getAsStringEBody = new StringBuffer();
616
// getAsStringBody.append("if (object == null) {\n return null;\n }\n"
617
// + "if(object instanceof " + entityReferenceName + ") {\n"
618
// + entityReferenceName + " o = (" + entityReferenceName +") object;\n");
619
// if (embeddable) {
620
// idPropertyTypeRefName = JMIGenerationUtil.createImport(idConverter, idPropertyType).getName();
621
// getAsStringEBody.append("if (object == null) {\n return null;\n }\n"
622
// + "if(object instanceof " + idPropertyTypeRefName + ") {\n"
623
// + idPropertyTypeRefName + " o = (" + idPropertyTypeRefName +") object;\n");
624
// getAsStringBody.append("return ");
625
// getAsStringEBody.append("return ");
626
// for(int i = 0; i < paramSetters.size(); i++) {
627
// if (i > 0) {
628
// getAsStringBody.append(" + \";\" + ");
629
// getAsStringEBody.append(" + \";\" + ");
630
// }
631
// getAsStringBody.append("o." + idGetter + "()." + paramSetters.get(i).getName() + "()");
632
// getAsStringEBody.append("o." + paramSetters.get(i).getName() + "()");
633
// }
634
// getAsStringBody.append(";\n");
635
// getAsStringEBody.append(";\n");
636
// } else {
637
// getAsStringBody.append("return \"\" + o." + idGetter + "();\n");
638
// }
639
// getAsStringBody.append("} else {\n"
640
// + "throw new IllegalArgumentException(\"object:\" + object + \" of type:\" + object.getClass().getName() + \"; expected type: " + entityClass +"\");\n}");
641
// getAsString.setBodyText(getAsStringBody.toString());
642
// javaClass.getFeatures().add(getAsString);
643
// if (embeddable) {
644
// getAsStringEBody.append("} else {\n"
645
// + "throw new IllegalArgumentException(\"object:\" + object + \" of type:\" + object.getClass().getName() + \"; expected type: " + idPropertyTypeRefName +"\");\n}");
646
// getAsStringE.setBodyText(getAsStringEBody.toString());
647
// idConverter.getFeatures().add(getAsStringE);
648
// }
649
//
650
// rollback = false;
651
// } catch (Exception e) {
652
// e.printStackTrace();
653
// } finally {
654
// JavaModel.getJavaRepository().endTrans(rollback);
655
// }
656
// return javaClass;
657
// }
658
//
659
// private static JavaClass generateControllerClass(
660
// final String fieldName,
661
// final FileObject pkg,
662
// final String idProperty,
663
// final String idGetter,
664
// final String persistenceUnit,
665
// final String simpleControllerName,
666
// final String entityClass,
667
// final String idPropertyType,
668
// final String simpleEntityName,
669
// final List toOneRelMethods,
670
// final List toManyRelMethods,
671
// final boolean isInjection,
672
// final boolean isFieldAccess) {
673
// JavaClass javaClass = null;
674
// boolean rollback = true;
675
//
676
// JavaModel.getJavaRepository().beginTrans(true);
677
// try {
678
// javaClass = JMIGenerationUtil.createClass(pkg, simpleControllerName);
679
//
680
// String entityReferenceName = JMIGenerationUtil.createImport(javaClass, entityClass).getName();
681
// Field entityField = JMIGenerationUtil.createField(javaClass, fieldName, Modifier.PRIVATE, entityClass);
682
// javaClass.getFeatures().add(entityField);
683
//
684
// TypeReference dmReference = JMIGenerationUtil.createImport(javaClass, "javax.faces.model.DataModel"); //NOI18N
685
// Field dmField = JMIGenerationUtil.createField(javaClass, "model", Modifier.PRIVATE, dmReference.getName()); //NOI18N
686
// javaClass.getFeatures().add(dmField);
687
//
688
// TypeReference ldmReference = JMIGenerationUtil.createImport(javaClass, "javax.faces.model.ListDataModel"); //NOI18N
689
//
690
// Field emfField = JMIGenerationUtil.createField(javaClass, "emf", Modifier.PRIVATE, "javax.persistence.EntityManagerFactory");
691
// if (isInjection) {
692
// Field utxField = JMIGenerationUtil.createField(javaClass, "utx", Modifier.PRIVATE, "javax.transaction.UserTransaction");
693
// Annotation resourceAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.annotation.Resource", Collections.EMPTY_LIST); //NOI18N
694
// utxField.getAnnotations().add(resourceAnnotation);
695
// javaClass.getFeatures().add(utxField);
696
//
697
// Annotation persistenceContextAnnotation;
698
// if (persistenceUnit == null) {
699
// persistenceContextAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.persistence.PersistenceUnit", Collections.EMPTY_LIST); //NOI18N
700
// } else {
701
// AttributeValue persistenceContextAttrValue = JMIGenerationUtil.createAttributeValue(javaClass, "unitName", persistenceUnit); //NOI18N
702
// persistenceContextAnnotation = JMIGenerationUtil.createAnnotation(javaClass, "javax.persistence.PersistenceUnit", Collections.singletonList(persistenceContextAttrValue)); //NOI18N
703
// }
704
// emfField.getAnnotations().add(persistenceContextAnnotation);
705
// } else {
706
//
707
// Constructor constr = javaClass.getConstructor(Collections.EMPTY_LIST, false);
708
// boolean noDefaultConstructor = constr == null;
709
// if (noDefaultConstructor) {
710
// constr = JMIGenerationUtil.createConstructor(javaClass, Modifier.PUBLIC);
711
// }
712
// JMIGenerationUtil.createImport(javaClass, "javax.persistence.Persistence");
713
// constr.setBodyText("emf = Persistence.createEntityManagerFactory(\"" + persistenceUnit + "\");"); //NOI18N
714
// if (noDefaultConstructor) {
715
// javaClass.getFeatures().add(constr);
716
// }
717
// }
718
// javaClass.getFeatures().add(emfField);
719
//
720
// Method getEntityManager = JMIGenerationUtil.createMethod(javaClass, "getEntityManager", Modifier.PRIVATE, "javax.persistence.EntityManager");
721
// getEntityManager.setBodyText("return emf.createEntityManager();");
722
// javaClass.getFeatures().add(getEntityManager);
723
//
724
// Field batchSizeField = JMIGenerationUtil.createField(javaClass, "batchSize", Modifier.PRIVATE, "int");
725
// batchSizeField.setInitialValueText("20");
726
// javaClass.getFeatures().add(batchSizeField);
727
//
728
// Field firstItemField = JMIGenerationUtil.createField(javaClass, "firstItem", Modifier.PRIVATE, "int");
729
// firstItemField.setInitialValueText("0");
730
// javaClass.getFeatures().add(firstItemField);
731
//
732
// StringBuffer updateRelatedInCreate = new StringBuffer();
733
// StringBuffer updateRelatedInEditPre = new StringBuffer();
734
// StringBuffer updateRelatedInEditPost = new StringBuffer();
735
// StringBuffer updateRelatedInDestroy = new StringBuffer();
736
//
737
// List allRelMethods = new ArrayList(toOneRelMethods);
738
// allRelMethods.addAll(toManyRelMethods);
739
//
740
// Method getEntity = JMIGenerationUtil.createMethod(javaClass, "get" + simpleEntityName, Modifier.PUBLIC, entityClass); //NOI18N
741
// getEntity.setBodyText("return " + fieldName + ";"); //NOI18N
742
// javaClass.getFeatures().add(getEntity);
743
//
744
// Method setEntity = JMIGenerationUtil.createMethod(javaClass, "set" + simpleEntityName, Modifier.PUBLIC, "void"); //NOI18N
745
// setEntity.setBodyText("this." + fieldName + " = " + fieldName + ";"); //NOI18N
746
// Parameter entityParameter = JMIGenerationUtil.createParameter(javaClass, fieldName, entityClass);
747
// setEntity.getParameters().add(entityParameter);
748
// javaClass.getFeatures().add(setEntity);
749
//
750
// Method getEntityForDetail = JMIGenerationUtil.createMethod(javaClass, "getDetail" + simpleEntityName + "s", Modifier.PUBLIC, "DataModel"); //NOI18N
751
// getEntityForDetail.setBodyText("return model;"); //NOI18N
752
// javaClass.getFeatures().add(getEntityForDetail);
753
//
754
// JMIGenerationUtil.createImport(javaClass, "java.util.Collection");
755
// JMIGenerationUtil.createImport(javaClass, "java.util.ArrayList"); //NOI18N
756
// Method setEntityForDetail = JMIGenerationUtil.createMethod(javaClass, "setDetail" + simpleEntityName + "s", Modifier.PUBLIC, "void"); //NOI18N
757
// setEntityForDetail.setBodyText("model = new ListDataModel(new ArrayList(m));"); //NOI18N
758
// Parameter entityForDetailParameter = JMIGenerationUtil.createParameter(javaClass, "m", "Collection<" + entityReferenceName + ">"); //NOI18N
759
// setEntityForDetail.getParameters().add(entityForDetailParameter);
760
// javaClass.getFeatures().add(setEntityForDetail);
761
//
762
// // <editor-fold desc=" all relations ">
763
// for(Iterator it = allRelMethods.iterator(); it.hasNext();) {
764
// Method m = (Method) it.next();
765
// int multiplicity = JsfForm.isRelationship(m, isFieldAccess);
766
// Method otherSide = JsfForm.getOtherSideOfRelation(m, isFieldAccess);
767
// if (otherSide != null) {
768
// JavaClass relClass = (JavaClass) otherSide.getDeclaringClass();
769
// boolean isRelFieldAccess = JsfForm.isFieldAccess(relClass);
770
// int otherSideMultiplicity = JsfForm.isRelationship(otherSide, isRelFieldAccess);
771
// Type t = m.getType();
772
// boolean isCollection = false;
773
// if (t instanceof ParameterizedType) {
774
// MultipartId id = (MultipartId) m.getTypeName();
775
// for (Iterator iter = id.getTypeArguments().iterator(); iter.hasNext();) {
776
// MultipartId param = (MultipartId) iter.next();
777
// NamedElement parType = param.getElement();
778
// if (param instanceof JavaClass) {
779
// t = (JavaClass) param;
780
// isCollection = true;
781
// }
782
// }
783
// }
784
// String relTypeReference = JMIGenerationUtil.createImport(javaClass, t.getName()).getName();
785
// String relType = t.getName();
786
// String simpleRelType = simpleClassName(relType);
787
// String relFieldName = getPropNameFromMethod(m.getName());
788
//
789
// updateRelatedInCreate.append("\n//update property " + relFieldName + " of entity " + simpleRelType + "\n" +
790
// (isCollection ? "for(" + relTypeReference + " " + relFieldName + " : " + fieldName + "." + m.getName() + "()){\n" :
791
// relTypeReference + " " + relFieldName + "=" + fieldName + "." + m.getName() +"();\n" +
792
// "if (" + relFieldName + " != null) {\n") +
793
// relFieldName + " = em.merge(" + relFieldName +");\n" +
794
// ((otherSideMultiplicity == JsfForm.REL_TO_ONE) ? relFieldName + ".s" + otherSide.getName().substring(1) + "(" + fieldName+ ");\n" :
795
// relFieldName + "." + otherSide.getName() + "().add(" + fieldName +");\n") +
796
// relFieldName + "=em.merge(" + relFieldName +");\n}\n\n");
797
//
798
// if (isCollection) {
799
// updateRelatedInEditPre.append("\n Collection<" + relTypeReference + "> " + relFieldName + "sOld = em.find("
800
// + entityReferenceName +".class, " + fieldName + "." + idGetter + "())." + m.getName() + "();\n");
801
// updateRelatedInEditPost.append("\n//update property " + relFieldName + " of entity " + simpleRelType + "\n" +
802
// "Collection <" + relTypeReference + "> " + relFieldName + "sNew = " + fieldName + "." + m.getName() + "();\n" +
803
// "for(" + relTypeReference + " " + relFieldName + "New : " + relFieldName + "sNew) {\n" +
804
// ((otherSideMultiplicity == JsfForm.REL_TO_ONE) ? relFieldName + "New.s" + otherSide.getName().substring(1) + "(" + fieldName+ ");\n" :
805
// relFieldName + "New." + otherSide.getName() + "().add(" + fieldName +");\n") +
806
// relFieldName + "New=em.merge(" + relFieldName +"New);\n}\n" +
807
// "for(" + relTypeReference + " " + relFieldName + "Old : " + relFieldName + "sOld) {\n" +
808
// ((otherSideMultiplicity == JsfForm.REL_TO_ONE) ? relFieldName + "Old.s" + otherSide.getName().substring(1) + "(null);\n" :
809
// relFieldName + "Old." + otherSide.getName() + "().remove(" + fieldName +");\n") +
810
// relFieldName + "Old=em.merge(" + relFieldName +"Old);\n}\n");
811
// } else {
812
// updateRelatedInEditPre.append("\n" + relTypeReference + " " + relFieldName + "Old = em.find("
813
// + entityReferenceName +".class, " + fieldName + "." + idGetter + "())." + m.getName() + "();\n");
814
// updateRelatedInEditPost.append("\n//update property " + relFieldName + " of entity " + simpleRelType + "\n" +
815
// relTypeReference + " " + relFieldName + "New = " + fieldName + "." + m.getName() +"();\n" +
816
// "if(" + relFieldName + "New != null) {\n" +
817
// ((otherSideMultiplicity == JsfForm.REL_TO_ONE) ? relFieldName + "New.s" + otherSide.getName().substring(1) + "(" + fieldName+ ");\n" :
818
// relFieldName + "New." + otherSide.getName() + "().add(" + fieldName +");\n") +
819
// relFieldName + "New=em.merge(" + relFieldName +"New);\n}\n" +
820
// "if(" + relFieldName + "Old != null) {\n" +
821
// ((otherSideMultiplicity == JsfForm.REL_TO_ONE) ? relFieldName + "Old.s" + otherSide.getName().substring(1) + "(null);\n" :
822
// relFieldName + "Old." + otherSide.getName() + "().remove(" + fieldName +");\n") +
823
// relFieldName + "Old=em.merge(" + relFieldName +"Old);\n}\n");
824
// }
825
//
826
// updateRelatedInDestroy.append("\n//update property " + relFieldName + " of entity " + simpleRelType + "\n" +
827
// (isCollection ? "Collection<" + relTypeReference + "> " + relFieldName + "s" : relTypeReference + " " + relFieldName) + " = " + fieldName + "." + m.getName() +"();\n" +
828
// (isCollection ? "for(" + relTypeReference + " " + relFieldName + " : " + relFieldName + "s" : "if (" + relFieldName + " != null") + ") {\n" +
829
// relFieldName + " = em.merge(" + relFieldName +");\n" +
830
// ((otherSideMultiplicity == JsfForm.REL_TO_ONE) ? relFieldName + ".s" + otherSide.getName().substring(1) + "(null);\n" :
831
// relFieldName + "." + otherSide.getName() + "().remove(" + fieldName +");\n") +
832
// relFieldName + "=em.merge(" + relFieldName +");\n}\n\n");
833
//
834
// Method destroyFromDetail = JMIGenerationUtil.createMethod(javaClass, "destroyFrom" + simpleRelType, Modifier.PUBLIC, "String"); //NOI18N
835
// String relIdGetter = JsfForm.getIdGetter(isRelFieldAccess, relClass).getName();
836
// destroyFromDetail.setBodyText(simpleRelType + " param = get" + simpleRelType + "Controller().get" + simpleRelType + "();\n"
837
// + "destroy();\n"
838
// + "EntityManager em = getEntityManager();\n try {\n"
839
// + "get" + simpleRelType + "Controller().set" + simpleRelType
840
// + "(em.find(" + relTypeReference + ".class, param." + relIdGetter + "()));\n"
841
// + "} finally {\n em.close();\n}\n"
842
// + "return \"" + getManagedBeanName(simpleRelType) + "_detail\";\n");
843
// javaClass.getFeatures().add(destroyFromDetail);
844
//
845
// Method controllerAccess = JMIGenerationUtil.createMethod(javaClass, "get" + simpleRelType + "Controller", Modifier.PRIVATE, simpleRelType + "Controller"); //NOI18N
846
// if (isInjection) {
847
// controllerAccess.setBodyText("FacesContext context = FacesContext.getCurrentInstance();\n"
848
// + "return (" + simpleRelType +"Controller) context.getApplication().getELResolver().getValue(\n context.getELContext(), null, \""
849
// + getManagedBeanName(simpleRelType) +"\");\n");
850
// } else {
851
// controllerAccess.setBodyText("FacesContext context = FacesContext.getCurrentInstance();\n"
852
// + "return (" + simpleRelType +"Controller) context.getApplication().getVariableResolver().resolveVariable(\n context, \""
853
// + getManagedBeanName(simpleRelType) +"\");\n");
854
// }
855
// javaClass.getFeatures().add(controllerAccess);
856
//
857
// if (multiplicity == JsfForm.REL_TO_MANY) {
858
// setEntity.setBodyText(setEntity.getBodyText() + "\n"
859
// + controllerAccess.getName() + "().setDetail" + simpleRelType
860
// + "s(" + fieldName + "." + m.getName() + "());");
861
// }
862
//
863
// if (multiplicity == JsfForm.REL_TO_MANY && otherSideMultiplicity == JsfForm.REL_TO_MANY) {
864
// //methods needed to add items into N:M relationship
865
// JMIGenerationUtil.createImport(javaClass, "javax.faces.model.SelectItem");
866
// JMIGenerationUtil.createImport(javaClass, "java.util.List");
867
// Method getRelatedAvailable = JMIGenerationUtil.createMethodArray(javaClass, m.getName() + "Available", Modifier.PUBLIC, "javax.faces.model.SelectItem");
868
// getRelatedAvailable.setBodyText("EntityManager em = getEntityManager();\n try{\n"
869
// + "Query q = em.createQuery(\"select o from " + simpleRelType + " as o where "
870
// + (otherSideMultiplicity == JsfForm.REL_TO_MANY ? ":param not member of o." + getPropNameFromMethod(otherSide.getName()) + "\");\n" :
871
// "o." + getPropNameFromMethod(otherSide.getName()) + " <> :param or o." + getPropNameFromMethod(otherSide.getName()) + " IS NULL\");\n")
872
// + "q.setParameter(\"param\", " + fieldName + ");\n"
873
// + "List <" + simpleRelType + "> l = (List <" + simpleRelType + ">) q.getResultList();\n"
874
// + "SelectItem select[] = new SelectItem[l.size()];\n"
875
// + "int i = 0;\n"
876
// + "for(" + simpleRelType + " x : l) {\n"
877
// + "select[i++] = new SelectItem(x);\n"
878
// + "}\n return select;\n"
879
// + "} finally {\n em.close();\n}\n");
880
// javaClass.getFeatures().add(getRelatedAvailable);
881
//
882
// Field relatedToAdd = JMIGenerationUtil.createFieldArray(javaClass, getPropNameFromMethod(m.getName()), Modifier.PUBLIC, relTypeReference);
883
// javaClass.getFeatures().add(relatedToAdd);
884
//
885
// Method getRelatedToAdd = JMIGenerationUtil.createMethodArray(javaClass, m.getName() + "ToAdd", Modifier.PUBLIC, relTypeReference);
886
// getRelatedToAdd.setBodyText("return " + relatedToAdd.getName() + ";\n");
887
// javaClass.getFeatures().add(getRelatedToAdd);
888
//
889
// Method setRelatedToAdd = JMIGenerationUtil.createMethod(javaClass, "s" + m.getName().substring(1) + "ToAdd", Modifier.PUBLIC, "void");
890
// Parameter setRelatedToAddParam = JMIGenerationUtil.createParameterArray(javaClass, relatedToAdd.getName(), relTypeReference);
891
// setRelatedToAdd.getParameters().add(setRelatedToAddParam);
892
// setRelatedToAdd.setBodyText("this." + relatedToAdd.getName() + " = " + relatedToAdd.getName() + ";\n");
893
// javaClass.getFeatures().add(setRelatedToAdd);
894
//
895
// Method addRelated = JMIGenerationUtil.createMethod(javaClass, "add" + m.getName().substring(3), Modifier.PUBLIC, "String");
896
// addRelated.setBodyText("EntityManager em = getEntityManager();\n"
897
// + "try {\n em.getTransaction().begin();\n"
898
// + "for(" + simpleRelType + " entity : " + relatedToAdd.getName() + ") {\n"
899
// + "entity." + (otherSideMultiplicity == JsfForm.REL_TO_MANY ? otherSide.getName() + "().add(" + fieldName + ");\n" : "s" + otherSide.getName().substring(1) + "(" + fieldName + ");\n")
900
// + "entity = em.merge(entity);\n"
901
// + fieldName + "." + m.getName() + "().add(entity);\n"
902
// + "}\n"
903
// + fieldName + " = em.merge(" + fieldName + ");\n"
904
// + "em.getTransaction().commit();\n"
905
// + setEntity.getName() + "(" + fieldName + ");\n"
906
// + "addSuccessMessage(\"" + simpleRelType + " successfully added.\");\n"
907
// + "} catch (Exception ex) {\n try {\n addErrorMessage(ex.getLocalizedMessage());\n"
908
// + "em.getTransaction().rollback();\n } catch (Exception e) {\n addErrorMessage(e.getLocalizedMessage());\n"
909
// + "}\n } finally {\n em.close();\n }\n"
910
// + "return \"" + fieldName + "_detail\";\n");
911
// javaClass.getFeatures().add(addRelated);
912
//
913
// Method removeRelated = JMIGenerationUtil.createMethod(javaClass, "remove" + m.getName().substring(3), Modifier.PUBLIC, "String");
914
// removeRelated.setBodyText("EntityManager em = getEntityManager();\n"
915
// + "try {\n"
916
// + "em.getTransaction().begin();\n"
917
// + simpleRelType + " entity = (" + simpleRelType +") " + controllerAccess.getName() + "().getDetail" + simpleRelType + "s().getRowData();\n"
918
// + "entity." + (otherSideMultiplicity == JsfForm.REL_TO_MANY ? otherSide.getName() + "().remove(" + fieldName + ");\n" : "s" + otherSide.getName().substring(1) + "(null);\n")
919
// + "entity = em.merge(entity);\n"
920
// + fieldName + "." + m.getName() + "().remove(entity);\n"
921
// + fieldName + " = em.merge(" + fieldName + ");\n"
922
// + "em.getTransaction().commit();\n"
923
// + setEntity.getName() + "(" + fieldName + ");\n"
924
// + "addSuccessMessage(\"" + simpleEntityName + " successfully removed.\");\n"
925
// + "} catch (Exception ex) {\n"
926
// + "try {\n"
927
// + "addErrorMessage(ex.getLocalizedMessage());\n"
928
// + "em.getTransaction().rollback();\n"
929
// + "} catch (Exception e) {\n"
930
// + "addErrorMessage(e.getLocalizedMessage());\n"
931
// + "}\n } finally {\n em.close();\n }\n"
932
// + "return \"" + fieldName + "_detail\";\n");
933
// javaClass.getFeatures().add(removeRelated);
934
// }
935
//
936
// Method createFromDetailSetup = JMIGenerationUtil.createMethod(javaClass, "createFrom" + simpleRelType +"Setup", Modifier.PUBLIC, "String"); //NOI18N
937
// createFromDetailSetup.setBodyText("this." + fieldName + " = new " + entityReferenceName + "();\n"
938
// + "EntityManager em = getEntityManager();\n try{\n"
939
// + (isCollection ? "if (" + fieldName + "." + m.getName() + "() == null) {\n" + fieldName + ".s" + m.getName().substring(1) + "(new ArrayList());\n}\n" : "")
940
// + fieldName + (isCollection ? "." + m.getName() + "().add" : ".s" + m.getName().substring(1)) + "(em.find(" + relTypeReference + ".class, get" + simpleRelType + "Controller().get" + simpleRelType + "()." + relIdGetter + "()));\n"
941
// + "} finally {\n em.close();\n}\n"
942
// + "return \"" + getManagedBeanName(simpleEntityName) + "_create\";\n");
943
// javaClass.getFeatures().add(createFromDetailSetup);
944
//
945
// Method createFromDetail = JMIGenerationUtil.createMethod(javaClass, "createFrom" + simpleRelType, Modifier.PUBLIC, "String"); //NOI18N
946
// createFromDetail.setBodyText("create();\n" +
947
// "get" + simpleRelType + "Controller().set" + simpleRelType + "(" + fieldName + "." + m.getName() + "()"
948
// + (isCollection ? ".iterator().next()" : "") + ");\n" +
949
// "return \"" + getManagedBeanName(simpleRelType) + "_detail\";\n");
950
// javaClass.getFeatures().add(createFromDetail);
951
// } else {
952
// ErrorManager.getDefault().log(ErrorManager.INFORMATIONAL, "Cannot detect other side of a relationship.");
953
// }
954
// }
955
// // </editor-fold>
956
//
957
// Method createSetup = JMIGenerationUtil.createMethod(javaClass, "createSetup", Modifier.PUBLIC, "String"); //NOI18N
958
// createSetup.setBodyText("this." + fieldName + " = new " + entityReferenceName + "();\n return \"" + fieldName + "_create\";"); //NOI18N
959
// javaClass.getFeatures().add(createSetup);
960
//
961
// String BEGIN = isInjection ? "utx.begin();" : "em.getTransaction().begin();";
962
// String COMMIT = isInjection ? "utx.commit();" : "em.getTransaction().commit();";
963
// String ROLLBACK = isInjection ? "utx.rollback();" : "em.getTransaction().rollback();";
964
//
965
// Method create = JMIGenerationUtil.createMethod(javaClass, "create", Modifier.PUBLIC, "String"); //NOI18N
966
// create.setBodyText("EntityManager em = getEntityManager();\n"
967
// + "try {\n " + BEGIN + "\n em.persist(" + fieldName + ");\n" + updateRelatedInCreate.toString() + COMMIT + "\n" //NOI18N
968
// + "addSuccessMessage(\"" + simpleEntityName + " was successfully created.\");\n" //NOI18N
969
// + "} catch (Exception ex) {\n try {\n addErrorMessage(ex.getLocalizedMessage());\n" + ROLLBACK + "\n } catch (Exception e) {\n addErrorMessage(e.getLocalizedMessage());\n}\n } " //NOI18N
970
// + "finally {\n em.close();\n }\n"
971
// + "return \"" + fieldName + "_list\";");
972
// javaClass.getFeatures().add(create);
973
//
974
// String setFromReqParamMethod = "set" + simpleEntityName + "FromRequestParam";
975
// String getFromReqParamMethod = "get" + simpleEntityName + "FromRequestParam";
976
//
977
// Method showSetup = JMIGenerationUtil.createMethod(javaClass, "detailSetup", Modifier.PUBLIC, "String"); //NOI18N
978
// showSetup.setBodyText(setFromReqParamMethod + "();\n return \"" + fieldName + "_detail\";"); //NOI18N
979
// javaClass.getFeatures().add(showSetup);
980
//
981
// Method editSetup = JMIGenerationUtil.createMethod(javaClass, "editSetup", Modifier.PUBLIC, "String"); //NOI18N
982
// editSetup.setBodyText(setFromReqParamMethod + "();\n return \"" + fieldName + "_edit\";"); //NOI18N
983
// javaClass.getFeatures().add(editSetup);
984
//
985
// Method edit = JMIGenerationUtil.createMethod(javaClass, "edit", Modifier.PUBLIC, "String"); //NOI18N
986
// edit.setBodyText("EntityManager em = getEntityManager();\n"
987
// + "try {\n " + BEGIN + "\n" + updateRelatedInEditPre.toString()
988
// + fieldName + " = em.merge(" + fieldName + ");\n "
989
// + updateRelatedInEditPost.toString() + COMMIT + "\n" //NOI18N
990
// + "addSuccessMessage(\"" + simpleEntityName + " was successfully updated.\");\n" //NOI18N
991
// + "} catch (Exception ex) {\n try {\n addErrorMessage(ex.getLocalizedMessage());\n" + ROLLBACK + "\n } catch (Exception e) {\n addErrorMessage(e.getLocalizedMessage());\n}\n} " //NOI18N
992
// + "finally {\n em.close();\n }\n" //NOI18N
993
// + "return \"" + fieldName + "_list\";"); //NOI18N
994
// javaClass.getFeatures().add(edit);
995
//
996
//
997
// Method destroy = JMIGenerationUtil.createMethod(javaClass, "destroy", Modifier.PUBLIC, "String"); //NOI18N
998
// destroy.setBodyText("EntityManager em = getEntityManager();\n"
999
// + "try {\n " + BEGIN + "\n" + entityReferenceName + " " + fieldName + " = " + getFromReqParamMethod + "();\n"
1000
// + fieldName + " = em.merge(" + fieldName + ");\n" + updateRelatedInDestroy.toString()
1001
// + "em.remove(" + fieldName + ");\n " + COMMIT + "\n" //NOI18N
1002
// + "addSuccessMessage(\"" + simpleEntityName + " was successfully deleted.\");\n" //NOI18N
1003
// + "} catch (Exception ex) {\n try {\n addErrorMessage(ex.getLocalizedMessage());\n" + ROLLBACK + "\n } catch (Exception e) {\n addErrorMessage(e.getLocalizedMessage());\n}\n} " //NOI18N
1004
// + "finally {\n em.close();\n }\n" //NOI18N
1005
// + "return \"" + fieldName + "_list\";"); //NOI18N
1006
// javaClass.getFeatures().add(destroy);
1007
//
1008
// String idField = createIdFieldDeclaration(idPropertyType, "param");
1009
//
1010
// JMIGenerationUtil.createImport(javaClass, "javax.faces.context.FacesContext");
1011
// JMIGenerationUtil.createImport(javaClass, "javax.faces.application.FacesMessage");
1012
// Method getFromReq = JMIGenerationUtil.createMethod(javaClass, getFromReqParamMethod, Modifier.PUBLIC, entityClass); //NOI18N
1013
// JavaClass idClass = null;
1014
// Type idType = JMIUtils.resolveType(idPropertyType);
1015
// if (idType instanceof JavaClass) {
1016
// idClass = (JavaClass) idType;
1017
// }
1018
// boolean embeddable = idClass != null && JsfForm.isEmbeddableClass(idClass);
1019
// getFromReq.setBodyText("EntityManager em = getEntityManager();\n try{\n"
1020
// + entityReferenceName + " o = (" + entityReferenceName +") model.getRowData();\n"
1021
// + "o = em.merge(o);\n"
1022
// + "return o;\n"
1023
// + "} finally {\n em.close();\n}\n");
1024
// javaClass.getFeatures().add(getFromReq);
1025
//
1026
// Method setFromReq = JMIGenerationUtil.createMethod(javaClass, setFromReqParamMethod, Modifier.PUBLIC, "void"); //NOI18N
1027
// setFromReq.setBodyText(entityReferenceName + " " + fieldName + " = " + getFromReqParamMethod + "();\n" //NOI18N
1028
// + "set" + simpleEntityName + "(" + fieldName + ");"); //NOI18N
1029
// javaClass.getFeatures().add(setFromReq);
1030
//
1031
// Method getEntities = JMIGenerationUtil.createMethod(javaClass, "get" + simpleEntityName + "s", Modifier.PUBLIC, dmReference.getName()); //NOI18N
1032
// JMIGenerationUtil.createImport(javaClass, "javax.persistence.Query");
1033
// getEntities.setBodyText("EntityManager em = getEntityManager();\n try{\n"
1034
// + "Query q = em.createQuery(\"select object(o) from " + simpleEntityName +" as o\");\n"
1035
// + "q.setMaxResults(batchSize);\n"
1036
// + "q.setFirstResult(firstItem);\n"
1037
// + "model = new " + ldmReference.getName() + "(q.getResultList());\n"
1038
// + "return model;\n" //NOI18N
1039
// + "} finally {\n em.close();\n}\n");
1040
// javaClass.getFeatures().add(getEntities);
1041
//
1042
// Method addErrorMessage = JMIGenerationUtil.createMethod(javaClass, "addErrorMessage", Modifier.PUBLIC + Modifier.STATIC, "void"); //NOI18N
1043
// addErrorMessage.setBodyText("FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);\n" //NOI18N
1044
// + "FacesContext fc = FacesContext.getCurrentInstance();\n" //NOI18N
1045
// + "fc.addMessage(null, facesMsg);"); //NOI18N
1046
// Parameter msgParameter = JMIGenerationUtil.createParameter(javaClass, "msg", "String");
1047
// addErrorMessage.getParameters().add(msgParameter);
1048
// javaClass.getFeatures().add(addErrorMessage);
1049
//
1050
// Method addSuccessMessage = JMIGenerationUtil.createMethod(javaClass, "addSuccessMessage", Modifier.PUBLIC + Modifier.STATIC, "void"); //NOI18N
1051
// addSuccessMessage.setBodyText("FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);\n" //NOI18N
1052
// + "FacesContext fc = FacesContext.getCurrentInstance();\n" //NOI18N
1053
// + "fc.addMessage(\"successInfo\", facesMsg);"); //NOI18N
1054
// Parameter successMsgParameter = JMIGenerationUtil.createParameter(javaClass, "msg", "String");
1055
// addSuccessMessage.getParameters().add(successMsgParameter);
1056
// javaClass.getFeatures().add(addSuccessMessage);
1057
//
1058
// //getter for converter
1059
// Method findById = JMIGenerationUtil.createMethod(javaClass, "find" + simpleEntityName, Modifier.PUBLIC, entityClass); //NOI18N
1060
// findById.setBodyText("EntityManager em = getEntityManager();\n try{\n"
1061
// + entityReferenceName + " o = (" + entityReferenceName + ") em.find(" + entityReferenceName + ".class, id);\n"
1062
// + "return o;\n"
1063
// + "} finally {\n em.close();\n}\n");
1064
// Parameter idParameter = JMIGenerationUtil.createParameter(javaClass, "id", idPropertyType);
1065
// findById.getParameters().add(idParameter);
1066
// javaClass.getFeatures().add(findById);
1067
//
1068
// // <editor-fold desc=" toOne relations ">
1069
// for(Iterator it = toOneRelMethods.iterator(); it.hasNext();) {
1070
// Method m = (Method) it.next();
1071
// String relType = m.getType().getName();
1072
// String simpleRelType = simpleClassName(relType);
1073
//
1074
// String methodName = m.getName() + "s";
1075
// //make sure we do not generate >1 getter for each type
1076
// boolean alredyGenerated = false;
1077
// for (Iterator it2 = javaClass.getFeatures().iterator(); it2.hasNext();) {
1078
// Feature f = (Feature) it2.next();
1079
// if (methodName.equals(f.getName())) {
1080
// alredyGenerated = true;
1081
// break;
1082
// }
1083
// }
1084
//
1085
// if (!alredyGenerated) {
1086
// Method selectItems = JMIGenerationUtil.createMethodArray(javaClass, methodName, Modifier.PUBLIC, "javax.faces.model.SelectItem"); //NOI18N
1087
// JMIGenerationUtil.createImport(javaClass, "javax.faces.model.SelectItem"); //NOI18N
1088
// JMIGenerationUtil.createImport(javaClass, "java.util.List"); //NOI18N
1089
// String relTypeReference = JMIGenerationUtil.createImport(javaClass, relType).getName();
1090
// selectItems.setBodyText("EntityManager em = getEntityManager();\n try{\n"
1091
// + "List <" + relTypeReference + "> l = (List <" + relTypeReference +">) em.createQuery(\"select o from " + simpleRelType + " as o\").getResultList();\n"
1092
// + "SelectItem select[] = new SelectItem[l.size()];\n"
1093
// + "int i = 0;\n for(" + relTypeReference + " x : l) {\n"
1094
// + "select[i++] = new SelectItem(x);\n}\nreturn select;\n"
1095
// + "} finally {\n em.close();\n}\n");
1096
// javaClass.getFeatures().add(selectItems);
1097
// }
1098
// }
1099
// // </editor-fold>
1100
//
1101
// Method getItemCount = JMIGenerationUtil.createMethod(javaClass, "getItemCount", Modifier.PUBLIC, "int");
1102
// getItemCount.setBodyText("EntityManager em = getEntityManager();\n try{\n"
1103
// + "int count = ((Long) em.createQuery(\"select count(o) from " + simpleEntityName + " as o\").getSingleResult()).intValue();\n"
1104
// + "return count;\n"
1105
// + "} finally {\n em.close();\n}\n");
1106
// javaClass.getFeatures().add(getItemCount);
1107
//
1108
// Method getFirstItem = JMIGenerationUtil.createMethod(javaClass, "getFirstItem", Modifier.PUBLIC, "int");
1109
// getFirstItem.setBodyText("return firstItem;");
1110
// javaClass.getFeatures().add(getFirstItem);
1111
//
1112
// Method getLastItem = JMIGenerationUtil.createMethod(javaClass, "getLastItem", Modifier.PUBLIC, "int");
1113
// getLastItem.setBodyText("int size = getItemCount();\n return firstItem + batchSize > size ? size : firstItem + batchSize;\n");
1114
// javaClass.getFeatures().add(getLastItem);
1115
//
1116
// Method getBatchSize = JMIGenerationUtil.createMethod(javaClass, "getBatchSize", Modifier.PUBLIC, "int");
1117
// getBatchSize.setBodyText("return batchSize;");
1118
// javaClass.getFeatures().add(getBatchSize);
1119
//
1120
// Method next = JMIGenerationUtil.createMethod(javaClass, "next", Modifier.PUBLIC, "String");
1121
// next.setBodyText("if (firstItem + batchSize < getItemCount()) {\n"
1122
// + "firstItem += batchSize;\n}\n"
1123
// + "return \"" + fieldName + "_list\";\n");
1124
// javaClass.getFeatures().add(next);
1125
//
1126
// Method prev = JMIGenerationUtil.createMethod(javaClass, "prev", Modifier.PUBLIC, "String");
1127
// prev.setBodyText("firstItem -= batchSize;\n if (firstItem < 0) {\nfirstItem = 0;\n}\n"
1128
// + "return \"" + fieldName + "_list\";\n");
1129
// javaClass.getFeatures().add(prev);
1130
//
1131
// rollback = false;
1132
// } catch (Exception e) {
1133
// e.printStackTrace();
1134
// } finally {
1135
// JavaModel.getJavaRepository().endTrans(rollback);
1136
// }
1137
// return javaClass;
1138
// }
1139

1140    private static HashSet JavaDoc<String JavaDoc> CONVERTED_TYPES = new HashSet JavaDoc<String JavaDoc>();
1141    static {
1142        CONVERTED_TYPES.add("Boolean");
1143        CONVERTED_TYPES.add("Byte");
1144        CONVERTED_TYPES.add("Double");
1145        CONVERTED_TYPES.add("Float");
1146        CONVERTED_TYPES.add("Integer");
1147        CONVERTED_TYPES.add("Long");
1148        CONVERTED_TYPES.add("Short");
1149        CONVERTED_TYPES.add("StringBuffer");
1150    }
1151    private static HashMap JavaDoc<String JavaDoc,String JavaDoc> PRIMITIVE_TYPES = new HashMap JavaDoc<String JavaDoc, String JavaDoc>();
1152    static {
1153        PRIMITIVE_TYPES.put("boolean", "Boolean");
1154        PRIMITIVE_TYPES.put("byte", "Byte");
1155        PRIMITIVE_TYPES.put("double", "Double");
1156        PRIMITIVE_TYPES.put("float", "Float");
1157        PRIMITIVE_TYPES.put("int", "Integer");
1158        PRIMITIVE_TYPES.put("long", "Long");
1159        PRIMITIVE_TYPES.put("short", "Short");
1160    }
1161    
1162    /** @param valueVar is name of a String variable */
1163    private static String JavaDoc createIdFieldDeclaration(String JavaDoc idPropertyType, String JavaDoc valueVar) {
1164        String JavaDoc idField;
1165        if (idPropertyType.startsWith("java.lang.")) {
1166            String JavaDoc shortName = idPropertyType.substring(10);
1167            idField = shortName + " id = " + createIdFieldInitialization(idPropertyType, valueVar) + ";";
1168        } else if (idPropertyType.equals("java.math.BigInteger") || "BigInteger".equals(idPropertyType)) {
1169            idField = "java.math.BigInteger id = " + createIdFieldInitialization(idPropertyType, valueVar) + ";";
1170        } else if (idPropertyType.equals("java.math.BigDecimal") || "BigDecimal".equals(idPropertyType)) {
1171            idField = "java.math.BigDecimal id = " + createIdFieldInitialization(idPropertyType, valueVar) + ";";
1172        } else {
1173            idField = idPropertyType + " id = " + createIdFieldInitialization(idPropertyType, valueVar) + ";";
1174        }
1175        return idField;
1176    }
1177    
1178    /** @param valueVar is name of a String variable */
1179    private static String JavaDoc createIdFieldInitialization(String JavaDoc idPropertyType, String JavaDoc valueVar) {
1180        String JavaDoc idField;
1181        //PENDING cannot assume that key type is Integer, Long, String, int or long
1182
if ("char".equals(idPropertyType)) {
1183            idField = valueVar + ".charAt(0);";
1184        } else if (PRIMITIVE_TYPES.containsKey(idPropertyType)) {
1185            String JavaDoc objectType = PRIMITIVE_TYPES.get(idPropertyType);
1186            String JavaDoc methodName = "parse" + idPropertyType.substring(0,1).toUpperCase() + idPropertyType.substring(1);
1187            idField = objectType + "." + methodName + "(" + valueVar + ")";
1188        } else if (idPropertyType.equals("java.math.BigInteger") || "BigInteger".equals(idPropertyType)) {
1189            idField = "new java.math.BigInteger(" + valueVar + ")";
1190        } else if (idPropertyType.equals("java.math.BigDecimal") || "BigDecimal".equals(idPropertyType)) {
1191            idField = "new java.math.BigDecimal(" + valueVar + ")";
1192        } else if (idPropertyType.equals("java.lang.String") || "String".equals(idPropertyType)) {
1193            idField = valueVar;
1194        } else if (idPropertyType.startsWith("java.lang.")) {
1195            String JavaDoc shortName = idPropertyType.substring(10);
1196            idField = "new " + shortName + "(" + valueVar + ")";
1197        } else if (CONVERTED_TYPES.contains(idPropertyType)) {
1198            idField = "new " + idPropertyType + "(" + valueVar + ")";
1199        } else {
1200            idField = "(" + idPropertyType + ") FacesContext.getCurrentInstance().getApplication().\n"
1201                    + "createConverter(" + idPropertyType + ".class).getAsObject(FacesContext.\n"
1202                    + "getCurrentInstance(), null, " + valueVar + ")";
1203        }
1204        return idField;
1205    }
1206    
1207    public static String JavaDoc simpleClassName(String JavaDoc fqn) {
1208        int lastDot = fqn.lastIndexOf('.');
1209        return lastDot > 0 ? fqn.substring(lastDot + 1) : fqn;
1210    }
1211
1212    public static String JavaDoc fieldFromClassName(String JavaDoc className) {
1213        boolean makeFirstLower = className.length() == 1 || (!Character.isUpperCase(className.charAt(1)));
1214        String JavaDoc candidate = makeFirstLower ? className.substring(0,1).toLowerCase() + className.substring(1) : className;
1215        if (!Utilities.isJavaIdentifier(candidate)) {
1216            candidate += "1"; //NOI18N
1217
}
1218        return candidate;
1219    }
1220    
1221    public static String JavaDoc getManagedBeanName(String JavaDoc simpleEntityName) {
1222        int len = simpleEntityName.length();
1223        return len > 1 ? simpleEntityName.substring(0,1).toLowerCase() + simpleEntityName.substring(1) : simpleEntityName.toLowerCase();
1224    }
1225    
1226    public static String JavaDoc getPropNameFromMethod(String JavaDoc name) {
1227        //getABcd should be converted to ABcd, getFooBar should become fooBar
1228
//getA1 is "a1", getA_ is a_, getAB is AB
1229
boolean makeFirstLower = name.length() < 5 || (!Character.isUpperCase(name.charAt(4)));
1230        return makeFirstLower ? name.substring(3,4).toLowerCase() + name.substring(4) : name.substring(3);
1231    }
1232}
1233
Popular Tags