how to make my validator conditional for my checkbox control - java

I have a validator defined for my checkbox control:
<xp:checkBox uncheckedValue="false"
checkedValue="true" readonly="#{!matterBean.matter.editable}"
id="cbKCSupport" style="width:100%"
value="#{matterBean.matter.creatorKCSupport}"
validator="#{matterValidators.valCreatorKCSupport}">
</xp:checkBox>
the method is nothing fancy, I just check the value true or false of the checkbox:
public void valCreatorKCSupport(FacesContext facesContext, UIComponent component, Object value) {
utils.printToConsole(this.getClass().getSimpleName().toString() + " - valCreatorKCSupport(...), value = " + value.toString());
String msg = null;
if (value.toString().equals("false")){
msg = matterProp.getProperty("gen_KCSupport");
FacesMessage message = new FacesMessage(msg);
throw new ValidatorException(message);
}
}
I notice that this validation blocks the behaviour of other components e.g. the opening of dialog boxes.
For other controls I have a similar approach where the required property is based upon which component (buttons) have initiated the call to the server:
<xp:this.required><![CDATA[#{javascript:return ( submittedBy('btnSendToCommitee') || submittedBy('btnForCompletion') )}]]></xp:this.required>
I tried to set up a similar approach for my checkbox:
but then I get presented an error message:
Error while executing JavaScript action expression
Script interpreter error, line=2, col=33: Error calling method 'valCreatorKCSupport(com.ibm.xsp.domino.context.DominoFacesContext, com.ibm.xsp.component.xp.XspInputCheckbox, string)' on java class 'se.sebank.kkom.test.MatterValidators'
Message (text with text from matterProp.getProperty("gen_KCSupport"))
Anyone a suggestion how I should apply some conditional statement to my validator?

Related

Vaadin: How to set validation false to form from listener

I have a form and some textfields on it:
TextField taxNumber = new TextField();
taxNumber.setPrefixComponent(VaadinIcon.BARCODE.create());
accountApplicationBinder
.forField(taxNumber)
.withValidator(new StringLengthValidator(....
And I have some validation logic in the Listener:
taxNumber.addBlurListener(event -> {
String localResult = "";
InfoResult ir = ks.loadInfo(taxNumber.getValue());
if ((ir.errorText == null) && (!ir.name.isEmpty())) {
...
} else {
localResult = "";
taxNumber.setInvalid(true);
taxNumber.setErrorMessage("Not valid tax - " + accountApplicationBinder.isValid());
}
taxNumberStatusLabel.setText(localResult);
});
And I want to get a behavior like a ".withValidator... return not valid" in my submit button listener. In other words: I want to have my submit button not working then taxNumber.addBlurListener return not valid result. How I can do that?
it seems to me that your logic in the blurlistener replicates the validation you have already set when you bound the field with .withValidator(new StringLengthValidator()). That Validator is supposed to do exactly that.
When you click your submit button, all you have to do is validate the binder, and if it's not valid, then don't submit. You can customize the error string that it shows under the taxNumber field by providing a customized string into the StringLengthValidator:
.withValidator(new StringLengthValidator("Not valid tax", 4, null))
I just realized that you probably have custom validation in ks.loadInfo(taxNumber.getValue()). If that is the case, then the best way is to replace the StringLengthValidator with a custom Validator that you can write, for example like this
.withValidator(taxNr -> {
InfoResult ir = ks.loadInfo(taxNr);
return ir.errorText == null && !ir.name.isEmpty();
}, "Not valid tax")

HtmlUnit won't change TextArea's text

I have written a code to connect to this webpage: compilerjava.net
1) I found the text-area field within that page which accepts the code to compile.
2) I have found the button that compiles the code.
3) I have found the text-area which returns the result of the code.
The issue is, when I call textarea.setText( "something"), it (I think) doesn't actually change the code in the webpage. So when I click on the compile button, it compiles the default code within that page and returns the output of that default code.
I have tried to set focus to textarea, you can see all of those down below.
I called;
1) textArea.focus();
2) textArea.click();
3) I tried using textArea.setAttribute( "name", "code");
I have searched the internet and found various stackoverflow questions close to this problem, neither of them solved my issue and it just seems to work for everyone when they say textArea.setText().
Another interesting fact I should share with you is,
If I call textArea.setText( "...") and then I say;
HtmlTextArea textArea1 = form.getTextAreaByName( "code");
If I call textArea1.getText(), the value of this text will be "...". This should imply that I have actually managed to change the value of the text-area, but when I compile, it compiles the default text in the text-area and not the text that I have set it to.
Any help with this?
P.S: The reason why I put the result of the compilation on a while loop is related to network connection issues. If you try to run this code it might not work on your first try. Also note that the run-time is around 15 seconds, because it gives thousands of warnings which I blocked to print to console.
P.S2: I also looked at this page and none of these worked;
http://www.programcreek.com/java-api-examples/index.php?api=com.gargoylesoftware.htmlunit.html.HtmlTextArea
public class Test {
public static void main(String[] args) {
try {
// Prevents the program to print thousands of warning codes.
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
// Initializes the web client and yet again stops some warning codes.
WebClient webClient = new WebClient( BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnFailingStatusCode( false);
webClient.getOptions().setThrowExceptionOnScriptError( false);
webClient.getOptions().setJavaScriptEnabled( true);
webClient.getOptions().setCssEnabled( true);
// Gets the html page, which is the online compiler I'm using.
HtmlPage page = webClient.getPage("https://www.compilejava.net/");
// Succesfully finds the form which has the required buttons etc.
List<HtmlForm> forms = page.getForms();
HtmlForm form = forms.get( 0);
// Finds the textarea which will hold the code.
HtmlTextArea textArea = form.getTextAreaByName( "code");
// Finds the textarea which will hold the result of the compilation.
HtmlTextArea resultArea = page.getHtmlElementById( "execsout");
// Finds the compile button.
HtmlButtonInput button = form.getInputByName( "compile");
textArea.click();
textArea.focus();
// Simple code to run.
textArea.setDefaultValue( "public class HelloWorld\n" +
"{\n" +
" // arguments are passed using the text field below this editor\n" +
" public static void main(String[] args)\n" +
" {\n" +
" System.out.print( \"Hello\");\n" +
" }\n" +
"}");
System.out.println( textArea.getText());
// Compiles.
button.click();
// Result of the compilation.
String str = resultArea.getText();
while ( resultArea.getText() == null || resultArea.getText().substring(0, 3).equals( "exe")) {
System.out.print( resultArea.getText());
}
System.out.println();
System.out.println( resultArea.getText());
} catch ( Exception e) {
e.printStackTrace();
}
}
}
a little patience helps here
// Result of the compilation.
while (resultArea.getText() == null || resultArea.getText().startsWith("exe")) {
System.out.println(resultArea.getText());
Thread.sleep(500);
}
System.out.println();
System.out.println(resultArea.getText());

Pass the error Message to XPage client from Java Server code

Here is my Java code, before call I call the save() method. I want to check this business rule.
if (endDate.before(startDate)){
message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "",
"The end date should be not before the start date.");
// Throw exception so that it prevents document from being saved
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage("travel_endDate",message);
return false;
}
I want this message display at the "travel_endDate" component.
You have to use the client id of your component when adding the message.
1.) Add a binding to you component
<xp:inputText
id="travel_endDate"
binding="#{errorComponent}">
</xp:inputText>
2.) resolve the variable in your save method
UIComponent cmp = (UIComponent) facesContext.getApplication().getVariableResolver().resolveVariable(facesContext, "errorComponent");
String clientId = cmp.getClientId(facesContext);
3.) Add the message with the id to the facesContext
facesContext.addMessage(clientId,message);

