Apache MyFaces JSF2.0 bug: getStateHelper().put doesn't save anything? - java

MyFaces seems to be ignoring my call to getStateHelper.put() in this component:
public class BFTableComponent extends UINamingContainer {
...
private void setCurrentPageNumber(int currentPageNumber) {
getStateHelper().put(PropertyKeys.currentPageNumber, currentPageNumber);
}
public int getCurrentPageNumber() {
return (Integer) getStateHelper().eval(PropertyKeys.currentPageNumber, 0);
}
public void nextPage() {
setCurrentPageNumber(getCurrentPageNumber() + 1);
updateCurrentPage();
}
public void previousPage() {
setCurrentPageNumber(getCurrentPageNumber() - 1);
updateCurrentPage();
}
...
}
As you can see, when the frontend component calls nextPage, the goal is to advance the page number by one. However, when running this in MyFaces, the eval() call will work for the immediate request lifecycle, but the next request, it will return 0. If I put null instead of 0, I gett an NPE.
The pageNumber state needs to carry for the lifetime of the component, not just the current request. What am I doing wrong? This code runs fine under Mojarra, but not in MyFaces.

Turns out it actually was a bug somewhere in MyFaces. I was running this in Apache TomEE beta2. It included MyFaces 2.1.2. I replaced the jars with 2.1.7 and the problem fixed itself.
Thanks for looking!

Related

Wicket DropDownChoice onSelectionChanged method removed after version update

I was designated as a developer to upgrade our old wicket app from 6.x to 8.x. I am resolving multiple errors one by one, but (since I never worked with wicket) one I am unable to move on with.
In version 6.x it had DropDownChoice with overriden onSelectionChanged which no longer exists in version 8.x and I am unable to find any info about deprecation (going through 7.x versions...) so it seems they just removed it .. what are my alternatives here? The aforementioned code:
booleanType = new DropDownChoice<BooleanType>("booleanType", new PropertyModel<>(this, "selectedBooleanType"), booleanTypes) {
#Override
protected void onSelectionChanged(BooleanType newSelection) {
super.onSelectionChanged(newSelection);
selectedBooleanType = newSelection;
}
};
EDIT:
Similar question that I found only later
Wicket 6 to 8 upgrade: RadioGroup.onSelectionChanged() replacement
for those wondering how to update the value since it is not coming as an argument of the method anymore:
selectedType = (YourChoiceType) super.getFormComponent().getDefaultModelObject();
wantOnSelectionChangedNotifications moved to FormComponentUpdatingBehavior. From the changelog:
// Wicket 7.x
new CheckBox("id", model) {
protected boolean wantOnSelectionChangedNotifications() {
return true;
}
protected void onSelectionChanged(Boolean newSelection) {
// do something, page will be rerendered;
}
};
// Wicket 8.x
new CheckBox("id", model)
.add(new FormComponentUpdatingBehavior() {
protected void onUpdate() {
// do something, page will be rerendered;
}
protected void onError(RuntimeException ex) {
super.onError(ex);
}
});
(The example uses a CheckBox but it also applies to DropDownChoice).
For another example see the wiki.

How to disable image loading in CEF/JCEF?

