Charts not visible on the page - java

EDIT
Finally figured it out. You need to add this to your project. Probably a good thing to document:
http://www.jqplot.com/
No chart is displaying on the page, even though the code of the javascript etc is available through Firebug.
I am using Mojarra and Primefaces 3
<h:form>
<p:growl id="growl" showDetail="true" />
<p:pieChart value="#{distributionChart.pieModel}" legendPosition="w"
title="Interactive Pie Chart" style="width:400px;height:300px">
<p:ajax event="itemSelect" listener="#{distributionChart.itemSelect}" update="growl" />
</p:pieChart>
</h:form>
Backing bean
#Named
#RequestScoped
public class DistributionChart implements Serializable {
#Inject
private QuestionServiceBean questionService;
private CartesianChartModel categoryModel;
private PieChartModel pieModel;
private List<QuestionCategoryDistribution> distribution;
#PostConstruct
public void init() {
distribution = questionService.getQuestionCategoryDistribution();
createPieModel();
}
public void itemSelect(ItemSelectEvent event) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Item selected",
"Item Index: " + event.getItemIndex() + ", Series Index:" + event.getSeriesIndex());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public PieChartModel getPieModel() {
return pieModel;
}
private void createPieModel() {
pieModel = new PieChartModel();
for (QuestionCategoryDistribution obj : distribution) {
pieModel.set(obj.getCategoryDescription(), obj.getNumberOfQuestions());
}
}
}

Related

JSF Order of operations, should converters be applied before validators?

Are JSF converters supposed to be applied before validators? We have a situation where it seems it's being applied before the converter.
<o:importConstants
type="com.xxx.enums.UsState"
var="UsState" />
<b:selectOneMenu
id="homeStateSelectOneMenu"
value="#{contactPage.contact.homeState}"
label="Home State"
converter="DisplayableTextConverter">
<f:selectItem
id="selectOneUsStateSelectItem"
itemLabel="Select One"
noSelectionOption="true"
itemDisabled="true" />
<f:selectItems
id="usStateSelectItems"
value="#{UsState}" />
</b:selectOneMenu>
and the model object has this field:
#Enumerated(EnumType.STRING)
#Column(name = "home_state")
#NotNull //LYNCHPIN
private UsState homeState;
Converter:
#ApplicationScoped
#FacesConverter(value = "DisplayableTextConverter", managed = true)
public class DisplayableTextConverter implements Converter<DisplayableText> {
public static final String STATE_KEY = "DisplayableTextConverter.forClass";
#SuppressWarnings("unchecked")
#Override
public DisplayableText getAsObject(final FacesContext context, final UIComponent component, String text) {
text = trimToNull(text);
if (text != null) {
final String className = (String) component.getTransientStateHelper().getTransient(STATE_KEY);
try {
return DisplayableText.parseEnum(text, (Class<DisplayableText>) Class.forName(className));
} catch (final ClassNotFoundException e) {
throw new RuntimeException(e);
}
} else {
return null;
}
}
#Override
public String getAsString(final FacesContext context, final UIComponent component, final DisplayableText displayableText) {
if (displayableText != null) {
component.getTransientStateHelper().putTransient(STATE_KEY, displayableText.getClass().getName());
return displayableText.getDisplayText();
} else {
return null;
}
}
}
Enum: (truncated)
public enum UsState implements DisplayableText {
AL("Alabama"), AK("Alaska"), AZ("Arizona"), AR("Arkansas"), ....
public final String displayText;
#Override
public String getDisplayText() {
return displayText;
}
UsState(String specificDisplayValue) {
displayText = specificDisplayValue;
}
}
So what's interesting is if we remove #NotNull, the form submits, and if we add it, the submission fails. Looking at the stack trace, it appears that when the #NotNull it appears the validator is being called before the converter in certain cases. Why would this be?
Here is No #NotNull:
java.lang.IllegalArgumentException: Arkansas is not an instance of class com.xxx.UsState
at org.apache.bval.jsr.job.ValidateProperty.<init>(ValidateProperty.java:515)
at org.apache.bval.jsr.job.ValidationJobFactory.validateValue(ValidationJobFactory.java:76)
at org.apache.bval.jsr.ValidatorImpl.validateValue(ValidatorImpl.java:65)
at org.apache.bval.jsr.CascadingPropertyValidator.validateValue(CascadingPropertyValidator.java:99)
at javax.faces.validator.BeanValidator.validate(BeanValidator.java:218)
at javax.faces.component._ComponentUtils.callValidators(_ComponentUtils.java:291)
at javax.faces.component.UIInput.validateValue(UIInput.java:489)
at net.bootsfaces.component.selectOneMenu.SelectOneMenu.validateValue(SelectOneMenu.java:118)
at net.bootsfaces.component.selectOneMenu.SelectOneMenuRenderer.decode(SelectOneMenuRenderer.java:96)
at javax.faces.component.UIComponentBase.decode(UIComponentBase.java:479)
at javax.faces.component.UIInput.decode(UIInput.java:371)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1408)
at javax.faces.component.UIInput.processDecodes(UIInput.java:207)
at javax.faces.component.UIComponentBase.processDecodes(UIComponentBase.java:1402)
at javax.faces.component.UIForm.processDecodes(UIForm.java:154)
at org.apache.myfaces.context.servlet.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:775)
and here is without the #NotNull (breakpoint in DisplayableTextConverter):
at com.xxx.jsf.converter.DisplayableTextConverter.getAsObject(DisplayableTextConverter.java:21)
at com.xxx.jsf.converter.DisplayableTextConverter.getAsObject(DisplayableTextConverter.java:1)
at org.apache.myfaces.cdi.converter.FacesConverterCDIWrapper.getAsObject(FacesConverterCDIWrapper.java:63)
at net.bootsfaces.render.CoreRenderer.getConvertedValue(CoreRenderer.java:532)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:789)
at javax.faces.component.UIInput.validate(UIInput.java:708)
at javax.faces.component.UIInput.processValidators(UIInput.java:293)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1458)
at javax.faces.component.UIForm.processValidators(UIForm.java:210)
at org.apache.myfaces.context.servlet.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:779)
Thanks! This is running on Apache TomEE 8.0.6 but with MyFaces 2.3.8, Bootsfaces 1.5.0

