JSF Ajax addClientBehavior gives null.pointer.exception - ajax

I'm trying to add programatically an Ajax client behavior to a custom component but when I do I get a null.pointer.exception (as an Alert in the browser no error in the logs), if I add the behavior in the .xhtml it works fine but I really need to add them programatically (actually the component is going to be rendered dinamically from a top component (dashboard -> N columns -> N widgets per column all from a Database)
I have tested this creating a simple DataList component
Here is the relevant code...
DataListRenderer
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException{
DataList datalist = (DataList)component;
ResponseWriter writer = context.getResponseWriter();
.. bunch of rendering options....
// If sortable then we add the sortable script.
// This basically ends up generating a call to jsf.ajax.request(source,event,params);
if (sortable != null && sortable.equalsIgnoreCase("true")) {
ScriptUtils.startScript(writer, clientId);
writer.write("$(function() {");
writer.write("$(EasyFaces.escapeId('" + clientId + "')).sortable({");
writer.write("update: function (event, ui) { ");
writer.write(new AjaxRequest().addEvent(StringUtils.addSingleQuotes("update"))
.addExecute(StringUtils.addSingleQuotes(datalist.getClientId()))
.addSource(StringUtils.addSingleQuotes(datalist.getClientId()))
.addOther("sourceId", "ui.item.attr('id')")
.addOther("dataValue", "ui.item.attr('data-value')")
.addOther("dropedPosition", "ui.item.index()")
.getAjaxCall());
writer.write(" } ");
encodeClientBehaviors(context, datalist);
writer.write("});");
writer.write("});");
ScriptUtils.endScript(writer);
}
// This is where I add the behavior
AjaxBehavior ajaxBehavior = (AjaxBehavior) FacesContext.getCurrentInstance().getApplication().createBehavior(AjaxBehavior.BEHAVIOR_ID);
ajaxBehavior.setRender(Arrays.asList("#form"));
ajaxBehavior.setExecute(Arrays.asList("#form"));
MethodExpression listener = FacesContext.getCurrentInstance().getApplication()
.getExpressionFactory().createMethodExpression(context.getELContext(),"#{dataListManager.updateModel}", null,
new Class[] { AjaxBehaviorEvent.class });
ajaxBehavior.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(listener));
datalist.addClientBehavior(datalist.getDefaultEventName(), ajaxBehavior);
}
... rest of the code
Now the .xhtml is as follows:
...
h:form>
<et:dataList id="dl" value="#{easyfacesBean.data}" itemValue="foo" var="xx" sortable="true">
<h:outputText id="txt" value="#{xx}" />
</et:dataList>
</h:form>
...
This renders the code Ok, the list actually can be ordered but when re-ordered it gives me the null.pointer.exception error
This is what comes back from the server:
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><error><error-name>class java.lang.NullPointerException</error-name><error-message><![CDATA[]]></error-message></error></partial-response>
Now, If I comment this line
datalist.addClientBehavior(datalist.getDefaultEventName(), ajaxBehavior);
And simply add the tag like so:
<h:form>
<et:dataList id="dl" value="#{easyfacesBean.data}" itemValue="foo" var="xx" sortable="true">
<f:ajax />
<h:outputText id="txt" value="#{xx}" />
</et:dataList>
</h:form>
Everything works fine.. any ideas? I would settle for a way to actually know where the null.point.exception is ..
BTW if I don't comment the line that actually add's the behavior and add the < f:ajax > tag the error changes to java.lang.IndexOutOfBoundsException
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><error><error-name>class java.lang.IndexOutOfBoundsException</error-name><error-message><![CDATA[Index: 1, Size: 1]]></error-message>
Regards!

Related

JSF Displaying Text in modal if INSERT operation was successful

