How to specify command attribute in h:inputText? - jsf

I have a function that I derclare beans in my manager and I want to return the value in inputText but when I put the name of my function in the value attribute of inputText tag like this:
<p: inputText value = "#{ticketBean.getLastIndexTache} "/>
this error appear:
Etat HTTP 500 - /pages/test.xhtml #13,106 value="#{ticketBean.getLastIndexTache}": Property 'getLastIndexTache' not found on type com.bean.TicketBean
here is the java code
#ManagedBean(name="ticketBean")
public class TicketBean {
public int getLastIndexTache() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
int index = 0;
try {
session.beginTransaction();
String sql = "select MAX(t.IDTICKET) from ticket t ";
Query query = session.createSQLQuery(sql);
if( query.uniqueResult()==null){
index=0;
}else{
index=(int) query.uniqueResult();
index=index+1;
}
} catch (HibernateException e) {
// TODO: handle exception
session.getTransaction().rollback();
e.printStackTrace();
}
return index;
}
}

You should use the bean property in value like
<p:inputText value="#{ticketBean.lastIndexTache}"/>
as JSF by itself adds "get" to the property name. Currently it will look for the method getGetLastIndexTache().
Besides its very bad practice to have logic in any getter as they are called multiple times by JSF. Instead you should make an property like
private Integer lastIndexTache; // +getter/setter
and set the value in a #PostConstruct method:
#PostConstruct
public void init() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
// etc....
lastIndexTache = index;
}
The getter would then simply be
public Integer getLastIndexTache() {
return lastIndexTache;
}
and don't forget a setter:
public void setLastIndexTache(Integer newValue) {
lastIndexTache = newValue;
}
Also you should probably put a scope on the bean (for example #ViewScoped).

Related

My sessionscoped bean does not have values stored on every refresh

I have a SessionScoped Bean which consists of a list and a flag. The list populates a datatable in the xhtml view.
On first load, the list is populated. Every other load should not repopulate the list but it does despite the check. This behaviour also holds for postbacks on commandLinks clicks.
#ManagedBean(name = "customerSegmentInfo")
#SessionScoped
public class CustomerSegmentInfo extends BasePage implements Serializable {
private boolean isNBACalled = false;
private List<NextBestActionDTO> nextBestActionList = null;
public List<NextBestActionDTO> getNextBestActionList() {
log.debug("----- nbaCalled: " + isNBACalled);
if(nextBestActionList == null && !isNBACalled){
log.debug("-------- getNextBestAction");
try {
nextBestActionList = this.getNbaService().getNextBestAction(this.getCustomerInfo().getCountryCode(), this.getCustomerInfo().getCustomerNo());
log.debug("---- " + nextBestActionList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
log.debug("------ error calling nba service bean " + e);
}
isNBACalled = true;
log.debug("----- nbaCalled: " + isNBACalled);
}
return nextBestActionList;
}
public void setNextBestActionList(List<NextBestActionDTO> nextBestActionList) {
this.nextBestActionList = nextBestActionList;
}
}
As the list is not null from last page load and flag also set to true, the call getNextBestAction shouldnt be made, but in logs the flag is false and apparently the list is null too.
the behaviour is irregular
On certain loads it behaves as expected on others not.
I Tried setting the javax.faces.STATE_SAVING_METHOD context parameter in the web.xml to both server and client, nothing changed.
Thank you in advance

Bean doesn't dispatch to another page

I've a problem with a bean that doesn't dispatch the response to another page.
This is the code:
#ManagedBean(name = "ssoServiceBean")
public class SSOServiceBean {
#ManagedProperty(value="#{param.samlRequest}")
private String samlRequest;
#ManagedProperty(value="#{param.relayState}")
private String relayState;
#PostConstruct
public void submit() {
System.out.println("1) PostConstruct method called");
//samlRequest = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("samlRequest");
//relayState = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("relayState");
processResponse();
}
//getters and setters omitted for succinctness
private void processResponse(){
System.out.println("2) Processing response");
String uri;
if(samlRequest != null && !samlRequest.equals("") && relayState != null && !relayState.equals("")) {
System.out.println("SAMLRequest: "+samlRequest);
System.out.println("RelayState: "+relayState);
uri = "challenge.xhtml";
System.out.println("3) Sending challenge...");
} else {
uri = "dashboard.xhtml";
System.out.println("3) Sending dashboard...");
}
try {
FacesContext.getCurrentInstance().getExternalContext().dispatch(uri);
System.out.println("4) Done.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem is that the dispatch() method doesn't work properly, and seems to be ignored.
Infact the system responses with an error of the related bean's page ssoservice.xhtml
I've used the Postconstruct annotation because with this bean I've to intercept POST parameters that come from a third-party page.
Once I've received the post parameters, I've to render the challenge.xhtml page, WITHOUT using a redirect directive.
Nextly, the user will submit challenge.xhtml to the related bean ChallengeBean.java .
So, what is the problem? Why dispatch doesn't work?

PrimeFaces switch with initial value

I have a PrimeFaces inputSwitch:
<p:inputSwitch id="snoozeSwitch" value="#{dashBController.snooze}" valueChangeListener="#{dashBController.updateSnoozeStatus}">
<p:ajax listener="#{dashBController.updateSnoozeStatus}" update="msgSnooze" />
</p:inputSwitch>
Now I want to give this switch an initial value from my DB. I get the value with:
#PostConstruct
public void init() {
if (!FacesContext.getCurrentInstance().isPostback()) {
snooze = getSnoozeStatus();
}
}
But I have trouble to update the old value with the new one.
public void updateSnoozeStatus() {
if(snooze == true) {
DBconnector.updateSnooze("true");
} else {
DBconnector.updateSnooze("false");
}
}
The problem: My app always uses the inital value and so the switch is stucking on the state it has originally. Maybe #BalusC knows the answer :)
Unless I am missing something your solution seems complex for something very simple. Why don't you just use a getter and a setter?
The getter should load the value from the database and the setter should save it. I couldn't test the code below because I don't have PF 5.0.4 but it should be a good start.
public class DashBController {
private Boolean snooze = null;
public boolean isSnooze() {
if (snooze == null) {
snooze = getSnoozeStatus();
}
return snooze;
}
public void setSnooze(boolean snooze) {
this.snooze = snooze;
DBconnector.updateSnooze(this.snooze.toString());
}
}
and simply :
<p:inputSwitch id="snoozeSwitch" value="#{dashBController.snooze}"/>

How to add condition based action to command button in ADF?

How to navigate to the next page based on the return value from the method called inside the action attribute of the command button.
<af:button id="tt_b2"
rendered="#{attrs.nextRendered}"
partialSubmit="true"
action="#{attrs.backingBean.nextAction}"
text="Next"
disabled="#{attrs.nextDisabled}"/>
private static final String NEXT_NAVIGATION_ACTION = "controllerContext.currentViewPort.taskFlowContext.trainModel.getNext";
public String nextAction() {
if (validate()) {
updateModel();
return NEXT_NAVIGATION_ACTION;
}
return null;
}
The use case is done for train model, which is implemented based on this blog : http://javacollectibles.blogspot.co.uk/2014/10/adf-train-template.html
We need to define a generic next action in the template but the action should be called conditionally, based on whether all the validation checks has been passed on not.
Try using ADFUtils.invokeEl
public String nextAction() {
if (validate()) {
updateModel();
return (String)ADFUtils.invokeEL(NEXT_NAVIGATION_ACTION);
}
return null;
}
Its ain't necessary to hardcode any steps, you can query TaskFlowTrainModel
/**
* Navigates to the next stop in a train
* #return outcome string
*/
public String navigateNextStop() {
String nextStopAction = null;
ControllerContext controllerContext = ControllerContext.getInstance();
ViewPortContext currentViewPortCtx = controllerContext.getCurrentViewPort();
TaskFlowContext taskFlowCtx = currentViewPortCtx.getTaskFlowContext();
TaskFlowTrainModel taskFlowTrainModel = taskFlowCtx.getTaskFlowTrainModel();
TaskFlowTrainStopModel currentStop = taskFlowTrainModel.getCurrentStop();
TaskFlowTrainStopModel nextStop = taskFlowTrainModel.getNextStop(currentStop);
//is either null or has the value of outcome
return nextStopAction;
}
Full code of the sample can be found on the ADF Code Corner.
To navigate by taskflow outcomes you just need to provide exact outcome String as return of your method:
private static final String NEXT_NAVIGATION_ACTION = "next";
public String nextAction() {
if (validate()) {
updateModel();
return NEXT_NAVIGATION_ACTION;
}
return null;
}
Can you verify, you can do it in through phase listener.
Verify you condition in the phase listener and allow it to move ahead if it validates else stop the thread execution.
Below is the sample phase listener code.
public class MyPhaseListener implements PagePhaseListener{
public MyPhaseListener() {
super();
}
#Override
public void afterPhase(PagePhaseEvent pagePhaseEvent) {
if (pagePhaseEvent.getPhaseId() == Lifecycle.PREPARE_RENDER_ID ) {
// DO your logic here
}
}
#Override
public void beforePhase(PagePhaseEvent pagePhaseEvent) {
}
}

BeanELResolver #Override getValue(ELContext context, Object base, Object property)

I have
public class ExtendedBeanELResolver extends BeanELResolver {
private static final Pattern regExpDn = Pattern.compile("PLMN-PLMN/\\w+.\\d+(.*)");
#Override
public Object getValue(ELContext context, Object base, Object property)
try {
// remake DIST.NAME appearance
if (property.equals("dn") && base instanceof Alarm && ((Alarm) base).getCustomer().getNameEng().equalsIgnoreCase("mts")) {
String dn = null;
try {
dn = ((Alarm) base).getDn();
Matcher mtch = regExpDn.matcher(dn);
mtch.find();
((Alarm) base).setDn(mtch.group(1));
} catch (Throwable e) {
// logger.error("error in dn - " + dn);
} finally {
return super.getValue(context, base, property);
}
}
}
for change some visible values in object depending on some conditions. I do not want to change value if this called from jsf <ui:param name="fullDistName" value="#{alarm.dn}" />
How i can get id of component from which this EL called?
sorry for my english.
You can get the current JSF component by programmatically evaluating #{component} or by invoking UIComponent#getCurrentComponent().
UIComponent component = UIComponent.getCurrentComponent(FacesContext.getCurrentInstance();
// ...
Please note that this tight-couples your EL resolver to JSF.

Resources