NullPointer Exception - JSF Event Handling ( ValueChangeListener )

I am learning JSF Event Handling and when I try to run some sample code, I am getting a Null Pointer Exception.
This is my index.xhtml snippet,
<h:form>
<h2>Implement valueChangeListener</h2>
<hr />
<h:panelGrid columns="2">
Selected Locale:
<h:selectOneMenu value="#{userData.selectedCountry}" onchange="submit()">
<f:valueChangeListener type="com.cyb3rh4wk.test.LocaleChangeListener" />
<f:selectItems value="#{userData.countries}" />
</h:selectOneMenu>
Country Name:
<h:outputText id="countryInterface" value="#{userData.selectedCountry}" />
</h:panelGrid>
</h:form>
UserData.java
#ManagedBean(name = "userData", eager = true)
#ApplicationScoped
public class UserData implements Serializable{
private static Map<String, String> countryMap;
private String selectedCountry = "United Kingdom";
static {
countryMap = new LinkedHashMap<String, String>();
countryMap.put("en", "United Kingdon");
countryMap.put("fr", "French");
countryMap.put("de", "German");
countryMap.put("def", "Default");
}
public String getSelectedCountry() {
return selectedCountry;
}
public void setSelectedCountry(String selectedCountry) {
this.selectedCountry = selectedCountry;
System.out.println("Locale set");
}
public Map<String, String> getCountries() {
return countryMap;
}
public void localeChanged(ValueChangeEvent event) {
selectedCountry = event.getNewValue().toString();
}
}
LocaleChangeListener.java
public class LocaleChangeListener implements ValueChangeListener {
#Override
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
UserData userData = (UserData) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userData");
String newLocale = event.getNewValue().toString();
if (newLocale != null)
userData.setSelectedCountry(newLocale);
else
userData.setSelectedCountry("Default");
}
}
When I run these on Glassfish Server, I get an error,
java.lang.NullPointerException
at com.cyb3rh4wk.test.LocaleChangeListener.processValueChange(LocaleChangeListener.java:25)
at com.sun.faces.facelets.tag.jsf.core.ValueChangeListenerHandler$LazyValueChangeListener.processValueChange(ValueChangeListenerHandler.java:128)
at javax.faces.event.ValueChangeEvent.processListener(ValueChangeEvent.java:134)
Can anyone help me with this ?
You are getting NullPointerException because userData is not found in the session scope.
The reason this is happening is that you put the userData in the application scope (#ApplicationScoped annotation on your managed bean) and searching it in the session scope.
Eventhough you verified that userData is null it still prints Locale set because the bean is in the application scope as described in 2. above.
So what is the solution? Either change #ApplicationScoped to #SessionScoped or access your userData by changing:
UserData userData = (UserData) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("userData");
to
FacesContext ctx = FacesContext.getCurrentInstance();
UserData userData = (UserData)ctx.getExternalContext().getApplicationMap().get("userData");

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

Can't update password using Hibernate

I'm using Hibernate + JSF + PrimeFaces. Now I wanna update password of admin but I always get error dialog. I can't figure out what wrong in my code. Hope anyone suggest me.
loginBean (SessionScoped)
public class loginBean {
private Users username;
private UsersDao userdao;
/** Creates a new instance of loginBean */
public loginBean() {
userdao = new UsersDao();
username = new Users();
}
public Users getUsername() {
return username;
}
public void setUsername(Users username) {
this.username = username;
}
public void updateUser(){
String msg;
if(userdao.updateUser(username)){
msg = "Updated Successfully!";
}else{
msg = "Error. Please check again!";
}
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, null);
FacesContext.getCurrentInstance().addMessage(msg, message);
}
}
UserDAO.java
public class UsersDao {
public boolean updateUser(Users user){
boolean flag;
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
try{
session.beginTransaction();
session.save(user);
session.beginTransaction().commit();
flag = true;
}catch(Exception e){
flag = false;
session.beginTransaction().rollback();
}
return flag;
}
}
xhtml
<p:growl id="growl" showDetail="true" life="3000" />
<h:form id="tab">
<h:outputLabel>Password</h:outputLabel>
<h:inputSecret value="#{loginBean.username.password}" />
<p:commandButton id="loginButton" value="Login" update=":growl" ajax="false" action="#{loginBean.updateUser}"/>
</h:form>
You're actually performing a save operation into the Session, instead of an update one, that's why you've got a Violation of PRIMARY KEY exception. You're telling Hibernate to add a new user with the same credentials, which is constrained by the Data Base.
In addition, and unrelated to the concrete problem, you should change your Users class name to User, as it refers to a concrete user.

