-
Notifications
You must be signed in to change notification settings - Fork 43
/
UIInputContainer.java
452 lines (398 loc) · 17.6 KB
/
UIInputContainer.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
package org.jboss.seam.faces.component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.el.ValueExpression;
import javax.el.ValueReference;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.component.EditableValueHolder;
import javax.faces.component.FacesComponent;
import javax.faces.component.NamingContainer;
import javax.faces.component.UIComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.component.UIMessage;
import javax.faces.component.UINamingContainer;
import javax.faces.component.UIViewRoot;
import javax.faces.component.html.HtmlOutputLabel;
import javax.faces.context.FacesContext;
import javax.faces.validator.BeanValidator;
import javax.validation.Validation;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.metadata.BeanDescriptor;
import javax.validation.metadata.PropertyDescriptor;
/**
* <strong>UIInputContainer</strong> is a supplemental component for a JSF 2.0 composite component encapsulating one or more
* input components (<strong>EditableValueHolder</strong>), their corresponding message components (<strong>UIMessage</strong>)
* and a label (<strong>HtmlOutputLabel</strong>). This component takes care of wiring the label to the first input and the
* messages to each input in sequence. It also assigns two implicit attribute values, "required" and "invalid" to indicate that
* a required input field is present and whether there are any validation errors, respectively. To determine if a input field is
* required, both the required attribute is consulted and whether the property has Bean Validation constraints. Finally, if the
* "label" attribute is not provided on the composite component, the label value will be derived from the id of the composite
* component, for convenience.
* <p/>
* <p>
* Composite component definition example (minus layout):
* </p>
* <p/>
*
* <pre>
* <cc:interface componentType="org.jboss.seam.faces.InputContainer"/>
* <cc:implementation>
* <h:outputLabel id="label" value="#{cc.attrs.label}:" styleClass="#{cc.attrs.invalid ? 'invalid' : ''}">
* <h:ouputText styleClass="required" rendered="#{cc.attrs.required}" value="*"/>
* </h:outputLabel>
* <cc:insertChildren/>
* <h:message id="message" errorClass="invalid message" rendered="#{cc.attrs.invalid}"/>
* </cc:implementation>
* </pre>
* <p/>
* <p>
* Composite component usage example:
* </p>
* <p/>
*
* <pre>
* <example:inputContainer id="name">
* <h:inputText id="input" value="#{person.name}"/>
* </example:inputContainer>
* </pre>
* <p/>
* <p>
* Possible enhancements:
* </p>
* <ul>
* <li>append styleClass "invalid" to label, inputs and messages when invalid</li>
* </ul>
* <p/>
* <p>
* NOTE: Firefox does not properly associate a label with the target input if the input id contains a colon (:), the default
* separator character in JSF. JSF 2 allows developers to set the value via an initialization parameter (context-param in
* web.xml) keyed to javax.faces.SEPARATOR_CHAR. We recommend that you override this setting to make the separator an underscore
* (_).
* </p>
*
* @author Dan Allen
* @author <a href="http://community.jboss.org/people/spinner)">Jose Rodolfo freitas</a>
*/
@FacesComponent(UIInputContainer.COMPONENT_TYPE)
public class UIInputContainer extends UIComponentBase implements NamingContainer {
/**
* The standard component type for this component.
*/
public static final String COMPONENT_TYPE = "org.jboss.seam.faces.InputContainer";
protected static final String HTML_ID_ATTR_NAME = "id";
protected static final String HTML_CLASS_ATTR_NAME = "class";
protected static final String HTML_STYLE_ATTR_NAME = "style";
private boolean beanValidationPresent = false;
public UIInputContainer() {
beanValidationPresent = isClassPresent("javax.validation.Validator");
}
@Override
public String getFamily() {
return UINamingContainer.COMPONENT_FAMILY;
}
/**
* The name of the auto-generated composite component attribute that holds a boolean indicating whether the the template
* contains an invalid input.
*/
public String getInvalidAttributeName() {
return "invalid";
}
/**
* The name of the auto-generated composite component attribute that holds a boolean indicating whether the template
* contains a required input.
*/
public String getRequiredAttributeName() {
return "required";
}
/**
* The name of the composite component attribute that holds the string label for this set of inputs. If the label attribute
* is not provided, one will be generated from the id of the composite component or, if the id is defaulted, the name of the
* property bound to the first input.
*/
public String getLabelAttributeName() {
return "label";
}
/**
* The name of the auto-generated composite component attribute that holds the elements in this input container. The
* elements include the label, a list of inputs and a cooresponding list of messages.
*/
public String getElementsAttributeName() {
return "elements";
}
/**
* The name of the composite component attribute that holds a boolean indicating whether the component template should be
* enclosed in an HTML element, so that it be referenced from JavaScript.
*/
public String getEncloseAttributeName() {
return "enclose";
}
public String getContainerElementName() {
return "div";
}
public String getDefaultLabelId() {
return "label";
}
public String getDefaultInputId() {
return "input";
}
public String getDefaultMessageId() {
return "message";
}
@Override
public void encodeBegin(final FacesContext context) throws IOException {
if (!isRendered()) {
return;
}
super.encodeBegin(context);
InputContainerElements elements = scan(getFacet(UIComponent.COMPOSITE_FACET_NAME), null, context);
// assignIds(elements, context);
wire(elements, context);
getAttributes().put(getElementsAttributeName(), elements);
if (elements.hasValidationError()) {
getAttributes().put(getInvalidAttributeName(), true);
}
// set the required attribute, but only if the user didn't already assign it
if (!getAttributes().containsKey(getRequiredAttributeName()) && elements.hasRequiredInput()) {
getAttributes().put(getRequiredAttributeName(), true);
}
/*
* for some reason, Mojarra is not filling Attribute Map with "label" key if label attr has an EL value, so I added a
* labelHasEmptyValue to guarantee that there was no label setted.
*/
if (getValueExpression(getLabelAttributeName()) == null
&& (!getAttributes().containsKey(getLabelAttributeName()) || labelHasEmptyValue(elements))) {
getAttributes().put(getLabelAttributeName(), generateLabel(elements, context));
}
if (Boolean.TRUE.equals(getAttributes().get(getEncloseAttributeName()))) {
startContainerElement(context);
}
}
@Override
public void encodeEnd(final FacesContext context) throws IOException {
if (!isRendered()) {
return;
}
super.encodeEnd(context);
if (Boolean.TRUE.equals(getAttributes().get(getEncloseAttributeName()))) {
endContainerElement(context);
}
}
protected void startContainerElement(final FacesContext context) throws IOException {
context.getResponseWriter().startElement(getContainerElementName(), this);
String style = (getAttributes().get("style") != null ? getAttributes().get("style").toString().trim() : null);
if (style.length() > 0) {
context.getResponseWriter().writeAttribute(HTML_STYLE_ATTR_NAME, style, HTML_STYLE_ATTR_NAME);
}
String styleClass = (getAttributes().get("styleClass") != null ? getAttributes().get("styleClass").toString().trim()
: null);
if (styleClass.length() > 0) {
context.getResponseWriter().writeAttribute(HTML_CLASS_ATTR_NAME, styleClass, HTML_CLASS_ATTR_NAME);
}
context.getResponseWriter().writeAttribute(HTML_ID_ATTR_NAME, getClientId(context), HTML_ID_ATTR_NAME);
}
protected void endContainerElement(final FacesContext context) throws IOException {
context.getResponseWriter().endElement(getContainerElementName());
}
protected String generateLabel(final InputContainerElements elements, final FacesContext context) {
String name = getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX) ? elements.getPropertyName(context) : getId();
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
/**
* Walk the component tree branch built by the composite component and locate the input container elements.
*
* @return a composite object of the input container elements
*/
protected InputContainerElements scan(final UIComponent component, InputContainerElements elements,
final FacesContext context) {
if (elements == null) {
elements = new InputContainerElements();
}
// NOTE we need to walk the tree ignoring rendered attribute because it's condition
// could be based on what we discover
if ((elements.getLabel() == null) && (component instanceof HtmlOutputLabel)) {
elements.setLabel((HtmlOutputLabel) component);
} else if (component instanceof EditableValueHolder) {
elements.registerInput((EditableValueHolder) component, getDefaultValidator(context), context);
} else if (component instanceof UIMessage) {
elements.registerMessage((UIMessage) component);
}
// may need to walk smarter to ensure "element of least suprise"
for (UIComponent child : component.getChildren()) {
scan(child, elements, context);
}
return elements;
}
// assigning ids seems to break form submissions, but I don't know why
public void assignIds(final InputContainerElements elements, final FacesContext context) {
boolean refreshIds = false;
if (getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
setId(elements.getPropertyName(context));
refreshIds = true;
}
UIComponent label = elements.getLabel();
if (label != null) {
if (label.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
label.setId(getDefaultLabelId());
} else if (refreshIds) {
label.setId(label.getId());
}
}
for (int i = 0, len = elements.getInputs().size(); i < len; i++) {
UIComponent input = (UIComponent) elements.getInputs().get(i);
if (input.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
input.setId(getDefaultInputId() + (i == 0 ? "" : (i + 1)));
} else if (refreshIds) {
input.setId(input.getId());
}
}
for (int i = 0, len = elements.getMessages().size(); i < len; i++) {
UIComponent msg = elements.getMessages().get(i);
if (msg.getId().startsWith(UIViewRoot.UNIQUE_ID_PREFIX)) {
msg.setId(getDefaultMessageId() + (i == 0 ? "" : (i + 1)));
} else if (refreshIds) {
msg.setId(msg.getId());
}
}
}
/**
* Wire the label and messages to the input(s)
*/
protected void wire(final InputContainerElements elements, final FacesContext context) {
elements.wire(context);
}
/**
* Get the default Bean Validation Validator to read the contraints for a property.
*/
private Validator getDefaultValidator(final FacesContext context) throws FacesException {
if (!beanValidationPresent) {
return null;
}
ValidatorFactory validatorFactory;
Object cachedObject = context.getExternalContext().getApplicationMap().get(BeanValidator.VALIDATOR_FACTORY_KEY);
if (cachedObject instanceof ValidatorFactory) {
validatorFactory = (ValidatorFactory) cachedObject;
} else {
try {
validatorFactory = Validation.buildDefaultValidatorFactory();
} catch (ValidationException e) {
throw new FacesException("Could not build a default Bean Validator factory", e);
}
context.getExternalContext().getApplicationMap().put(BeanValidator.VALIDATOR_FACTORY_KEY, validatorFactory);
}
return validatorFactory.getValidator();
}
private boolean isClassPresent(final String fqcn) {
try {
if (Thread.currentThread().getContextClassLoader() != null) {
return Thread.currentThread().getContextClassLoader().loadClass(fqcn) != null;
} else {
return Class.forName(fqcn) != null;
}
} catch (ClassNotFoundException e) {
return false;
} catch (NoClassDefFoundError e) {
return false;
}
}
private boolean labelHasEmptyValue(InputContainerElements elements) {
if (elements.getLabel() == null || elements.getLabel().getValue() == null)
return false;
return (elements.getLabel().getValue().toString().trim().equals(":") || elements.getLabel().getValue().toString()
.trim().equals(""));
}
public static class InputContainerElements {
private String propertyName;
private HtmlOutputLabel label;
private final List<EditableValueHolder> inputs = new ArrayList<EditableValueHolder>();
private final List<UIMessage> messages = new ArrayList<UIMessage>();
private boolean validationError = false;
private boolean requiredInput = false;
public HtmlOutputLabel getLabel() {
return label;
}
public void setLabel(final HtmlOutputLabel label) {
this.label = label;
}
public List<EditableValueHolder> getInputs() {
return inputs;
}
public void registerInput(final EditableValueHolder input, final Validator validator, final FacesContext context) {
inputs.add(input);
if (input.isRequired() || isRequiredByConstraint(input, validator, context)) {
requiredInput = true;
}
if (!input.isValid()) {
validationError = true;
}
// optimization to avoid loop if already flagged
else if (!validationError) {
Iterator<FacesMessage> it = context.getMessages(((UIComponent) input).getClientId(context));
while (it.hasNext()) {
if (it.next().getSeverity().compareTo(FacesMessage.SEVERITY_WARN) >= 0) {
validationError = true;
break;
}
}
}
}
public List<UIMessage> getMessages() {
return messages;
}
public void registerMessage(final UIMessage message) {
messages.add(message);
}
public boolean hasValidationError() {
return validationError;
}
public boolean hasRequiredInput() {
return requiredInput;
}
private boolean isRequiredByConstraint(final EditableValueHolder input, final Validator validator,
final FacesContext context) {
if (validator == null) {
return false;
}
// NOTE believe it or not, getValueReference on ValueExpression is broken, so we have to do it ourselves
ValueExpression valueExpression = ((UIComponent) input).getValueExpression("value");
if (valueExpression != null) {
ValueExpressionAnalyzer valueExpressionAnalyzer = new ValueExpressionAnalyzer(valueExpression);
ValueReference vref = valueExpressionAnalyzer.getValueReference(context.getELContext());
if (vref != null) { // valueExpressionAnalyzer can return a null value. The condition prevents a NPE
BeanDescriptor constraintsForClass = validator.getConstraintsForClass(vref.getBase().getClass());
PropertyDescriptor d = constraintsForClass.getConstraintsForProperty((String) vref.getProperty());
return (d != null) && d.hasConstraints();
}
}
return false;
}
public String getPropertyName(final FacesContext context) {
if (propertyName != null) {
return propertyName;
}
if (inputs.size() == 0) {
return null;
}
propertyName = (String) new ValueExpressionAnalyzer(((UIComponent) inputs.get(0)).getValueExpression("value"))
.getValueReference(context.getELContext()).getProperty();
return propertyName;
}
public void wire(final FacesContext context) {
int numInputs = inputs.size();
if (numInputs > 0) {
if (label != null) {
label.setFor(((UIComponent) inputs.get(0)).getClientId(context));
}
for (int i = 0, len = messages.size(); i < len; i++) {
if (i < numInputs) {
messages.get(i).setFor(((UIComponent) inputs.get(i)).getClientId(context));
}
}
}
}
}
}