jsf variable lost value [duplicate] - variables

This question already has an answer here:
#ViewScoped calls #PostConstruct on every postback request
(1 answer)
Closed 5 years ago.
I have a managed Bean called bean1.java that has a boolean var called found. The variable says if a client has been found or not.
The bean has a method validate() that goes to the DB and checks if the client exists, and sets the variable to found=true if it exists or 'false' if it doesn't.
Then I keep completing other fields in my form. Now, when I click the button save, it the method saving(). That method has to do an action if the var found is true and another action if it's false.
But the problem is when I validate the variable that has been set to true on the method validate(), now it has the value "false".
#ManagedBean
#ViewScoped //SessionScoped
public class AgregarPoliza implements Serializable{
public boolean found=false;
public void validate(){
// go to data base and validate if the client exist, when exist
// set variable true
found = true; // setFound(true); <--- i already try this way too
}
public void saving(){
//it has two actions to do but need to know the value of found
System.out.println("my var found has" + found); //this system.out shows false
if(found ==true){
//makes an action
}
else{
//makes another action
}
}
//get and set of the value found
}

You should try calling the validate method in the method saving like this.
public void validate()
{
// go to data base and validate if the client exist, when exist
// set variable true
found = true; // setFound(true); <--- i already try this way too
}
public void saving(){
this.validate();
//it has two actions to do but need to know the value of found
System.out.println("my var found has" + found); //this system.out shows false
if(found ==true){
//makes an action
}
else{
//makes another action
}

i hava use this and this is working fine now check it please now it can not lost value...
AgregarPoliza.java
package com.best.uibeansTest;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "agregarPoliza")
#SessionScoped
public class AgregarPoliza implements Serializable{
public boolean found=false;
public void validate(){
// go to data base and validate if the client exist, when exist
// set variable true
found = true; // setFound(true); <--- i already try this way too
}
public String saving(){
validate();
//it has two actions to do but need to know the value of found
System.out.println("my var found has" + found); //this system.out shows false
if(found ==true){
//makes an action
}
else{
//makes another action
}
return "test2.xhtml" ;
}
//get and set of the value found
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
//get and set of the value found
}
here i just get agregarPoliza as bean i am showing jsf code below through which i check this..
test2.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<head>
<title>JSF Tutorial!</title>
</head>
<h:body>
<h2>Result</h2>
<hr />
<h:form>
<p:commandButton value="Save" ajax="false" action="#{agregarPoliza.saving}"/>
|
found value:
#{agregarPoliza.found}
</h:form>
</h:body>
</html>
on clicking of save button found value is changed to true. try this..

Related

Testng - Skip dependent tests for only failed data sets

I am attempting to modify my dependent tests so they are ran in a specific way and have yet find a way possible. For instance, say I have the following two tests and the defined data provider:
#Dataprovider(name = "apiResponses")
Public void queryApi(){
return getApiResponses().entrySet().stream().map(response -> new Object[]{response.getKey(), response.getValue()}).toArray(Object[][]::new);
}
#Test(dataprovider = "apiResponses")
Public void validateApiResponse(Object apiRequest, Object apiResponse){
if(apiResponse.statusCode != 200){
Assert.fail("Api Response must be that of a 200 to continue testing");
}
}
#Test(dataprovider = "apiResponses", dependsOnMethod="validateApiResponse")
Public void validateResponseContent(Object apiRequest, Object apiResponse){
//The following method contains the necessary assertions for validating api repsonse content
validateApiResponseData(apiResponse);
}
Say I have 100 api requests I want to validate, with the above, if a single one of those 100 requests were to return a status code of anything other than 200, then validateResponseContent would be skipped for all 100. What I'm attempting to achieve is that the dependent tests would be skipped for only the api responses that were to return without a status code of 200 and for all tests to be ran for responses that returned WITH a status code of 200.
You should be using a TestNG Factory which creates instances with both the apiRequest and apiResponse in it for each instance. Now each instance would basically first run an assertion on the status code before it moves on to validating the actual api response.
Here's a sample that shows how this would look like:
public class TestClassSample {
private Object apiRequest, apiResponse;
#Factory(dataProvider = "apiResponses")
public TestClassSample(Object apiRequest, Object apiResponse) {
this.apiRequest = apiRequest;
this.apiResponse = apiResponse;
}
#Test
public void validateApiResponse() {
Assert.assertEquals(apiResponse.statusCode, 200, "Api Response must be that of a 200 to continue testing");
}
#Test(dependsOnMethods = "validateApiResponse")
public void validateResponseContent() {
//The following method contains the necessary assertions for validating api repsonse content
validateApiResponseData(apiResponse);
}
#DataProvider(name = "apiResponses")
public static java.lang.Object[][] queryApi() {
return getApiResponses().entrySet()
.stream().map(
response -> new java.lang.Object[]{
response.getKey(), response.getValue()
})
.toArray(Object[][]::new);
}
}
Would'nt adding a if/else block solve this?
#Test(dataprovider = "apiResponses")
Public void validateApiResponse(Object apiRequest, Object apiResponse){
if(apiResponse.statusCode != 200){
Assert.fail("Api Response must be that of a 200 to continue testing");
} else {
validateApiResponseData(apiResponse);
}
}