How to populate certain text field after selecting item from <h:selectOneMenu /> JSF 2.0

i want that, when user select item in a inputText field populates with data from database.
I have a select menu list:
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
<f:selectItems value="#{controller.listOfId()}" />
</h:selectOneMenu>
and let's say have input text like this:
<h:inputText value="In here we place value from backing bean"></h:inputText>
How can i make after selecting an item from a list(which holds the id) populate text field with other data from my backing bean(let's say a name).
Here is my backingBean:
#ManagedBean(name = "controller")
#SessionScoped
public class Bean implements Serializable {
private Catalog current;// here i'm holding int id, String name and other stuff...
private DataModel items = null;
#EJB
private probaSession.CatalogFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public KatalogController() {
}
public Katalog getSelected() {
if (current == null) {
current = new Catalog();
selectedItemIndex = -1;
}
return current;
}
private KatalogFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
//......
public ArrayList<Catalog> listOfId() {
ArrayList<Catalog> list=new ArrayList<Catalog>();
try{
String upit="select id from Catalog";
Statement st=connection.createStatement();
ResultSet rs=st.executeQuery(upit);
while(rs.next()) {
Katalog k=new Katalog();
k.setId(rs.getInt(1));
k.setName(rs.getString(2));
list.add(k);
}
disconnect();
}
catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
and that's pretty much it.
I'm here if anything needs to explaining. It think it is easy(using ajax let's say) but i don't even know how to start doing it...
You must add an f:ajax (that is standard, many component library offer extended versions) to catch a change event in the inputText
<h:selectOneMenu id="blah" value="#{controller.selected.id}" title="#{bundle.CreateTitle_id}" >
<f:selectItems value="#{controller.listOfId()}" />
<f:ajax
event="change" <-- The event to capture. I believe that if not specified
there is a default event to capture from
each component (for inputText it would be "change")
render="myForm:foo" <-- Only repaint "blah"
listener="#{controller.myBlahListener}"
</h:selectOneMenu>
<h:inputText id="foo" value="#{controller.fooText}"/>
Your listener will read the new value in this.getSelected().getId(), and change the model so that controller.getFooText() returns the new value (the easiest way probably is this.setFooTest(this.getSelected().getId(), but that depends of your model.

Categories