Is there a switch/flag that allows to do this? I spent hours finding those but couldn't find anything that works. The other thing I'm planning to do is intercept the cefRequest by adding my own CefRequestHandler, examine the resource type and if it matches RT_IMAGE, cancel the request. Everything seems easy except the part when I have to cancel a request. How do I stop/block/cancel a cefRequest? I probably should not be doing it this way but it doesn't work anyway:
public class CefClientRequestHandler extends CefRequestHandlerAdapter {
#Override
public boolean onBeforeResourceLoad(CefBrowser cefBrowser, CefFrame cefFrame, CefRequest cefRequest) {
if (cefRequest.getResourceType().equals(CefRequest.ResourceType.RT_IMAGE)) {
cefRequest.setURL("");
}
return false;
}
// more overides
}
Any ideas?
So here's a hack that works. The trick is to change the Request Method to HEAD, and because HEAD requests aren't returned the body, images won't be part of the response.
public class CefClientRequestHandler extends CefRequestHandlerAdapter {
#Override
public boolean onBeforeResourceLoad(CefBrowser cefBrowser, CefFrame cefFrame, CefRequest cefRequest) {
if (cefRequest.getResourceType().equals(RT_IMAGE)) {
cefRequest.setMethod("HEAD");
}
return false;
}
// other overridden methods here...
}
I believe that this approach should be avoided mainly because of the following two reasons:
Changing the method from GET to HEAD does not prevent CEF from making the request to the server. The overhead of opening a connection and handling a request is still there which makes it slower than simply blocking the request.
I'm not sure if images won't be displayed if they are available from browser cache. Currently, I don't know of any methods to test this. Suggestions are welcome.
Edit 1:
Changing URL didn't work in the example I posted in the question because I was passing an empty String as the new URL. If we set the URL to some address that is not an "active" domain name (e.g. https://absolutegarbage-sdjdjfbskdfb.com), the request for that resource fails immediately:
#Override
public boolean onBeforeResourceLoad(CefBrowser cefBrowser, CefFrame cefFrame, CefRequest cefRequest) {
if (cefRequest.getResourceType().equals(CefRequest.ResourceType.RT_IMAGE)) {
cefRequest.setURL("https://yghjbnbk.com");
System.out.println("LOL!");
}
return false;
}
As you can probably guess, this still is not the best solution. Please post an answer or comment if someone has found a better solution.
Edit 2: Finally I have a clean working solution, thanks to user amaitland. We just have to pass a command line switch while setting the CefAppHandler. We can do that by overriding the method onBeforeCommandLineProcessing like this:
CefApp.addAppHandler(new CefAppHandlerAdapter(null) {
#Override
public void onBeforeCommandLineProcessing(String s, CefCommandLine cefCommandLine) {
cefCommandLine.appendSwitch("disable-image-loading");
}
#Override
public void stateHasChanged(CefApp.CefAppState state) {
if (state == CefApp.CefAppState.TERMINATED) System.exit(0);
}
});

Wicket's AjaxSelfUpdatingTimerBehavior stops updating after leaving and re-entering the page

I have this behavior added to a component(MarkupContainer)
AjaxSelfUpdatingTimerBehavior updateBehavior = new AjaxSelfUpdatingTimerBehavior(Duration.seconds(3))
{
#Override
public void onEvent(Component component, IEvent<?> event) {
// some business logic
}
};
Somewhere , on the same page I have an AjaxLink which redirects to another page(in whom constructor I pass the actual page as a parameter) and on that page I have a "Back" AjaxLink which redirects me back , calling setResponsePage(myFirstPage) .
The problem is that even though , when rendering the page the behavior updates once , it stops updating once at 3 seconds , as was constructed for.No problem faced with the behavior until leaving the page.
Probably not the best solution , but I managed to fix it by removing the behavior onBeforeRender() of the page and adding again . I declared a field on the page private int autoUpdateBehaviorId = -1;
public void addUpdateBehavior(Component c)
{
if(autoUpdateBehaviorId >= 0)
c.remove(c.getBehaviorById(autoUpdateBehaviorId));
AjaxSelfUpdatingTimerBehavior updateBehavior = new AjaxSelfUpdatingTimerBehavior(Duration.seconds(3))
{
#Override
public void onEvent(Component component, IEvent<?> event) {
// bussines logic
}
};
c.add(updateBehavior);
autoUpdateBehaviorId = c.getBehaviorId(updateBehavior);
}
#Override
protected void onBeforeRender() {
super.onBeforeRender();
addUpdateBehavior(myContainer);
}
Not necessarily the solution to your problem; but I have implemented the behavior by overriding onConfigure method of the AjaxSelfUpdatingTimerBehavior as below.
In my case, I had to update label with a count of current records in queue every 10 seconds.
Following is code snippet:
labelToBeUpdated.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(configurableDelay)) {
#Override
public void onConfigure(Component component) {
String inProgressOutOfTotal = "10/100"; //Business logic to get total count and inprogress count
labelToBeUpdated.setDefaultModel(Model.of(inProgressOutOfTotal));
//Set visibility of the component if needed
}
}
labelToBeUpdated.setOutputMarkupId(true);
Just curious; is it that onEvent is waiting on an event on the component in order to refresh? Since onConfigure is called before the rendering cycle has begun, it is working for me.
But as Sven Meier has mentioned, you might still want to work on his advise to get your code with onEvent.