What is the correct way to return a value from a method in a managed bean indicating a successful SQL DML operation such as INSERT or UPDATE
Based on the tutorials and some blogs I read online, it says that a good practice in returning values from a method contained in a ManagedBean is a String value of a facelet or the .xhtml page
(in other words, a view) to redirect to a webpage.
Like this.
Original version:
#ManagedBean(name="myBean")
public class MyBean{
public String register(){
String SQL = "INSERT INTO myTable(col1,col2) VALUES(?,?);
PreparedStatement ps = connection.prepareStatement(SQL);
ps.setString(1,someStringVariable1);
ps.setString(2,someStringVariable2);
ps.executeUpdate();
return "index"; //pointing to index.xhtml
}
}
How about if i want to know if the executeUpdate() method was successful?
I thought I'd just change it to something like
Modified version:
public int register(){
int isSuccessful = 0;
try{
String SQL = "INSERT INTO myTable(col1,col2) VALUES(?,?);
PreparedStatement ps = connection.prepareStatement(SQL);
ps.setString(1,someStringVariable1);
ps.setString(2,someStringVariable2);
isSuccessful = ps.executeUpdate();
}
return isSuccessful;
}
However, on the modified version I returned an int which I don't see as correct as per how JSF should work with ManagedBean (Please correct me if i'm wrong)
I asked because say I have a Twitter Bootstrap modal which has the following.
<div class="modal-body">
<h:form>
//....some code here...
<h:commandButton value="Submit" action=#{myBean.register()}
<h:outputText value=" #{myBean.whatToPutHere_ToKnowIf_addData()wasSuccessful}" />
</h:form>
</div>
I need to be able to show within the modal div that register() execution was successful.
What is the simplest and correct way to accomplish that?
I read somewhere that AJAX will help but right now, I have very little knowledge of AJAX so maybe a simple solution to this is better.
I'd appreciate any help.
Thank you.
You can use a bean variable:
#ManagedBean(name="myBean")
public class MyBean {
private boolean isSuccessful = false;
public boolean isSuccessful() { return isSuccessful; }
public String register(){
isSuccessful = ...
}
}
and in your xhtml
....
<h:commandButton value="Submit" action="#{myBean.register()}" />
<f:ajax execute="#form" render="outtext" />
</h:commandButton>
<h:panelGroup id="outtext">
<h:outputText value="any Text" rendered="#{myBean.successful} />
</h:panelGroup>
</h:form>

How to pass a param through a Ajax request

My objective is to save the current cursor position and append new values to it for every new button we enter.To achive it i am trying to send a ajax request and update my back end coordinated every time is focus out of the input field.
I am succesfull i calling the java script function before calling by backing bean action method.But for some reason i am unable to see my request param values when ever i make a ajax request.
<p:inputText id="testing1" value="#{dropDownView.city}">
<p:ajax event="keyup" onstart="callOnAjax();" listener="#{dropDownView.assignCity()}" execute="#this" update="out1" >
<f:param value="test" name="#{articlePromo.promocionArticuloId}"/>
<h:inputHidden id="x" value="#{bean.x}" />
</p:ajax>
<script type="text/javascript">
function callOnAjax(){
$("#detailsPanel").bind("keydown keypress mousemove", function() {
var $form = jQuery(this).closest("form");
$form.find("input[id$=':x']").val($(this).caret().start);
alert("Current position: " + $(this).caret().start);
});
}
</script>
And in my dropDownView Controller
public void assignCity()
{
System.out.println("positon of x"+getX()+"position of y"+y);
FacesContext context = FacesContext.getCurrentInstance();
String id = context.getApplication().evaluateExpressionGet(context, "#{articlePromo.promocionArticuloId}", String.class);
city =country;
}
I tried all different approaches using hidden as well.But i dont see the value in my controller.I even hard coded the request param value and hidden attribute value.But still not succesfull.Any help is much appreciated.

Primefaces how to toggle a dashboard widget/panel visibility using ajax?

I have a dashboard with a considerable number of widgets / panels which are working just fine.
I'm looking for a way to toggle the visibility of a specific one using a commandButton ction listener without having to refresh the page, i.e. via AJAX.
<p:dashboard id="board" model="#{dashboardBean.model}">
<!-- iteration code begins -->
<p:panel id="#{wdgt.code}" header="#{wdgt.title}">
<h:outputText value="One of the dozens of widgets" />
</p:panel>
<!-- iteration code ends -->
<p:panel id="staticWdgtId" header="Static Widget Initially Invisible" visible="false">
Some static content
</p:panel>
</p:dashboard>
Then in the backing bean, at some point this action needs to be fired via a commandButton or an actionListener...
public void showTheWidget() {
DashboardColumn dbc = this.model.getColumn(1);
dbc.getWidget(2); // does not get a widget object with a visibility attribute :((
// so that I could manipulate such as dbc.getWidget(2).setVisible(true);
}
Any ideas?
STATIC APPROACH
You can associate the panel with a boolean.
Panel
<p:panel id="staticWdgtId" header="Static Widget Initially Invisible"
visible="#{bean.panelShow}">
Some static content
</p:panel>
Button
<p:commandButton actionListener="#{bean.actionListener()}"
value="Button"
update=":staticWdgtId" />
Bean
public void actionListener() {
setShowPanel(true);
}
DYNAMIC APPROACH
Render all the panel with display: none
Dashboard
<p:dashboard id="board" model="#{dashboardBean.model}">
<p:panel id="#{wdgt.code}" header="#{wdgt.title}" style="display: none">
<h:outputText value="One of the dozens of widgets" />
</p:panel>
</p:dashboard>
remoteCommand
<p:remoteCommand name="panelsToShow"
actionListener="#{bean.panelsToShowAction()}"
oncomplete="handleComplete(xhr, status, args)" />
bean.panelsToShowAction() you need Gson
public void panelsToShowAction() {
List<String> panels = new ArrayList<String>();
//iterate over the panels you want to show, and put #{wdgt.code} which is the id of the panel
panels.add("Code1");//id
panels.add("Code2");//id
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.addCallbackParam("panels", new Gson().toJson(panels));
}
JS
$(document).ready(function() {
panelsToShow();
})
function handleComplete(xhr, status, args) {
var panels = eval('(' + args.panels + ')');
for (var i = 0, len = panels.length; i < len; i++) {
$('#'+panels[i]).show();
}
}