WebDriver is unable to perform click on an input element having onclick=function1() as an attribute

I am using Web driver 2.31 with Java. It seems the web driver is unable to perform click action on an input element having onclick() attribute.
The input element I need to perform click action on is having the following attributes - id (which is a random generated number), class, type=button, onclick, onmouseout, onmouseover, title and value.
I'm able to fetch the values of title and value attributes which means that the web driver is able to recognize the input element but is not able to perform click action on it.
I have tried with the following:
webdriver.findElement(By.xpath("xpath for the input")).click()
webdriver.findElement(By.xpath("xpath for the input")).sendKeys(Keys.ENTER);
new Actions(webdriver).moveToElement(webdriver.findElement(By.xpath("xpath for the input"))).click().perform();
None of the above options are working.
Do you get any exceptions from element.click()? It it enabled and visible? One of the problems we had was that WebDriver didn't handle position:static elements correctly, so during playback it would cover the button (and you won't see it on screenshot) and it would throw exception "Element is not clickable at point".
We had similar problem with element and had following code that did work sometimes (but also not 100% of times):
element.click();
if("button".equals(tagName)) {
if(element.isEnabled() && element.isDisplayed())
element.sendKeys(Keys.ENTER);
}
But the problem disappeared itself after upgrading WebDriver and we removed sendKeys(ENTER), also it was working fine in 2.29.0.
I faced exactly same problem in my project. The issue was not to locate the element but the onClick() event was not firing.
Then i found out that something else was there which stopped from the event to fire. I had used java script to enable the date picker box & did this,
((JavascriptExecutor)driver).executeScript ("document.getElementById('txtOriginDate').removeAttribute('readonly',0);");
WebElement originDateBox= driver.findElement(By.xpath(prop.getProperty("originDateBox")));
originDateBox.clear();
originDateBox.sendKeys("9-Dec-2014"); //Enter date
Developer designed this in such a way that if you don't use date picker to select date, a specific variable was not set. Which eventually made the **onclick event not to fire.
The date picker code was something like this,
var jsoncustdate = "";
var jsonorigindate = "";
function onSelectCalender( StrDt, obj )
{
if ( !varReadonly ) {
if ( $( "#txtCustDescisionDate" ).attr( "IsDisable" ) == "FALSE" )
{
if ( obj.id == "txtCustDescisionDate" )
{
custobjDt = new Date( obj.selectedYear, obj.selectedMonth,obj.selectedDay, 0, 0, 0, 0 );
jsoncustdate = custobjDt.getTime();
jsoncustdate = "\/Date(" + jsoncustdate + ")\/";
DisabledBtnStage();
// $("#txtFromDate").datepicker("option", "maxDate", objDt);
}
if ( obj.id == "txtOriginDate" )
{
var objDt = new Date( obj.selectedYear, obj.selectedMonth,obj.selectedDay,0, 0,0,0 );
jsonorigindate = objDt.getTime();
jsonorigindate = "\/Date(" + jsonorigindate + ")\/";
DisabledBtnStage();
// $("#txtToDate").datepicker("option", "minDate", objDt);
}
}
elogCommon.CheckMandatory();
}
}
I finally used date picker in normal way & the event fired smoothly.
I hope this answer will help . .cheers !!!

