/
FacesScaffoldProvider.java
1054 lines (921 loc) · 44.2 KB
/
FacesScaffoldProvider.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
*/
package org.jboss.forge.addon.scaffold.faces;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.persistence.CascadeType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import org.jboss.forge.addon.configuration.Configuration;
import org.jboss.forge.addon.dependencies.Dependency;
import org.jboss.forge.addon.dependencies.builder.DependencyBuilder;
import org.jboss.forge.addon.facets.FacetNotFoundException;
import org.jboss.forge.addon.javaee.cdi.CDIFacet;
import org.jboss.forge.addon.javaee.cdi.ui.CDISetupCommand;
import org.jboss.forge.addon.javaee.ejb.EJBFacet;
import org.jboss.forge.addon.javaee.ejb.ui.EJBSetupWizard;
import org.jboss.forge.addon.javaee.faces.FacesFacet;
import org.jboss.forge.addon.javaee.faces.ui.FacesSetupWizard;
import org.jboss.forge.addon.javaee.jpa.JPAFacet;
import org.jboss.forge.addon.javaee.jpa.ui.setup.JPASetupWizard;
import org.jboss.forge.addon.javaee.servlet.ServletFacet;
import org.jboss.forge.addon.javaee.servlet.ServletFacet_3_0;
import org.jboss.forge.addon.javaee.servlet.ServletFacet_3_1;
import org.jboss.forge.addon.javaee.servlet.ui.ServletSetupWizard;
import org.jboss.forge.addon.parser.java.facets.JavaSourceFacet;
import org.jboss.forge.addon.parser.java.resources.JavaResource;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.facets.DependencyFacet;
import org.jboss.forge.addon.projects.facets.WebResourcesFacet;
import org.jboss.forge.addon.resource.FileResource;
import org.jboss.forge.addon.resource.Resource;
import org.jboss.forge.addon.resource.ResourceFilter;
import org.jboss.forge.addon.scaffold.faces.freemarker.FreemarkerTemplateProcessor;
import org.jboss.forge.addon.scaffold.faces.metawidget.config.ForgeConfigReader;
import org.jboss.forge.addon.scaffold.spi.AccessStrategy;
import org.jboss.forge.addon.scaffold.spi.ScaffoldGenerationContext;
import org.jboss.forge.addon.scaffold.spi.ScaffoldProvider;
import org.jboss.forge.addon.scaffold.spi.ScaffoldSetupContext;
import org.jboss.forge.addon.scaffold.ui.ScaffoldSetupWizard;
import org.jboss.forge.addon.scaffold.util.ScaffoldUtil;
import org.jboss.forge.addon.ui.command.UICommand;
import org.jboss.forge.addon.ui.result.NavigationResult;
import org.jboss.forge.addon.ui.result.navigation.NavigationResultBuilder;
import org.jboss.forge.addon.ui.util.Metadata;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.Field;
import org.jboss.forge.roaster.model.source.AnnotationSource;
import org.jboss.forge.roaster.model.source.FieldSource;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.JavaSource;
import org.jboss.forge.roaster.model.source.MemberSource;
import org.jboss.forge.roaster.model.source.MethodSource;
import org.jboss.shrinkwrap.descriptor.api.javaee6.ParamValueType;
import org.jboss.shrinkwrap.descriptor.api.persistence.PersistenceCommonDescriptor;
import org.jboss.shrinkwrap.descriptor.api.webapp30.WebAppDescriptor;
import org.jboss.shrinkwrap.descriptor.spi.node.Node;
import org.jboss.shrinkwrap.descriptor.spi.node.NodeDescriptor;
import org.metawidget.statically.StaticMetawidget;
import org.metawidget.statically.StaticUtils.IndentedWriter;
import org.metawidget.statically.StaticWidget;
import org.metawidget.statically.faces.StaticFacesUtils;
import org.metawidget.statically.faces.component.html.StaticHtmlMetawidget;
import org.metawidget.statically.faces.component.html.widgetbuilder.HtmlOutcomeTargetLink;
import org.metawidget.statically.faces.component.html.widgetbuilder.ReadOnlyWidgetBuilder;
import org.metawidget.statically.faces.component.html.widgetbuilder.richfaces.RichFacesWidgetBuilder;
import org.metawidget.statically.html.widgetbuilder.HtmlTag;
import org.metawidget.statically.javacode.StaticJavaMetawidget;
import org.metawidget.util.ArrayUtils;
import org.metawidget.util.CollectionUtils;
import org.metawidget.util.XmlUtils;
import org.metawidget.util.simple.StringUtils;
import org.metawidget.widgetbuilder.composite.CompositeWidgetBuilder;
import org.metawidget.widgetbuilder.composite.CompositeWidgetBuilderConfig;
import org.metawidget.widgetbuilder.iface.WidgetBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import freemarker.template.Template;
/**
* The scaffold provider for JSF 2.0
*/
public class FacesScaffoldProvider implements ScaffoldProvider
{
private static final String JBOSS_COMMUNITY_PNG = "/resources/jboss-community.png";
private static final String SCAFFOLD_JBOSS_COMMUNITY_PNG = "/scaffold/faces/jboss-community.png";
private static final String TRUE_PNG = "/resources/true.png";
private static final String SCAFFOLD_TRUE_PNG = "/scaffold/faces/true.png";
private static final String SEARCH_PNG = "/resources/search.png";
private static final String SCAFFOLD_SEARCH_PNG = "/scaffold/faces/search.png";
private static final String REMOVE_PNG = "/resources/remove.png";
private static final String SCAFFOLD_REMOVE_PNG = "/scaffold/faces/remove.png";
private static final String FORGE_STYLE_CSS = "/resources/forge-style.css";
private static final String SCAFFOLD_FORGE_STYLE_CSS = "/scaffold/faces/forge-style.css";
private static final String FORGE_LOGO_PNG = "/resources/forge-logo.png";
private static final String SCAFFOLD_FORGE_LOGO_PNG = "/scaffold/faces/forge-logo.png";
private static final String FAVICON_ICO = "/resources/favicon.ico";
private static final String SCAFFOLD_FAVICON_ICO = "/scaffold/faces/favicon.ico";
private static final String FALSE_PNG = "/resources/false.png";
private static final String SCAFFOLD_FALSE_PNG = "/scaffold/faces/false.png";
private static final String BOOTSTRAP_CSS = "/resources/bootstrap.css";
private static final String SCAFFOLD_BOOTSTRAP_CSS = "/scaffold/faces/bootstrap.css";
private static final String ADD_PNG = "/resources/add.png";
private static final String SCAFFOLD_ADD_PNG = "/scaffold/faces/add.png";
private static final String ERROR_XHTML = "error.xhtml";
private static final String XMLNS_PREFIX = "xmlns:";
private static final String BACKING_BEAN_TEMPLATE = "scaffold/faces/BackingBean.jv";
private static final String VIEW_UTILS_TEMPLATE = "scaffold/faces/ViewUtils.jv";
private static final String TAGLIB_TEMPLATE = "scaffold/faces/forge.taglib.xml";
private static final String VIEW_TEMPLATE = "scaffold/faces/view.xhtml";
private static final String CREATE_TEMPLATE = "scaffold/faces/create.xhtml";
private static final String SEARCH_TEMPLATE = "scaffold/faces/search.xhtml";
private static final String NAVIGATION_TEMPLATE = "scaffold/faces/pageTemplate.xhtml";
private static final String SCAFFOLD_NAVIGATION_TEMPLATE = "/resources/scaffold/pageTemplate.xhtml";
private static final String ERROR_TEMPLATE = "scaffold/faces/error.xhtml";
private static final String INDEX_TEMPLATE = "scaffold/faces/index.xhtml";
private static final String INDEX_HTML_TEMPLATE = "scaffold/faces/index.html";
private static final String INDEX_XHTML = "/index.xhtml";
private static final String INDEX_HTML = "/index.html";
private static final String SCAFFOLD_META_WIDGET_REMOVE_ENTITY = "scaffold/faces/metawidget-remove-entity.xml";
private static final String SCAFFOLD_META_WIDGET_ENTITY = "scaffold/faces/metawidget-entity.xml";
private static final String SCAFFOLD_META_WIDGET_SEARCH = "scaffold/faces/metawidget-search.xml";
private static final String SCAFFOLD_META_WIDGET_BEAN = "scaffold/faces/metawidget-bean.xml";
private static final String SCAFFOLD_META_WIDGET_QBE = "scaffold/faces/metawidget-qbe.xml";
private static final String PAGINATOR = "/resources/scaffold/paginator.xhtml";
private static final String SCAFFOLD_PAGINATOR = "/scaffold/faces/paginator.xhtml";
private final Dependency richfaces3UI = DependencyBuilder.create("org.richfaces.ui:richfaces-ui");
private final Dependency richfaces3Impl = DependencyBuilder.create("org.richfaces.framework:richfaces-impl");
private final Dependency richfaces4UI = DependencyBuilder.create("org.richfaces.ui:richfaces-components-ui");
private final Dependency richfaces4Impl = DependencyBuilder.create("org.richfaces.core:richfaces-core-impl");
protected FreemarkerTemplateProcessor templateProcessor;
protected Template backingBeanTemplate;
protected int backingBeanTemplateQbeMetawidgetIndent;
protected int backingBeanTemplateRmEntityMetawidgetIndent;
protected Template viewUtilsTemplate;
protected Template taglibTemplate;
protected Template viewTemplate;
protected Map<String, String> viewTemplateNamespaces;
protected int viewTemplateEntityMetawidgetIndent;
protected Template createTemplate;
protected Map<String, String> createTemplateNamespaces;
protected int createTemplateEntityMetawidgetIndent;
protected Template searchTemplate;
protected Map<String, String> searchTemplateNamespaces;
protected int searchTemplateSearchMetawidgetIndent;
protected int searchTemplateBeanMetawidgetIndent;
protected Template navigationTemplate;
protected int navigationTemplateIndent;
protected Template errorTemplate;
protected Template indexWelcomeTemplate;
protected Template indexTemplate;
protected StaticHtmlMetawidget entityMetawidget;
protected StaticHtmlMetawidget searchMetawidget;
protected StaticHtmlMetawidget beanMetawidget;
protected StaticJavaMetawidget qbeMetawidget;
protected StaticJavaMetawidget rmEntityMetawidget;
private Configuration config;
private Project project;
@Inject
public FacesScaffoldProvider(final Configuration config, final FreemarkerTemplateProcessor templateProcessor)
{
this.config = config;
this.templateProcessor = templateProcessor;
}
public void setProject(Project project)
{
this.project = project;
resetMetaWidgets();
}
@Override
public String getName()
{
return "Faces";
}
@Override
public String getDescription()
{
return "Scaffold a Faces project from JPA entities";
}
@Override
public List<Resource<?>> setup(Project project, ScaffoldSetupContext setupContext)
{
setProject(project);
String targetDir = setupContext.getTargetDirectory();
boolean overwrite = setupContext.isOverwrite();
Resource<?> template = null;
List<Resource<?>> resources = generateIndex(targetDir, template, overwrite);
setupWebXML();
return resources;
}
@Override
public boolean isSetup(ScaffoldSetupContext setupContext)
{
WebResourcesFacet web = project.getFacet(WebResourcesFacet.class);
String targetDir = setupContext.getTargetDirectory();
FileResource<?> indexFacelet = web.getWebResource(targetDir + INDEX_XHTML);
FileResource<?> indexPage = web.getWebResource(targetDir + INDEX_HTML);
if (indexFacelet.exists() && indexPage.exists())
{
return true;
}
return false;
}
@Override
public List<Resource<?>> generateFrom(Project project, ScaffoldGenerationContext generationContext)
{
setProject(project);
List<Resource<?>> generatedResources = new ArrayList<Resource<?>>();
Collection<?> resources = generationContext.getResources();
for (Object resource : resources)
{
JavaSource<?> javaSource = null;
if (resource instanceof JavaResource)
{
JavaResource javaResource = (JavaResource) resource;
try
{
javaSource = javaResource.getJavaType();
}
catch (FileNotFoundException fileEx)
{
throw new IllegalStateException(fileEx);
}
}
else
{
continue;
}
JavaClassSource entity = (JavaClassSource) javaSource;
String targetDir = generationContext.getTargetDirectory();
targetDir = (targetDir == null) ? "" : targetDir;
Resource<?> template = (Resource<?>) generationContext.getAttribute("pageTemplate");
boolean overwrite = generationContext.isOverwrite();
List<Resource<?>> generatedResourcesForEntity = this
.generateFromEntity(targetDir, template, entity, overwrite);
// TODO give plugins a chance to react to generated resources, use event bus?
// if (!generatedResources.isEmpty())
// {
// generatedEvent.fire(new ScaffoldGeneratedResources(provider, prepareResources(generatedResources)));
// }
generatedResources.addAll(generatedResourcesForEntity);
}
return generatedResources;
}
@Override
public NavigationResult getSetupFlow(Project project)
{
NavigationResultBuilder builder = NavigationResultBuilder.create();
List<Class<? extends UICommand>> setupCommands = new ArrayList<Class<? extends UICommand>>();
if (!project.hasFacet(JPAFacet.class))
{
builder.add(JPASetupWizard.class);
}
if (!project.hasFacet(CDIFacet.class))
{
setupCommands.add(CDISetupCommand.class);
}
if (!project.hasFacet(EJBFacet.class))
{
setupCommands.add(EJBSetupWizard.class);
}
if (!project.hasFacet(ServletFacet.class))
{
// TODO: FORGE-1296. Ensure that this wizard only sets up Servlet 3.0+
setupCommands.add(ServletSetupWizard.class);
}
if (!project.hasFacet(FacesFacet.class))
{
setupCommands.add(FacesSetupWizard.class);
}
Metadata compositeSetupMetadata = Metadata.forCommand(ScaffoldSetupWizard.class)
.name("Setup Facets")
.description("Setup all dependent facets for the Faces scaffold.");
builder.add(compositeSetupMetadata, setupCommands);
return builder.build();
}
@Override
public NavigationResult getGenerationFlow(Project project)
{
NavigationResultBuilder builder = NavigationResultBuilder.create();
builder.add(ScaffoldableEntitySelectionWizard.class);
return builder.build();
}
protected List<Resource<?>> generateIndex(String targetDir, final Resource<?> template, final boolean overwrite)
{
List<Resource<?>> result = new ArrayList<Resource<?>>();
WebResourcesFacet web = this.project.getFacet(WebResourcesFacet.class);
ServletFacet servlet = this.project.getFacet(ServletFacet.class);
if (servlet instanceof ServletFacet_3_0)
{
WebAppDescriptor servletConfig = (WebAppDescriptor) servlet.getConfig();
servletConfig.getOrCreateWelcomeFileList().welcomeFile(INDEX_HTML);
}
else if (servlet instanceof ServletFacet_3_1)
{
org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor servletConfig = (org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor) servlet
.getConfig();
servletConfig.getOrCreateWelcomeFileList().welcomeFile(INDEX_HTML);
}
loadTemplates();
generateTemplates(targetDir, overwrite);
HashMap<Object, Object> context = getTemplateContext(targetDir, template);
// Basic pages
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(targetDir + INDEX_HTML),
this.templateProcessor.processTemplate(context, indexWelcomeTemplate), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(targetDir + INDEX_XHTML),
this.templateProcessor.processTemplate(context, indexTemplate), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(ERROR_XHTML),
this.templateProcessor.processTemplate(context, errorTemplate), overwrite));
// Static resources
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(ADD_PNG),
getClass().getResourceAsStream(SCAFFOLD_ADD_PNG), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(BOOTSTRAP_CSS),
getClass().getResourceAsStream(SCAFFOLD_BOOTSTRAP_CSS), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FALSE_PNG),
getClass().getResourceAsStream(SCAFFOLD_FALSE_PNG), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FAVICON_ICO),
getClass().getResourceAsStream(SCAFFOLD_FAVICON_ICO), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FORGE_LOGO_PNG),
getClass().getResourceAsStream(SCAFFOLD_FORGE_LOGO_PNG), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(FORGE_STYLE_CSS),
getClass().getResourceAsStream(SCAFFOLD_FORGE_STYLE_CSS), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(REMOVE_PNG),
getClass().getResourceAsStream(SCAFFOLD_REMOVE_PNG), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(SEARCH_PNG),
getClass().getResourceAsStream(SCAFFOLD_SEARCH_PNG), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(TRUE_PNG),
getClass().getResourceAsStream(SCAFFOLD_TRUE_PNG), overwrite));
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(JBOSS_COMMUNITY_PNG),
getClass().getResourceAsStream(SCAFFOLD_JBOSS_COMMUNITY_PNG), overwrite));
return result;
}
@Override
public AccessStrategy getAccessStrategy()
{
return new FacesAccessStrategy(this.project);
}
public TemplateStrategy getTemplateStrategy()
{
return new FacesTemplateStrategy(this.project);
}
protected List<Resource<?>> generateTemplates(String targetDir, final boolean overwrite)
{
List<Resource<?>> result = new ArrayList<Resource<?>>();
try
{
WebResourcesFacet web = this.project.getFacet(WebResourcesFacet.class);
result.add(ScaffoldUtil.createOrOverwrite(web.getWebResource(PAGINATOR),
getClass().getResourceAsStream(SCAFFOLD_PAGINATOR), overwrite));
result.add(generateNavigation(targetDir, overwrite));
}
catch (Exception e)
{
throw new RuntimeException("Error generating default templates", e);
}
return result;
}
protected void loadTemplates()
{
if (this.backingBeanTemplate == null)
{
this.backingBeanTemplate = this.templateProcessor.getTemplate(BACKING_BEAN_TEMPLATE);
String template = this.backingBeanTemplate.toString();
this.backingBeanTemplateQbeMetawidgetIndent = parseIndent(template, "${qbeMetawidget}");
this.backingBeanTemplateRmEntityMetawidgetIndent = parseIndent(template, "${rmEntityMetawidget}");
}
if (this.viewUtilsTemplate == null)
{
this.viewUtilsTemplate = this.templateProcessor.getTemplate(VIEW_UTILS_TEMPLATE);
}
if (this.taglibTemplate == null)
{
this.taglibTemplate = this.templateProcessor.getTemplate(TAGLIB_TEMPLATE);
}
if (this.viewTemplate == null)
{
this.viewTemplate = this.templateProcessor.getTemplate(VIEW_TEMPLATE);
String template = this.viewTemplate.toString();
this.viewTemplateNamespaces = parseNamespaces(template);
this.viewTemplateEntityMetawidgetIndent = parseIndent(template, "${metawidget}");
}
if (this.createTemplate == null)
{
this.createTemplate = this.templateProcessor.getTemplate(CREATE_TEMPLATE);
String template = this.createTemplate.toString();
this.createTemplateNamespaces = parseNamespaces(template);
this.createTemplateEntityMetawidgetIndent = parseIndent(template, "${metawidget}");
}
if (this.searchTemplate == null)
{
this.searchTemplate = this.templateProcessor.getTemplate(SEARCH_TEMPLATE);
String template = this.searchTemplate.toString();
this.searchTemplateNamespaces = parseNamespaces(template);
this.searchTemplateSearchMetawidgetIndent = parseIndent(template, "${searchMetawidget}");
this.searchTemplateBeanMetawidgetIndent = parseIndent(template, "${beanMetawidget}");
}
if (this.navigationTemplate == null)
{
this.navigationTemplate = this.templateProcessor.getTemplate(NAVIGATION_TEMPLATE);
String template = navigationTemplate.toString();
this.navigationTemplateIndent = parseIndent(template, "${navigation}");
}
if (this.errorTemplate == null)
{
this.errorTemplate = this.templateProcessor.getTemplate(ERROR_TEMPLATE);
}
if (this.indexTemplate == null)
{
this.indexTemplate = this.templateProcessor.getTemplate(INDEX_TEMPLATE);
}
if (this.indexWelcomeTemplate == null)
{
this.indexWelcomeTemplate = this.templateProcessor.getTemplate(INDEX_HTML_TEMPLATE);
}
}
protected HashMap<Object, Object> getTemplateContext(String targetDir, final Resource<?> template)
{
TemplateStrategy templateStrategy = getTemplateStrategy();
HashMap<Object, Object> context;
context = new HashMap<Object, Object>();
context.put("template", template);
context.put("templatePath",
templateStrategy.getReferencePath(template != null ? template : templateStrategy.getDefaultTemplate()));
context.put("templatePath", SCAFFOLD_NAVIGATION_TEMPLATE);
context.put("templateStrategy", templateStrategy);
context.put("targetDir", targetDir);
return context;
}
protected void setupWebXML()
{
WebResourcesFacet web = this.project.getFacet(WebResourcesFacet.class);
ServletFacet servlet = this.project.getFacet(ServletFacet.class);
if (servlet instanceof ServletFacet_3_0)
{
WebAppDescriptor servletConfig = (WebAppDescriptor) servlet.getConfig();
Node root = ((NodeDescriptor) servletConfig).getRootNode();
removeConflictingErrorPages(root);
// (prefer /faces/error.xhtml)
String errorLocation = getAccessStrategy().getWebPaths(web.getWebResource(ERROR_XHTML)).get(1);
servletConfig.createErrorPage().errorCode("404").location(errorLocation);
servletConfig.createErrorPage().errorCode("500").location(errorLocation);
// Use the server timezone since we accept dates in that timezone, and it makes sense to display them in the
// same
boolean found = false;
for (ParamValueType<WebAppDescriptor> contextParam : servletConfig.getAllContextParam())
{
if (contextParam.getParamName().equals("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE"))
{
found = true;
}
}
if (!found)
{
servletConfig.createContextParam()
.paramName("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE").paramValue("true");
}
servlet.saveConfig(servletConfig);
}
else if (servlet instanceof ServletFacet_3_1)
{
org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor servletConfig = (org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor) servlet
.getConfig();
// (prefer /faces/error.xhtml)
String errorLocation = getAccessStrategy().getWebPaths(web.getWebResource(ERROR_XHTML)).get(1);
servletConfig.createErrorPage().errorCode("404").location(errorLocation);
servletConfig.createErrorPage().errorCode("500").location(errorLocation);
// Use the server timezone since we accept dates in that timezone, and it makes sense to display them in the
// same
boolean found = false;
for (org.jboss.shrinkwrap.descriptor.api.javaee7.ParamValueType<org.jboss.shrinkwrap.descriptor.api.webapp31.WebAppDescriptor> contextParam : servletConfig
.getAllContextParam())
{
if (contextParam.getParamName().equals("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE"))
{
found = true;
}
}
if (!found)
{
servletConfig.createContextParam()
.paramName("javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE").paramValue("true");
}
servlet.saveConfig(servletConfig);
}
}
private void removeConflictingErrorPages(Node root)
{
List<Node> nodeList = root.get("error-page");
for (Node errorPage : nodeList)
{
String errorCode = errorPage.getTextValueForPatternName("error-code");
if (errorCode.equals("404") || errorCode.equals("500"))
{
// TODO: Prompt before removing? A prompt existed in Forge 1.
root.removeChild(errorPage);
}
}
}
/**
* Generates the navigation menu based on scaffolded entities.
*/
protected Resource<?> generateNavigation(final String targetDir, final boolean overwrite)
throws IOException
{
WebResourcesFacet web = this.project.getFacet(WebResourcesFacet.class);
HtmlTag unorderedList = new HtmlTag("ul");
ResourceFilter filter = new ResourceFilter()
{
@Override
public boolean accept(Resource<?> resource)
{
FileResource<?> file = (FileResource<?>) resource;
if (!file.isDirectory()
|| file.getName().equals("resources")
|| file.getName().equals("WEB-INF")
|| file.getName().equals("META-INF"))
{
return false;
}
return true;
}
};
for (Resource<?> resource : web.getWebResource(targetDir + "/").listResources(filter))
{
HtmlOutcomeTargetLink outcomeTargetLink = new HtmlOutcomeTargetLink();
String outcome = targetDir.isEmpty() || targetDir.startsWith("/") ? targetDir : "/" + targetDir;
outcomeTargetLink.putAttribute("outcome", outcome + "/" + resource.getName() + "/search");
outcomeTargetLink.setValue(StringUtils.uncamelCase(resource.getName()));
HtmlTag listItem = new HtmlTag("li");
listItem.getChildren().add(outcomeTargetLink);
unorderedList.getChildren().add(listItem);
}
Writer writer = new IndentedWriter(new StringWriter(), this.navigationTemplateIndent);
unorderedList.write(writer);
Map<Object, Object> context = CollectionUtils.newHashMap();
context.put("appName", StringUtils.uncamelCase(this.project.getRootDirectory().getName()));
context.put("navigation", writer.toString().trim());
context.put("targetDir", targetDir);
if (this.navigationTemplate == null)
{
loadTemplates();
}
try
{
return ScaffoldUtil.createOrOverwrite((FileResource<?>) getTemplateStrategy()
.getDefaultTemplate(),
this.templateProcessor.processTemplate(context, navigationTemplate),
true);
}
finally
{
writer.close();
}
}
/**
* Parses the given XML and determines what namespaces it already declares. These are later removed from the list of
* namespaces that Metawidget introduces.
*/
protected Map<String, String> parseNamespaces(final String template)
{
Map<String, String> namespaces = CollectionUtils.newHashMap();
Document document = XmlUtils.documentFromString(template);
Element element = document.getDocumentElement();
NamedNodeMap attributes = element.getAttributes();
for (int loop = 0, length = attributes.getLength(); loop < length; loop++)
{
org.w3c.dom.Node node = attributes.item(loop);
String nodeName = node.getNodeName();
int indexOf = nodeName.indexOf(XMLNS_PREFIX);
if (indexOf == -1)
{
continue;
}
namespaces.put(nodeName.substring(indexOf + XMLNS_PREFIX.length()), node.getNodeValue());
}
return namespaces;
}
/**
* Parses the given XML and determines the indent of the given String namespaces that Metawidget introduces.
*/
protected int parseIndent(final String template, final String indentOf)
{
int indent = 0;
int indexOf = template.indexOf(indentOf);
while ((indexOf >= 0) && (template.charAt(indexOf) != '\n'))
{
if (template.charAt(indexOf) == '\t')
{
indent++;
}
indexOf--;
}
return indent;
}
private void resetMetaWidgets()
{
ForgeConfigReader configReader = new ForgeConfigReader(this.config, this.project);
this.entityMetawidget = new StaticHtmlMetawidget();
this.entityMetawidget.setConfigReader(configReader);
this.entityMetawidget.setConfig(SCAFFOLD_META_WIDGET_ENTITY);
this.searchMetawidget = new StaticHtmlMetawidget();
this.searchMetawidget.setConfigReader(configReader);
this.searchMetawidget.setConfig(SCAFFOLD_META_WIDGET_SEARCH);
this.beanMetawidget = new StaticHtmlMetawidget();
this.beanMetawidget.setConfigReader(configReader);
this.beanMetawidget.setConfig(SCAFFOLD_META_WIDGET_BEAN);
this.qbeMetawidget = new StaticJavaMetawidget();
this.qbeMetawidget.setConfigReader(configReader);
this.qbeMetawidget.setConfig(SCAFFOLD_META_WIDGET_QBE);
this.rmEntityMetawidget = new StaticJavaMetawidget();
this.rmEntityMetawidget.setConfigReader(configReader);
this.rmEntityMetawidget.setConfig(SCAFFOLD_META_WIDGET_REMOVE_ENTITY);
}
private List<Resource<?>> generateFromEntity(String targetDir, final Resource<?> template,
final JavaClassSource entity,
final boolean overwrite)
{
resetMetaWidgets();
// FORGE-460: setupRichFaces during generateFromEntity, not during setup, as generally 'richfaces setup' is called
// *after* 'scaffold setup'
// TODO: Decide on whether to support Richfaces via the Faces scaffold
// setupRichFaces();
// Track the list of resources generated
List<Resource<?>> result = new ArrayList<Resource<?>>();
try
{
JavaSourceFacet java = this.project.getFacet(JavaSourceFacet.class);
WebResourcesFacet web = this.project.getFacet(WebResourcesFacet.class);
JPAFacet<PersistenceCommonDescriptor> jpa = this.project.getFacet(JPAFacet.class);
loadTemplates();
Map<Object, Object> context = CollectionUtils.newHashMap();
context.put("entity", entity);
String ccEntity = StringUtils.decapitalize(entity.getName());
context.put("ccEntity", ccEntity);
context.put("rmEntity", ccEntity + "ToDelete");
setPrimaryKeyMetaData(context, entity);
// Prepare qbeMetawidget
this.qbeMetawidget.setPath(entity.getQualifiedName());
StringWriter stringWriter = new StringWriter();
this.qbeMetawidget.write(stringWriter, this.backingBeanTemplateQbeMetawidgetIndent);
context.put("qbeMetawidget", stringWriter.toString().trim());
// Prepare removeEntityMetawidget
this.rmEntityMetawidget.setPath(entity.getQualifiedName());
stringWriter = new StringWriter();
this.rmEntityMetawidget.write(stringWriter, this.backingBeanTemplateRmEntityMetawidgetIndent);
context.put("rmEntityMetawidget", stringWriter.toString().trim());
// Prepare Java imports
Set<String> qbeMetawidgetImports = this.qbeMetawidget.getImports();
Set<String> rmEntityMetawidgetImports = this.rmEntityMetawidget.getImports();
Set<String> metawidgetImports = CollectionUtils.newHashSet();
metawidgetImports.addAll(qbeMetawidgetImports);
metawidgetImports.addAll(rmEntityMetawidgetImports);
metawidgetImports.remove(entity.getQualifiedName());
context.put("metawidgetImports",
CollectionUtils.toString(metawidgetImports, ";\r\nimport ", true, false));
// Prepare JPA Persistence Unit
context.put("persistenceUnitName", jpa.getConfig().getOrCreatePersistenceUnit().getName());
// Create the Backing Bean for this entity
JavaClassSource viewBean = Roaster.parse(JavaClassSource.class,
this.templateProcessor.processTemplate(context, this.backingBeanTemplate));
viewBean.setPackage(java.getBasePackage() + ".view");
result.add(ScaffoldUtil.createOrOverwrite(java.getJavaResource(viewBean), viewBean.toString(),
overwrite));
// Set new context for view generation
context = getTemplateContext(targetDir, template);
String beanName = StringUtils.decapitalize(viewBean.getName());
context.put("beanName", beanName);
context.put("ccEntity", ccEntity);
context.put("entityName", StringUtils.uncamelCase(entity.getName()));
setPrimaryKeyMetaData(context, entity);
// Prepare entityMetawidget
this.entityMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + "." + ccEntity));
this.entityMetawidget.setPath(entity.getQualifiedName());
this.entityMetawidget.setReadOnly(false);
this.entityMetawidget.setStyle(null);
// Generate create
writeEntityMetawidget(context, this.createTemplateEntityMetawidgetIndent, this.createTemplateNamespaces);
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource(targetDir + "/" + ccEntity + "/create.xhtml"),
this.templateProcessor.processTemplate(context, this.createTemplate),
overwrite));
// Generate view
this.entityMetawidget.setReadOnly(true);
writeEntityMetawidget(context, this.viewTemplateEntityMetawidgetIndent, this.viewTemplateNamespaces);
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource(targetDir + "/" + ccEntity + "/view.xhtml"),
this.templateProcessor.processTemplate(context, this.viewTemplate), overwrite));
// Generate search
this.searchMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + ".example"));
this.searchMetawidget.setPath(entity.getQualifiedName());
this.beanMetawidget.setValue(StaticFacesUtils.wrapExpression(beanName + ".pageItems"));
this.beanMetawidget.setPath(viewBean.getQualifiedName() + "/pageItems");
writeSearchAndBeanMetawidget(context, this.searchTemplateSearchMetawidgetIndent,
this.searchTemplateBeanMetawidgetIndent, this.searchTemplateNamespaces);
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource(targetDir + "/" + ccEntity + "/search.xhtml"),
this.templateProcessor.processTemplate(context, this.searchTemplate), overwrite));
// Generate navigation
result.add(generateNavigation(targetDir, overwrite));
// Need ViewUtils and forge.taglib.xml for forgeview:asList
JavaClassSource viewUtils = Roaster.parse(JavaClassSource.class,
this.templateProcessor.processTemplate(context, this.viewUtilsTemplate));
viewUtils.setPackage(viewBean.getPackage());
result.add(ScaffoldUtil.createOrOverwrite(java.getJavaResource(viewUtils), viewUtils.toString(),
true));
context.put("viewPackage", viewBean.getPackage());
result.add(ScaffoldUtil.createOrOverwrite(
web.getWebResource("WEB-INF/classes/META-INF/forge.taglib.xml"),
this.templateProcessor.processTemplate(context, this.taglibTemplate), true));
createInitializers(entity);
}
catch (Exception e)
{
throw new RuntimeException("Error generating default scaffolding: " + e.getMessage(), e);
}
return result;
}
/**
* Writes the entity Metawidget and its namespaces into the given context.
*/
protected void writeEntityMetawidget(final Map<Object, Object> context, final int entityMetawidgetIndent,
final Map<String, String> existingNamespaces)
{
StringWriter stringWriter = new StringWriter();
this.entityMetawidget.write(stringWriter, entityMetawidgetIndent);
context.put("metawidget", stringWriter.toString().trim());
Map<String, String> namespaces = this.entityMetawidget.getNamespaces();
namespaces.keySet().removeAll(existingNamespaces.keySet());
context.put("metawidgetNamespaces", namespacesToString(namespaces));
}
/**
* Writes the search Metawidget, the bean Metawidget and their namespaces into the given context.
*/
protected void writeSearchAndBeanMetawidget(final Map<Object, Object> context, final int searchMetawidgetIndent,
final int beanMetawidgetIndent,
final Map<String, String> existingNamespaces)
{
StringWriter stringWriter = new StringWriter();
this.searchMetawidget.write(stringWriter, searchMetawidgetIndent);
context.put("searchMetawidget", stringWriter.toString().trim());
stringWriter = new StringWriter();
this.beanMetawidget.write(stringWriter, beanMetawidgetIndent);
context.put("beanMetawidget", stringWriter.toString().trim());
Map<String, String> namespaces = this.searchMetawidget.getNamespaces();
namespaces.putAll(this.beanMetawidget.getNamespaces());
namespaces.keySet().removeAll(existingNamespaces.keySet());
context.put("metawidgetNamespaces", namespacesToString(namespaces));
}
protected String namespacesToString(final Map<String, String> namespaces)
{
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : namespaces.entrySet())
{
// At the start, break out of the current quote. Field must be in quotes so that we're valid XML
builder.append("\"\r\n\txmlns:");
builder.append(entry.getKey());
builder.append("=\"");
builder.append(entry.getValue());
}
return builder.toString();
}
protected void createInitializers(final JavaClassSource entity) throws FacetNotFoundException, FileNotFoundException
{
boolean dirtyBit = false;
for (FieldSource<JavaClassSource> field : entity.getFields())
{
if (field.hasAnnotation(OneToOne.class))
{
AnnotationSource<JavaClassSource> oneToOne = field.getAnnotation(OneToOne.class);
if (oneToOne.getStringValue("mappedBy") == null && oneToOne.getStringValue("cascade") == null)
{
oneToOne.setEnumValue("cascade", CascadeType.ALL);
dirtyBit = true;
}
String methodName = "new" + StringUtils.capitalize(field.getName());
if (!entity.hasMethodSignature(methodName))
{
entity.addMethod().setName(methodName).setReturnTypeVoid().setPublic()
.setBody("this." + field.getName() + " = new " + field.getType().getName() + "();");
dirtyBit = true;
}
}
}
for (MethodSource<JavaClassSource> method : entity.getMethods())
{
if (method.hasAnnotation(OneToOne.class))
{
AnnotationSource<JavaClassSource> oneToOne = method.getAnnotation(OneToOne.class);
if (oneToOne.getStringValue("mappedBy") == null && oneToOne.getStringValue("cascade") == null)
{
oneToOne.setEnumValue("cascade", CascadeType.ALL);
dirtyBit = true;
}
String fieldName = StringUtils.camelCase(method.getName().substring(3));
String methodName = "new" + StringUtils.capitalize(fieldName);
if (!entity.hasMethodSignature(methodName))
{
entity.addMethod().setName(methodName).setReturnTypeVoid().setPublic()
.setBody("this." + fieldName + " = new " + method.getReturnType().getName() + "();");
dirtyBit = true;
}
}
}
if (dirtyBit)
{
this.project.getFacet(JavaSourceFacet.class).saveJavaSource(entity);
}
}
private void setPrimaryKeyMetaData(Map<Object, Object> context, final JavaClassSource entity)
{
String pkName = "id";
String pkType = "Long";
String nullablePkType = "Long";
for (MemberSource<JavaClassSource, ?> m : entity.getMembers())
{
if (m.hasAnnotation(Id.class))
{
if (m instanceof Field)
{
Field<?> field = (Field<?>) m;
pkName = field.getName();
pkType = field.getType().getQualifiedName();
nullablePkType = pkType;
break;
}
MethodSource<?> method = (MethodSource<?>) m;
pkName = method.getName().substring(3);
if (method.getName().startsWith("get"))
{
pkType = method.getReturnType().getQualifiedName();
}
else
{
pkType = method.getParameters().get(0).getType().getQualifiedName();
}
nullablePkType = pkType;
break;
}
}
if ("int".equals(pkType))
{
nullablePkType = Integer.class.getSimpleName();
}
else if ("short".equals(pkType))
{
nullablePkType = Short.class.getSimpleName();
}
else if ("byte".equals(pkType))
{
nullablePkType = Byte.class.getSimpleName();
}
else if ("long".equals(pkType))
{
nullablePkType = Long.class.getSimpleName();
}
context.put("primaryKey", pkName);
context.put("primaryKeyCC", StringUtils.capitalize(pkName));
context.put("primaryKeyType", pkType);
context.put("nullablePrimaryKeyType", nullablePkType);
}
protected void setupRichFaces()
{
if ((this.project.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces3UI)
&& this.project.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces3Impl))
|| (this.project.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces4UI)
&& this.project.getFacet(DependencyFacet.class).hasEffectiveDependency(this.richfaces4Impl)))
{
this.entityMetawidget
.setWidgetBuilder(insertRichFacesWidgetBuilder((CompositeWidgetBuilder<StaticWidget, StaticMetawidget>) this.entityMetawidget
.getWidgetBuilder()));