Styling UIInputs that fail validation

the problem
I'm trying to work with form validation in jsf 1.2. I have a form with rows of two input text fields.
I enter two rows of data, with one bad cell, like this:
| :) | :/ |
| :) | :) |
The validator is called once for each row, but checks both fields.
Each UIInput that fails validation is added to a list of failed UIComponents.
The method for the submit action finally gets to run.
First it restores any saved styles.
Then it loops over the failed UIComponents.
Inside the loop, it saves the current style, then sets the style to "badInput".
But when the page loads, both end-cells have the "badInput" style:
| :) | :/ |
| :) | :/ |
my code
This is my validator, a method on the managed bean that handles this page:
public void validateTime(FacesContext context, UIComponent component, Object value)
{
UIInput out = (UIInput) component.findComponent("out");
for (UIComponent uic : Arrays.asList(component, out))
{
String time = (String) ((UIInput)uic).getSubmittedValue();
if (!StringToTime.isValid(time))
{
// mark that we found invalid times
validTimes = false;
// save the failed component
// the click method will change the style during the render phase
failedUics.add(uic); // List<UIComponent>
badComps.put(uic.getClientId(context), uic); // Map<String, UIComponent>
}
}
}
And here's the table of input fields:
<h:dataTable binding="#{entryHandler.tableAttends}" value="#{entryHandler.attends}" var="range">
<h:column>
<div>
<h:outputLabel>
<h:outputText value="In: " />
<h:inputText value="#{range.start}" id="in" validator="#{entryHandler.validateTime}" />
</h:outputLabel>
<h:outputLabel>
<h:outputText value="Out: " />
<h:inputText value="#{range.end}" id="out" />
</h:outputLabel>
<h:commandLink action="#{entryHandler.delAttend}" value="X" styleClass="removeTime" />
</div>
</h:column>
</h:dataTable>
I've tried applying the bad input style these two ways:
for (UIComponent target : failedUics)
{
log.debug("target client id: " + target.getClientId(context));
Map<String, Object> attr = target.getAttributes();
// save the style before changing it
String style = (String) attr.get("styleClass");
originalStyle.put(target.getClientId(context), style);
// add the badInput css class
if (style == null) style = "";
attr.put("styleClass", "badInput " + style);
}
failedUics = new ArrayList<UIComponent>();
and the second:
UIComponent root = context.getViewRoot();
for (String clientId : badComps.keySet())
{
root.invokeOnComponent(context, clientId, new BadInputCallback(originalStyle));
}
badComps = new HashMap<String, UIComponent>();
where this is the callback function:
private static class BadInputCallback implements ContextCallback
{
private final Map<String, String> originalStyle;
public BadInputCallback(Map<String, String> originalStyle)
{
this.originalStyle = originalStyle;
}
#Override
public void invokeContextCallback(FacesContext context, UIComponent target)
{
Map<String, Object> attr = uic.getAttributes();
// save the style before changing it
String style = (String) attr.get("styleClass");
originalStyle.put(target.getClientId(context), style);
// add the badInput css class
if (style == null) style = "";
attr.put("styleClass", "badInput " + style);
}
}
Your concrete problem is caused because there is physically only one input component in the component tree, whose state changes whenever the parent UIData component iterates over every item of the model. When you want to set the styleClass dynamically, you basically need to let it depend on the currently iterated item, like so:
<h:dataTable ... var="item">
<h:column>
<h:inputText ... styleClass="#{item.bad ? 'badInput' : ''}" />
</h:column>
</h:dataTable>
Or when you're already on JSF 2.x, then check UIInput#isValid() instead whereby the UIInput is referenced via implicit EL variable #{component}, like so:
<h:dataTable ... var="item">
<h:column>
<h:inputText ... styleClass="#{component.valid ? '' : 'badInput'}" />
</h:column>
</h:dataTable>
This problem is already identified before and taken into account in among others the JSF 1.2 targeted SetFocusListener phase listener on The BalusC Code and the JSF 2.0 <o:highlight> component of JSF utility library OmniFaces.
Both have under the covers the same approach: they collect the client IDs of all invalidated input components and pass them as an array to JavaScript code which in turn sets the desired class name via HTML DOM.
See also:
What exactly is #{component} in EL?
how to set ui-state-error class to h:selectOneMenu on validation error
Styling input component after validation failed
Eclipse errors on #{component.valid}: "valid cannot be resolved as a member of component”

