In system user can type a "URL", like "http://www.google.com" and this URL must be processed in SERVER and after the content is showed in XHTML page.
In my XHTML i have:
<h:form id="formNavegador" enctype="multipart/form-data">
<p:inputText value="#{navegadorMB.url}" required="true"
requiredMessage="A url é obrigatória"
type="Digite a url para navegar. Ex: http://www.google.com.br" />
<h:outputText value="#{navegadorMB.htmlContent}" escape="false"
id="htmlContent" />
<p:commandButton id="commandButtonProcessar" value="Ir"
update=":formNavegador:htmlContent" icon="ui-icon-play"
actionListener="#{navegadorMB.processaRequisicao}" />
</h:form>
So, when user type the URL and click in commandButton, the code bellow is processed:
public void processaRequisicao(ActionEvent event){
if (url.isEmpty()){
addErrorMessage("Você precisa digitar um endereço");
FacesContext.getCurrentInstance().validationFailed();
}else{
htmlContent = boPadrao.processaRequisicaoOnServer(url);
System.out.println(htmlContent);
}
}
In my method "processaRequisicaoOnServer" the URL is opened and all content is read, after the content of site is returned. See:
public String processaRequisicaoOnServer(String url) {
URL urlObj;
try {
urlObj = new URL(url.trim().toLowerCase());
BufferedReader conteudo = new BufferedReader(new InputStreamReader(urlObj.openStream()));
String linha = "";
StringBuffer sb = new StringBuffer();
while((linha = conteudo.readLine()) != null)
{
sb.append(linha);
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
throw new BOException(e.getMessage());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new BOException(e.getMessage());
}
}
So, the content of URL is showed in console because of "System.out.." but the h:outputText is not updated as i hope.
I can't see your entire bean here, but here are some things that I've noticed:
If this is your entire form, you don't need the enctype="multipart/form-data", so you can just remove it.
There is a strange type attribute in your first p:inputText. Didn't you mean title?
<p:inputText type="Digite a url para navegar. Ex: http://www.google.com.br" />
Also, you don't need to specify the parent of a component when the component is already a child of this parent, so you could change this:
<p:commandButton id="commandButtonProcessar" value="Ir" update=":formNavegador:htmlContent" icon="ui-icon-play" actionListener="#{navegadorMB.processaRequisicao}" />
to this:
<p:commandButton id="commandButtonProcessar" value="Ir" update="htmlContent" icon="ui-icon-play" actionListener="#{navegadorMB.processaRequisicao}" />
And you are calling an action listener and passing an ActionEvent, which you don't need to, so you could change this:
public void processaRequisicao(ActionEvent event) { ...
to this:
public void processaRequisicao() { ...
Furthermore, in order to test it all, you could go in steps, creating a mock method first and checking if things are working properly, and then adding your business stuff.
For instance, to test this you could change your processaRequisicao to something like:
public void processaRequisicaoMock() {
htmlContent = "Funcionou!";
}
And then call it, and check if the view is working properly. If it is, you can go on, adding the business layer and all.
I hope it helps.
Instead of
<p:commandButton id="commandButtonProcessar" value="Ir"
update=":formNavegador:htmlContent" icon="ui-icon-play"
actionListener="#{navegadorMB.processaRequisicao}" />
Try
<p:commandButton id="commandButtonProcessar" value="Ir"
update="htmlContent" icon="ui-icon-play"
actionListener="#{navegadorMB.processaRequisicao}" ajax="false"/>
Also, change your method to
public void processaRequisicao(){
if (url.isEmpty()){
addErrorMessage("Você precisa digitar um endereço");
FacesContext.getCurrentInstance().validationFailed();
}else{
htmlContent = boPadrao.processaRequisicaoOnServer(url);
System.out.println(htmlContent);
}
}
Related
This is my xhtml
<p:selectOneMenu
value="#{insurancePlanUpdateBean.insurancePlan.planType}">
<f:selectItems value="#{insurancePlanUpdateBean.planTypeList}" />
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
event="change" update="form:panelHead" process="#this" />
</p:selectOneMenu>
from my code, action listener should call the updatePlanType in my updateBean,
i didnt get any error when running in eclipse, but when debugging, this program didnt get to the my updatePlanType class, there is my updatePlanType code :
public void updatePlanType(ActionEvent actionEvent) {
logger.debug("Update Plan Type");
try {
resetDetail();
if (insurancePlan.getPlanType().equals(
InsurancePlanConstants.PLAN_TYPE_MASTER)) {
if (insurancePlan.getInsuranceCompany() != null
&& insurancePlan.getInsuranceCompany().getCompanyName() != null
&& !StringUtils.isEmpty(insurancePlan
.getInsuranceCompany().getCompanyCode()))
existPlanType = true;
dependantAvailable = false;
existReference = false;
} else if (insurancePlan.getPlanType().equals(
InsurancePlanConstants.PLAN_TYPE_DEPENDANT)) {
if (insurancePlan.getInsuranceCompany() != null
&& insurancePlan.getInsuranceCompany().getCompanyName() != null
&& !StringUtils.isEmpty(insurancePlan
.getInsuranceCompany().getCompanyCode()))
existPlanType = true;
dependantAvailable = true;
existReference = true;
} else {
existPlanType = false;
existReference = false;
}
logger.debug("existPlanType:" + existPlanType);
logger.debug("dependantAvailable:" + dependantAvailable);
} catch (Exception e) {
logger.error("Error : ", e);
}
}
i think this would be a syntax problem, please help, im stuck for a couple of hours, thanks!
You are using the wrong event in your p:ajax statement.
Use:
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
event="valueChange" update="form:panelHead" process="#this" />
or as valueChange already is the defaultEvent:
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
update="form:panelHead" process="#this" />
instead of:
<p:ajax actionListener="#{insurancePlanUpdateBean.updatePlanType}"
event="change" update="form:panelHead" process="#this" />
You can find a list of the supported event types of every component in the documentation: https://primefaces.github.io/primefaces/8_0/#/components/selectonemenu?id=selectonemenu
i'm using primefaces schedule , when the dialog form pop up , i need to select data from SelectOneMenu and pass them to the add function in order to insert them into database
the problem is that sometimes it works great and i can insert them, but when i try to add another second insert i doesn't work again
can you check it out please ? i need to know if i'm doing this the wrong way because i can't find the problem.
Managedbean constructor :
#PostConstruct
public void init() {
Chauffeurs = new ArrayList<Chauffeur>();
ChauffeurDispo = new dao.gsVoyage().getChauffeursDesponible(Chauffeurs);
model = new DefaultScheduleModel();
vDao=new dao.gsVoyage();
voyage=new Voyage();
try {
listVoyage=vDao.getListVoyages();
}catch(Exception ex) {
ex.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR,"erreur","erreur no sql"));
}
for(Voyage v:listVoyage) {
DefaultScheduleEvent evt=new DefaultScheduleEvent();
evt.setEndDate(v.getDateV());
evt.setStartDate(v.getDateV());
evt.setDescription(v.getChauffeurBean().getMatricule());
evt.setData(v.getIdVoyage());
model.addEvent(evt);
}
}
the add function :
public void ajouter() {
try {
new dao.gsVoyage().addVoyage(dateV, autocar, chauffeur,chauffeur2,0);
DefaultScheduleEvent evt=new DefaultScheduleEvent();
evt.setEndDate(dateV);
evt.setStartDate(dateV);
evt.setDescription(chauffeur);
model.addEvent(evt);
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", e.getMessage()));
}
voyage = new Voyage();
}
xhtml of SelectOneMenu :
<label>Chauffeur :</label><br/>
<h:selectOneMenu
value="#{scheduleJava8View.chauffeur}">
<f:selectItems
value="#{scheduleJava8View.chauffeurDispo}"
var="chauffeur" itemValue="#{chauffeur.matricule}"
itemLabel="#{chauffeur.nom}" />
</h:selectOneMenu>
this is how i display inserted data in xhtml
<label>Chauffeur:</label><br/>
<p:inputText value="#{scheduleJava8View.voyage.chauffeurBean.matricule}" />
Try changing your code to this
<h:selectOneMenu
onchange="submit()"
value="#{scheduleJava8View.chauffeur}">
This will make a call to
setChauffeur(Chauffeur c)
on your backed bean. Notice that in this case, you will need to define a converter since it is not a Java basic type (int, String,...).
I want to open the filters only if they are not already open. For that, I'm checking if "Apply Filter" button is visible/clickable.
To my surprise, I'm getting the element as visible/clickable even though it is not.
Button code mentioned below,
<div class="m-t-20 text-left filter-btn-holder ">
<input type="hidden" id="filterType" value="">
<button type="button" class="submit btn btn-primary btn-mini filter-focus" id="filterButton" onclick="javascript:getFilteredMedia(true);" "="">Filter</button>
<button type="button" class="submit btn btn-danger btn-mini" id="filterButton" onclick="clearFilter();">Reset</button>
<button type="button" class="submit btn btn-mini" data-webarch="toggle-right-side" id="closeButton"><i class="fa fa-times" aria-hidden="true"></i></button>
</div>
Method trying to check if element is clickable
public boolean isClickable(WebElement el)
{
try{
WebDriverWait wait = new WebDriverWait(driver, 6);
wait.until(ExpectedConditions.elementToBeClickable(el));
return true;
}
catch (Exception e){
return false;
}
}
XPath of the button: xpath = "//button[#id='filterButton' and text()[contains(.,'Filter')]]
Try this:
public boolean isClickable(WebElement el)
{
try{
WebDriverWait wait = new WebDriverWait(driver, 6);
wait.until(ExpectedConditions.elementToBeClickable(el));
return el.isDisplayed() && el.isEnabled();
}
catch (Exception e){
return false;
}
}
Please use the element with id=__multiselect_mediatag instead of its child elements.
Though I didn't get the answer exactly, found some workaround. Checked a parent element class if it's visible or not using the javascript executor.
Still not sure why I'm getting visible for an invisible element.
JavascriptExecutor js = (JavascriptExecutor)driver;
String className = (String) js.executeScript("return document.getElementById('chat-users').getAttribute('class');");
I had a similar problem. As part of client-side input validation, we provide a box listing all errors found. Of course, the box contains all possible error messages, and we toggle their display from Javascript. However, after filling one input field (and its related error message getting hidden) a new query would report it as still visible.
// always returns the same list as the first time it's called
public static List<String> getErrorGroupMsgs(TestState state) {
List<String> list = new ArrayList<>();
WebDriver driver = state.getDriver();
WebElement errorBox = driver.findElement(By.id(state.getProperty("errorBoxGroupId")));
for(WebElement div : errorBox.findElements(By.tagName("div"))) {
if(div.isDisplayed()) {
list.add(div.getDomProperty("innerText").trim());
}
}
return list;
}
Adding delays between sending text to the input field and re-reading the displayed messages did not help, but what finally did help was to interleave another call to findElements() with different parameters.
// returns an updated view of the world
public static List<String> getErrorGroupMsgs(TestState state) {
List<String> list = new ArrayList<>();
WebDriver driver = state.getDriver();
WebElement errorBox = driver.findElement(By.id(state.getProperty("errorBoxGroupId")));
// this line refreshes the errorBox element so we can get an accurate count below ....
errorBox.findElements(By.cssSelector("div[display='block']"));
for(WebElement div : errorBox.findElements(By.tagName("div"))) {
if(div.isDisplayed()) {
list.add(div.getDomProperty("innerText").trim());
}
}
return list;
}
i searched everywhere and i'm trying everything, no success with a real exception..
i need to throw an exception so it 'ignore' everything after the method point (a single return wouldn't be enough cuz there are more methods above) so I found something like this:
throw new javax.faces.validator.ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, ex instanceof ValidationException ? ex.getMessage() : MessageProvider.getMessage("sales.insert.error"), null));
EDIT 1
(This is done inside a void method in my ManagedBean (#ViewScoped), the method is called from a p:commandButton with a action="#{something}".
EDIT 2
The button:
<p:commandLink id="finalizarBtn" action="#{vendaMB.finalizarVenda()}" update="#form" process="#this, vendaList" styleClass="btn btn-regalo margin-side-5 btn-block" title="#{msg['sales.add']}" style="width: 500px; display: inline-block; margin: 20px 0px;" ><i class="fa fa-fw fa-2x fa-check"></i></p:commandLink>
And the complete method:
public void finalizarVenda() throws ValidatorException {
if(vendaProdutos.size() < 1) {
FacesUtil.addErrorMessage("vendaForm:produto", "");
return;
}
venda.setDataVenda(new Date());
try {
venda = vendaBO.incluir(venda, vendaProdutos);
} catch(Exception ex) {
venda.setDataVenda(null);
vendaBO.getDB().rollbackTransaction();
throw new javax.faces.validator.ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, ex instanceof ValidationException ? ex.getMessage() : MessageProvider.getMessage("sales.insert.error"), null));
}
FacesUtil.addInfoMessage(MessageProvider.getMessage("sales.insert.success"));
novaVenda();
}
The messages component:
<p:messages id="messages" autoUpdate="true" globalOnly="true" showSummary="true" showDetail="false" escape="false" rendered="true" closable="true" />
i use this inside my try/catch block, it throws the exception as expected (the message) but it's never rendered at the view, if i manually add the FacesMessage to the FacesContext and throw the exception that is being catch, the same happens, no error messages at the view, example:
try {
//something
} catch (Exception ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("something"));
throw ex;
}
Both solutions doesn't work, i'm using JSF, PrimeFaces and Tomcat 8.
Throwing a ValidatorException from your managed bean will not set the message.
Will the following work:
public void finalizarVenda() throws ValidatorException {
if(vendaProdutos.size() < 1) {
FacesUtil.addErrorMessage("vendaForm:produto", "");
return;
}
venda.setDataVenda(new Date());
try {
venda = vendaBO.incluir(venda, vendaProdutos);
FacesUtil.addInfoMessage(MessageProvider.getMessage("sales.insert.success"));
novaVenda();
} catch(Exception ex) {
venda.setDataVenda(null);
vendaBO.getDB().rollbackTransaction();
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex instanceof ValidationException ? ex.getMessage() : MessageProvider.getMessage("sales.insert.error"), null));
}
}
If the novaVenda() method can also throw an exception you might also want to wrap that in a try catch block and throw the caught exception.
I am writing a PrimeFaces application. I have the following code in my XHTML:
<p:selectOneMenu value="#{lottoCheckerBean.selectedPowerBallDrawingDate}">
<f:selectItems value="#{lottoCheckerBean.powerBallDrawingDates}" />
</p:selectOneMenu>
I am expecting the following code to be executed in my LottoCheckerBean when a value is selected:
public void setSelectedPowerBallDrawingDate(String selectedPowerBallDrawingDate) {
//get drawing
PowerBallDrawing currentDrawing = null;
for (int d = 0; d < powerBallDrawings.size(); d++) {
if (powerBallDrawings.get(d).getDrawingDate().equals(selectedPowerBallDrawingDate)) {
currentDrawing = powerBallDrawings.get(d);
break;
}
}
if (currentDrawing == null) {
try {
//create new drawing;
currentDrawing = new PowerBallDrawing(selectedPowerBallDrawingDate);
powerBallDrawings.add(currentDrawing);
Arrays.sort(powerBallDrawings.toArray());
} catch (Exception ex) {
//will not happen so ignore
}
}
this.selectedPowerBallDrawingDate = selectedPowerBallDrawingDate;
}
However, if I set a breakpoint at the beginning of the above method, the breakpoint is not reached.
What am I missing?
The code you expect to execute upon change will be called when you submit the form in which your selectOneMenu is placed. That is when the value from the selectOneMenu will be passed to your bean.
If you would want to perform something upon any other event, such as change, you need to enable ajax:
<p:selectOneMenu value="#{lottoCheckerBean.selectedPowerBallDrawingDate}" >
<f:selectItems value="#{lottoCheckerBean.powerBallDrawingDates}" />
<p:ajax event="change" listener="#{lottoCheckerBean.someMethod}" />
</p:selectOneMenu>
When value is changed in the backing bean, someMethod() will be called.
I would recommend you to use setSelectedPowerBallDrawingDate(String selectedPowerBallDrawingDate) only as a setter which sets the value, not to conatain any business logic at all. Then let the method you call from <p:ajax/> do the business logic.