JSF show thrown message in h:message - java

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.

Related

Primefaces ajax actionListener not called in p:selectOneMenu

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

pass SelectOneMenu value to add function in JSF / Primefaces

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,...).

JSF page is not showing the content

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);
}
}

Primefaces selectOneMenu does not execute on change

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.

JSP Custom Taglib: Nested Evaluation

Say I have my custom taglib:
<%# taglib uri="http://foo.bar/mytaglib" prefix="mytaglib"%>
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<mytaglib:doSomething>
Test
</mytaglib:doSomething>
Inside the taglib class I need to process a template and tell the JSP to re-evaluate its output, so for example if I have this:
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("<c:out value=\"My enclosed tag\"/>");
getJspBody().invoke(null);
}
}
The output I have is:
<c:out value="My enclosed tag"/>
Test
When I actually need to output this:
My enclosed tag
Test
Is this feasible? How?
Thanks.
Tiago, I do not know how to solve your exact problem but you can interpret the JSP code from a file. Just create a RequestDispatcher and include the JSP:
public int doStartTag() throws JspException {
ServletRequest request = pageContext.getRequest();
ServletResponse response = pageContext.getResponse();
RequestDispatcher disp = request.getRequestDispatcher("/test.jsp");
try {
disp.include(request, response);
} catch (ServletException e) {
throw new JspException(e);
} catch (IOException e) {
throw new JspException(e);
}
return super.doStartTag();
}
I tested this code in a Liferay portlet, but I believe it should work in other contexts anyway. If it don't, I would like to know :)
HTH
what you really need to have is this:
<mytaglib:doSomething>
<c:out value="My enclosed tag"/>
Test
</mytaglib:doSomething>
and change your doTag to something like this
#Override public void doTag() throws JspException, IOException {
try {
BodyContent bc = getBodyContent();
String body = bc.getString();
// do something to the body here.
JspWriter out = bc.getEnclosingWriter();
if(body != null) {
out.print(buff.toString());
}
} catch(IOException ioe) {
throw new JspException("Error: "+ioe.getMessage());
}
}
make sure the jsp body content is set to jsp in the tld:
<bodycontent>JSP</bodycontent>
Why do you write a JSTL tag inside your doTag method?
The println is directly going into the compiled JSP (read: servlet) When this gets rendered in the browser it will be printed as it is since teh browser doesn't understand JSTL tags.
public class MyTaglib extends SimpleTagSupport {
#Override public void doTag() throws JspException, IOException {
getJspContext().getOut().println("My enclosed tag");
getJspBody().invoke(null);
}
}
You can optionally add HTML tags to the string.

Categories