JSF 2.0 Custom Validation problem

I want to validate the inputs to my JSF page inside my Managed bean, but for some reason it does not work?
#ManagedBean
#RequestScoped
public class RegistrationController {
//values passed from the JSF page
private String name;
...
public void validateName(FacesContext context, UIComponent validate,
Object value) {
String inputFromField = (String) value;
String simpleTextPatternText = "^[a-zA-Z0-9]+$";
Pattern textPattern = null;
Matcher nameMatcher = null;
textPattern = Pattern.compile(simpleTextPatternText);
nameMatcher = textPattern.matcher(getName());
if (!nameMatcher.matches()) {
((UIInput) validate).setValid(false);
FacesMessage msg = new FacesMessage(
"your name cant contain special characters");
context.addMessage(validate.getClientId(), msg);
}
}
This is how input component looks like(Inside a form):
<h:inputText value="#{registrationController.name}" validator="#{registrationController.validateName}" required="true">
<h:message for="nameInput"/>
When i enter a wrong input i dont see the validation message, and in the console i see this:
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.
sourceId=bRegForm:j_idt7[severity=(ERROR 2), summary=(bRegForm:j_idt7: Validation Error: Value is required.), detail=(bRegForm:j_idt7: Validation Error: Value is required.)]
What it could be? Am i forgetting something? Do i have to add something to my configuration files...?
You forgot to give your input component an id. That's where the for attribute of <h:message> should point to.
<h:inputText id="nameInput">
Unrelated to the concrete problem, your approach is clumsy and technically wrong. As per the specification, you should throw a ValidatorException. So instead of
((UIInput) validate).setValid(false);
context.addMessage(validate.getClientId(), msg);
do
throw new ValidatorException(msg);
Then JSF will worry about setting the component as invalid and adding the message to the context.
There's a second problem, you're validating the local value instead of the submitted value.
Replace
nameMatcher = textPattern.matcher(getName());
by
nameMatcher = textPattern.matcher(inputFromField);

Categories

Resources