h:outputLink with f:ajax - method called, but link not shown

This does not work
<h:form style="display: inline;">
<h:outputLink value="#{title.link}" >
#{msg['g.readMore']}
<f:ajax event="click" immediate="true" listener="#{titlesBean.titleClicked(title.id)}" />
</h:outputLink>
</h:form>
What I want it to do is when clicked to call #{titlesBean.titleClicked(title.id)} and then go to the link. The method is called but it doesn't go to the link. There are several other ways to do it (with commandLink and then a redirect, but I would like to know why this is not working).
This is the method itself:
public String titleClicked(long titleId) {
this.titlesManager.addXtoRating(titleId, 1);
return null;
}
Note: this is only a sidenote, but I accidentally found out that this works:
<script type="text/javascript">
$('.share').popupWindow({centerBrowser:1,height:380,width:550});
</script>
<h:form style="display: inline;">
<h:outputLink styleClass="share" value="http://www.facebook.com/sharer.php...">
<img src="images/facebook-icon.jpg" />
<f:ajax event="click" immediate="true" listener="#{titlesBean.titleLiked(title.id)}" />
</h:outputLink>
</h:form>
Check out the styleClass="share"
Update: (I have less than 100 rep, so I cannot answer my own question for 8 hours, this is how to put it delicately - stupid).
I waited for a while, but nobody answered.
So this is my hacked solution ( I don't like it at all, but it works):
<h:form style="display: inline;">
<h:outputLink target="_blank" styleClass="click8" value="#{title.link}" >
#{title.heading}
<f:ajax event="click" immediate="true" listener="#{titlesBean.titleLiked(title.id)}" />
</h:outputLink>
</h:form>
And this is the important part:
<h:head>
<script type="text/javascript">
$(document).ready(function(){
$('.click8').click(function (event){
var url = $(this).attr("href");
window.open(url, "_blank");
event.preventDefault();
});
});
</script>
</h:head>
Note: this has to be in the header, otherwise I had a major bug with the link opening a thousand windows.
It does not work because there's means of a race condition here. Two HTTP requests are been sent simultaneously in the same window. One ajax to the server and one normal to the given link. The one which finishes sooner wins. You want to send the HTTP requests in sync. First the ajax one to the server and when it returns, then the normal one to the given link.
As to your hacky solution, it works because it uses JavaScript to open the URL in a new window instead of the current one and then blocks the link's default action, so the normal response just arrives in a completely separate window while the ajax response still arrives in the initial window. So there's no means of a race condition of two HTTP requests in the initial window anymore.
As to the final solution, this is not possible with standard set of JSF 2.0 components. Using <h:commandLink> and then doing a redirect is indeed doable, but the link is this way not crawlable by searchbots and it fires effectively a POST request, which is IMO more worse than your new window solution.
If you would really like to open the link in the current window, hereby keeping the target URL in the link's href, then I'd suggest to create a simple servlet which does the link tracking and redirecting job and let jQuery manipulate the link target during onclick.
Something like this
<a rel="ext" id="ext_#{title.id}" href="#{title.link}">read more</a>
(HTML element IDs may not start with a digit! Hence the ext_ prefix, you can of course change this whatever way you want.)
with
$(function() {
jQuery('a[rel=ext]').click(function(e) {
var link = jQuery(this);
var url = 'track'
+ '?id=' + encodeURIComponent(link.attr('id'))
+ '&url=' + encodeURIComponent(link.attr('href'));
if (link.attr('target') == '_blank') {
window.open(url);
} else {
window.location = url;
}
e.preventDefault();
});
});
and
#WebServlet(urlPatterns={"/track"})
public class TrackServlet extends HttpServlet {
#EJB
private TrackService trackService;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String url = request.getParameter("url");
if (id == null || url == null) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST);
return;
}
trackService.track(id.replaceAll("\\D+", "")); // Strips non-digits.
response.sendRedirect(url);
}
}

Resources