Selenium IE Page title is not working. Tried IWebDriver.Title

I asked this question last week and someone marked it as a duplicate. However the duplicate reference did not answer or give solution to my question.
I am trying to get the page title to a complicated html page. I am trying to get the 'By' locator used to find an element. This is the HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="ctl00_Head1"><title>
Smart Tracking System
</title><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" /><link rel="shortcut icon" type="image/x-icon" href="../images/desktopicon.ico" /><link href="../App_Themes/appthemes/appstyles.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/appthemes/calendarstyles.css" type="text/css" rel="stylesheet" /><link href="../App_Themes/appthemes/tabsstyles.css" type="text/css" rel="stylesheet" /></head>
<body>
When I copy the xpath from Firefox source code, it says the xpath is:
/html/head/title
I am using C# code to do the validation but I keep getting "LoadableComponentException..."
This is my C# code:
public class AccountsOverviewPage : CVALoadableComponent<AccountsOverviewPage>
{
private IWebDriver _driver;
private By textlabelPageHeader = By.XPath("//head[#class='title' and text()='Smart Tracking System']");
public AccountsOverviewPage()
{
_driver = ScenarioContext.Current.Get<IWebDriver>();
}
protected override void ExecuteLoad()
{
}
protected override bool EvaluateLoadedStatus()
{
if (!CVAElements.WaitForElementOnPageLoad(_driver, textlabelPageHeader))
{
UnableToLoadMessage = "Could not load Accounts Overview page within the designated timeout period";
return false;
}
return true;
}
public bool IsAt()
{
return CVAElements.CheckElementIsVisible(_driver, textlabelPageHeader);
}
}
I have even tried doing the validation by Id, and this time I used an element Id that I am sure is there:
private By textlabelPageHeader = By.Id("ctl00_Head1");
and still the validation failed. What am I not doing?? Please any assistance will be greatly appreciated.
UPDATE
This is how I am using the Driver.Title method:
public class AccountsOverviewPage : CVALoadableComponent<AccountsOverviewPage>
{
private IWebDriver _driver;
// error happens on this line:
string textlabelPageHeader = _driver.Title;
public string TextlabelPageHeader
{
get
{
return textlabelPageHeader;
}
set
{
textlabelPageHeader = value;
}
}
public AccountsOverviewPage()
{
_driver = ScenarioContext.Current.Get<IWebDriver>();
}
protected override void ExecuteLoad()
{
}
protected override bool EvaluateLoadedStatus()
{
if (!CVAElements.WaitForElementOnPageLoad(_driver, TextlabelPageHeader))
{
UnableToLoadMessage = "Could not load Accounts Overview page within the designated timeout period";
return false;
}
return true;
}
public bool IsAt()
{
return CVAElements.CheckElementIsVisible(_driver, TextlabelPageHeader);
}
and I getting error: "A field initializer cannot reference the non-static field, method, or property" here
string textlabelPageHeader = _driver.Title;
What you're trying to access - a page title - is not a web element. It's a property of the web page itself. In Selenium, you access the page title by:
String pageTitle = _driver.getTitle();
I program in Java, so that might not be the correct syntax for C#

MVC4 custom unobtrusive validator isn't working

not sure what is wrong. Syntax seems correct.... but it still doesn't fire on client side. If I submit the form, I get server side validation, client side nothing...
Here is the code that is on the page:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script type="text/javascript">
// we add a custom jquery validation method
(function ($) {
$.validator.addMethod('additive', function (value, element, params) {
//just return false to test it.
return false;
});
// and an unobtrusive adapter
$.validator.unobtrusive.adapters.add("additive", ["field2", "field3", "field4"], function (options) {
var params = {
field2: options.params.field2,
field3: options.params.field3,
field4: options.params.field4
};
options.rules['additive'] = params;
if (options.message) {
options.messages['additive'] = options.message;
}
});
}) (jQuery);
</script>
Here is the part that is on the validator that is related to client side (IClientValidatable):
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule rule = new ModelClientValidationRule
{
ValidationType = "additive",
ErrorMessage = "ERROR MESSAGE"
};
rule.ValidationParameters.Add("field2", propName2);
rule.ValidationParameters.Add("field3", propName3);
rule.ValidationParameters.Add("field4", propName4);
yield return rule;
}
The model is decorated as following:
[SumValidation("OtherField2...")]
public int MyField { get; set; }
When field renders, it is all there, all the stuff from the server side in terms of data-xxx attributes. Just this specific client validation does not fire. Anyone see what I'm missing?
figured it out. If anyone runs into this. Added custom validation too late on the page. After I moved my custom validation javascript to the head section of the _Layout.cshtml it started to work.
So if your script looks right, good place to check.
Another work around is to run $.validator.unobtrusive.parse('form'); which reloads all the validators.