Migration to wicket 1.5 - resource (path) issue

I got the task to migrate to wicket 1.4 to wicket 1.5. Despite lack of information in migration guide I was somehow able to refactor most issues. Unfortunetly I'm stuck with "resource" - atm I'm getting this error
java.lang.IllegalArgumentException: Argument 'resource' may not be null.
What I understand by that is that something was change and wicket can no longer "get" to my resources. So I used to have (in wicket 1.4) that piece of code that was responsible for creating image and passing it (the method is in class that extends WebPage) :
private void addImageLogo() {
Resource res = new Resource() {
#Override
public IResourceStream getResourceStream() {
String logo = ConfigurationManager.getInstance().getPathValue(ConfigurationManager.LOGO_FILE_PATH);
return new FileResourceStream(new File(logo));
};
Image logo = new Image("logo", res);
add(logo);
}
Now Resource class no longer exists or I can't find it. While searching internet I was able to change it into this
private void addImageLogo() {
String logoTxt = ConfigurationManager.getInstance().getPathValue(ConfigurationManager.LOGO_FILE_PATH);
ResourceReference res = new ResourceReference(logoTxt) {
#Override
public IResource getResource() {
return null;
}
};
Image logo = new Image("logo", res);
add(logo);
}
This is responsible for obtaining path (and its working): ConfigurationManager.getInstance().getPathValue(ConfigurationManager.LOGO_FILE_PATH)
Unfortunetly I'm still getting this error that I mentioned above. The method getResource() generated automaticly and I believe this is an issue because I'm retuning null but I have no idea what (or how) should I return.
Since it worked with a IResourceStream in 1.4.x then you can just use org.apache.wicket.request.resource.ResourceStreamResource as a IResource for the Image.
Your first code snippet is not complete so I cannot give you exact replacement code.

Vaadin SuperDevMode recompilation fails sometimes, Widget is not rendered as it should and Java code for the Widget is not available

I am trying to set up the SuperDevMode on a Vaadin project.
I have basically 3 problems related to this feature.
I have the following widget (created using the "New Vaadin Widget" wizard, below the code for the client-side widget, connector, state and server-side component):
// Widget:
public class CountedTextFieldWidget extends Composite {
private TextBox textBox = new TextBox();
private Label countLabel = new Label("0");
private HorizontalPanel panel = new HorizontalPanel();
public static final String CLASSNAME = "countedtextfield";
public CountedTextFieldWidget() {
initWidget(panel);
setStylePrimaryName(CLASSNAME);
textBox.setStylePrimaryName(CLASSNAME + "-field");
countLabel.setStylePrimaryName(CLASSNAME + "-label");
setStylePrimaryName(CLASSNAME);
panel.add(textBox);
panel.add(countLabel);
}
public String getText() {
return textBox.getText();
}
public void setText(String text) {
textBox.setText(text);
}
public void setCount(int count) {
countLabel.setText("" + count);
}
public int getCount() {
return Integer.parseInt(countLabel.getText());
}
// HandlerRegistration can be used to remove the key up handler (listener)
// added with this method
public HandlerRegistration addKeyUpHandler(KeyUpHandler handler) {
return textBox.addKeyUpHandler(handler);
}
}
/********************************************************/
// Connector:
#Connect(CountedTextField.class)
public class CountedTextFieldConnector extends AbstractComponentConnector {
public CountedTextFieldConnector() {
getWidget().addKeyUpHandler(new KeyUpHandler() {
#Override
public void onKeyUp(KeyUpEvent event) {
String text = getWidget().getText();
getWidget().setCount(text.length());
}
});
}
#Override
protected Widget createWidget() {
return GWT.create(CountedTextFieldWidget.class);
}
#Override
public CountedTextFieldWidget getWidget() {
return (CountedTextFieldWidget) super.getWidget();
}
#Override
public CountedTextFieldState getState() {
return (CountedTextFieldState) super.getState();
}
#Override
public void onStateChanged(StateChangeEvent stateChangeEvent) {
super.onStateChanged(stateChangeEvent);
final String text = getState().text;
getWidget().setText(text);
getWidget().setCount(text.length());
}
}
/********************************************************/
// State
public class CountedTextFieldState extends com.vaadin.shared.ui.textfield.AbstractTextFieldState {
{
primaryStyleName = null;
}
}
/********************************************************/
// Server-side component:
public class CountedTextField extends com.vaadin.ui.TextField {
#Override
public String getValue() {
return getState().text;
}
public void setValue(String value) {
getState().text = value;
}
#Override
public CountedTextFieldState getState() {
return (CountedTextFieldState) super.getState();
}
}
This widget is rendered as following:
Now, I have followed the following guide on the Vaadin's wiki:
https://vaadin.com/wiki/-/wiki/Main/Using%20SuperDevMode
The CodeServer starts as expected:
The code server is ready.
Next, visit: http://localhost:9876/
But when I open the project and append ?superdevmode to the URL, get the Recompilation failed... message and there's are some errors in the browser's console:
So my first problem is related to this issue:
1) Why does recompilation fail sometimes? And what are those SEVERE: JSONP compile call failed and SEVERE: Timeout Excecution?
Then if I ... click to retry sometimes the superdevmode starts, but the custom widget is not rendered as in the previous screenshot I posted.
Instead, I get a standard Vaadin's v-textfield...
2) WTF... Why? Where is my custom component?
I noticed that I get the same issue also if I open localhost:9876, drag the Dev Mode On button to the bookmarks toolbar and then click on it while on localhost:8080/project. My custom widget is disappears and instead I get the Vaadin's v-textfield widget...
And about the Enable Source Map feature. On the wiki, they say:
To be able to debug Java code in Chrome, open the Chrome Inspector
(right click -> Inspect Element), click the settings icon in the lower
corner of the window and check "Scripts -> Enable source maps".
Refresh the page with the inspector open and you will see Java code
instead of JavaScript code in the scripts tab.
In my Chrome, I don't have a settings icon on the lower corner of the window, I clicked the gear icon on the right and went to General -> Sources and checked Enable JavaScript Source Map (There's no generic Enable source maps entry on my settings tab).
I can see the Java sources, but they are all sources for GWT and Vaadin's components:
So my third issue and related question:
3) How can I see my custom widget code also?
Thanks for the attention! Hope I was clear.
I also had a similar problem trying to use SuperDev Mode with Vaadin. I'm not quite sure why recompilation fails on occasion, but I suspect it envolves the same issue I had trying to send my Java source maps. The problem I had seemed to be a caching issue due to the fact that the code server creates a persistent cache directory in my /tmp folder. So I deleted every folder it created (they usually have "gwt" in the name somewhere) and relaunched the code server. I suggest also adding the -src <complete-path-to-project> argument in the code server configurations to specify the directory containing GWT source to be prepended to the classpath for compiling and possibly changing the log level to TRACE or DEBUG. Heres an example those arguments:
com.example.AppWidgetSet -src /home/workspace/widgetset/src/main/java
-logLevel TRACE
I should mention that the log levels are quite verbose, but can be quite useful. The log should also show the location of the cache folder.

Categories