Struggling with passing messages through MVVM Light

I have two view and their corresponding ViewModels and i want to send text from one view to another using MVVM Light as follows
in first viewmodel i am calling the following method
public void NavigatePage()
{
string temp = "temp value";
Messenger.Default.Send("temp");
Frame frame = Window.Current.Content as Frame;
if (frame != null) frame.Navigate(typeof(MyPage), temp);
}
while in page 2 view model i am having the following code
public MyViewModel()
{
Messenger.Default.Register<string>(this, MessageReceived);
}
private string test;
public string Test
{
get { return test; }
set { test = value; RaisePropertyChanged("Test");}
}
private void MessageReceived(string message)
{
Test = message;
}
when i debug my code the ctor of this viewmodel is getting called but the MessageReceived is not getting called hence property Test is never getting set, I am missing something, please help
Is the SecondViewModel actually created before you send the message? You can specify this in the ViewModelLocator class.
In the locator you have to register your viewmodel and CREATE it when the applications starts.
Like this:
SimpleIoc.Default.Register<SecondViewModel>(true);
With the true parameter the SecondViewModel will be created when the application is started! :)

Struts2 more than one action in one class

I'm using Struts2. I have two web forms that have the same code. I would like to eliminate one form. Here is the structure of my Struts project.
\Web Pages
form.jsp
\WEB-INF
\Content
error.jsp
form.jsp
success.jsp
\Source Packages
\action
MyAction.java
MyAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.*;
public class MyAction extends ActionSupport {
#Action(value = "foo", results = {
#Result(name = "input", location = "form.jsp"),
#Result(name = "success", location = "success.jsp"),
#Result(name = "error", location = "error.jsp")
})
public String execute() throws Exception {
if (user.length() == 1) {
return "success";
} else {
return "error";
}
}
private String user = "";
public void validate() {
if (user.length() == 0) {
addFieldError("user", getText("user required"));
}
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
I tried to eliminate form.jsp under \Web Pages by adding a new action method to MyAction.java.
#Action(value="bar", results = {
#Result(name = "success", location = "form.jsp"),
})
public String another() {
return "success";
}
But I got the following error when I go to http : //localhost .../bar.action
HTTP Status 404 - No result defined for action action.MyAction and result input
Your MyAction has an implementation of validate(), which means it is validation aware.
What's happening is that you're calling another, but validate() is kicking in (as it's in the interceptor stack). Validation is failing, and therefore sending to INPUT result, which is not defined in another.
You should
Add #SkipValidation to the another method if you don't want validation there
Add the INPUT result to another() if you want a default input result
On a more general note, when you get that kind of error (No result defined for action X and result input) it usually means you're either having validation errors, parameter population errors (eg: an exception in preparable).