ActionListener Expression value for RichButton in ADF - action

We have a business need to collect specific bindings in every JSF page. and we do that inside overridden ViewHandlerWrapper class
I use the below code inside renderView method to get the whole expression value property for every RichInputText and it's work fine for me
ValueExpression valExp = Inputcomponent.getValueExpression("value");
String ExpressionString = valExp.getExpressionString();
output was: #{binding.EmployeeId.inputValue}
When I do the same against RichButtin I got null value as following:
ValueExpression valExp = Btncomponent.getValueExpression("actionlistener");
String ExpressionString = valExp.getExpressionString();
What is the wrong in my last peace of code?

Obtaining a ValueExpression form a RichInputText works because, as the name suggests, it evaluates to a value, which may or may not be an EL expression, let alone a method.
On the other hand, a RichButton does not really have to evaluate to something; rather, it aims to invoke behavior (i.e. a method), from which you would want a MethodExpression - though in this case, the closest we get to it is a MethodBinding.
Luckily, UIXCommand, a superclass of RichButton, provides two methods from which you can obtain your action listeners:
public final MethodBinding getActionListener()
From the MethodBinding returned, you can invoke getExpressionString() so you can get what you wanted - such as some actionListener EL string like #{binding.bean.actionListenerMethod}.
public final ActionListener[] getActionListeners()
Might be worth mentioning, though there is not much merit for this in your use case. It simply returns the listeners on which you can manually process the events.

Related

Calling methods dynamically (Crystal-lang)

I understand that this may be a duplicate of Any equivalent of Ruby's public_send method?. I'd like to explain what I am doing, and perhaps someone could advice.
I've been porting a ruby app over the last few days to learn Crystal. I've had to cut out a lot of functionality due to lack of send but today I've hit a main artery in my program.
I have a Hash which contains keystroke as key, and method as value. Based on what key is struck, the appropriate method is called. This obviously uses the send to implement the same.
From the linked question, I understand that Crystal is compiled so dynamic method calls are not permitted. However, if you look at the Vim editor, a user can map keys to methods, too. And vi(m) is written in C.
I am wondering if I missed something.
I know I could probably hardcode a switch statement with each key and call the appropriate method, but that still does not allow the user to assign a key to a method. Is there any alternative to this very large switch-case method ?
(I am guessing that rather than check the key in the when part, I would check the binding and call the method.
binding = #bindings[key]
case binding
when :up
up
when :down
down
when .....
else
end
Any better solution ?
I'm not sure that this way most simple and convenient (perhaps more experienced developers will correct me below) but i would use the Proc:
def method1
puts "i'm method1"
end
def method2
puts "i'm method2"
end
def method3
puts "i'm method3"
end
hash = {
"ctrl": -> { method1 },
"shift": -> { method2 },
"alt": -> { method3 }
}
binding = ["ctrl", "shift", "alt"].sample
hash[binding].call #=> i'm method2
See working example

c++ best way to realise global switches/flags to control program behaviour without tying the classes to a common point

Let me elaborate on the title:
I want to implement a system that would allow me to enable/disable/modify the general behavior of my program. Here are some examples:
I could switch off and on logging
I could change if my graphing program should use floating or pixel coordinates
I could change if my calculations should be based upon some method or some other method
I could enable/disable certain aspects like maybe a extension api
I could enable/disable some basic integrated profiler (if I had one)
These are some made-up examples.
Now I want to know what the most common solution for this sort of thing is.
I could imagine this working with some sort of singelton class that gets instanced globally or in some other globally available object. Another thing that would be possible would be just constexpr or other variables floating around in a namespace, again globally.
However doing something like that, globally, feels like bad practise.
second part of the question
This might sound like I cant decide what I want, but I want a way to modify all these switches/flags or whatever they are actually called in a single location, without tying any of my classes to it. I don't know if this is possible however.
Why don't I want to do that? Well I like to make my classes somewhat reusable and I don't like tying classes together, unless its required by the DRY principle and or inheritance. I basically couldn't get rid of the flags without modifying the possible hundreds of classes that used them.
What I have tried in the past
Having it all as compiler defines. This worked reasonably well, however I didnt like that I couldnt make it so if the flag file was gone there were some sort of default settings that would make the classes themselves still operational and changeable (through these default values)
Having it as a class and instancing it globally (system class). Worked ok, however I didnt like instancing anything globally. Also same problem as above
Instancing the system class locally and passing it to the classes on construction. This was kinda cool, since I could make multiple instruction sets. However at the same time that kinda ruined the point since it would lead to things that needed to have one flag set the same to have them set differently and therefore failing to properly work together. Also passing it on every construction was a pain.
A static class. This one worked ok for the longest time, however there is still the problem when there are missing dependencies.
Summary
Basically I am looking for a way to have a single "place" where I can mess with some values (bools, floats etc.) and that will change the behaviour of all classes using them for whatever, where said values either overwrite default values or get replaced by default values if said "place" isnt defined.
If a Singleton class does not work for you , maybe using a DI container may fit in your third approach? It may help with the construction and make the code more testable.
There are some DI frameworks for c++, like https://github.com/google/fruit/wiki or https://github.com/boost-experimental/di which you can use.
If you decide to use switch/flags, pay attention for "cyclometric complexity".
If you do not change the skeleton of your algorithm but only his behaviour according to the objets in parameter, have a look at "template design pattern". This method allow you to define a generic algorithm and specify particular step for a particular situation.
Here's an approach I found useful; I don't know if it's what you're looking for, but maybe it will give you some ideas.
First, I created a BehaviorFlags.h file that declares the following function:
// Returns true iff the given feature/behavior flag was specified for us to use
bool IsBehaviorFlagEnabled(const char * flagName);
The idea being that any code in any of your classes could call this function to find out if a particular behavior should be enabled or not. For example, you might put this code at the top of your ExtensionsAPI.cpp file:
#include "BehaviorFlags.h"
static const enableExtensionAPI = IsBehaviorFlagEnabled("enable_extensions_api");
[...]
void DoTheExtensionsAPIStuff()
{
if (enableExtensionsAPI == false) return;
[... otherwise do the extensions API stuff ...]
}
Note that the IsBehaviorFlagEnabled() call is only executed once at program startup, for best run-time efficiency; but you also have the option of calling IsBehaviorFlagEnabled() on every call to DoTheExtensionsAPIStuff(), if run-time efficiency is less important that being able to change your program's behavior without having to restart your program.
As far as how the IsBehaviorFlagEnabled() function itself is implemented, it looks something like this (simplified version for demonstration purposes):
bool IsBehaviorFlagEnabled(const char * fileName)
{
// Note: a real implementation would find the user's home directory
// using the proper API and not just rely on ~ to expand to the home-dir path
std::string filePath = "~/MyProgram_Settings/";
filePath += fileName;
FILE * fpIn = fopen(filePath.c_str(), "r"); // i.e. does the file exist?
bool ret = (fpIn != NULL);
fclose(fpIn);
return ret;
}
The idea being that if you want to change your program's behavior, you can do so by creating a file (or folder) in the ~/MyProgram_Settings directory with the appropriate name. E.g. if you want to enable your Extensions API, you could just do a
touch ~/MyProgram_Settings/enable_extensions_api
... and then re-start your program, and now IsBehaviorFlagEnabled("enable_extensions_api") returns true and so your Extensions API is enabled.
The benefits I see of doing it this way (as opposed to parsing a .ini file at startup or something like that) are:
There's no need to modify any "central header file" or "registry file" every time you add a new behavior-flag.
You don't have to put a ParseINIFile() function at the top of main() in order for your flags-functionality to work correctly.
You don't have to use a text editor or memorize a .ini syntax to change the program's behavior
In a pinch (e.g. no shell access) you can create/remove settings simply using the "New Folder" and "Delete" functionality of the desktop's window manager.
The settings are persistent across runs of the program (i.e. no need to specify the same command line arguments every time)
The settings are persistent across reboots of the computer
The flags can be easily modified by a script (via e.g. touch ~/MyProgram_Settings/blah or rm -f ~/MyProgram_Settings/blah) -- much easier than getting a shell script to correctly modify a .ini file
If you have code in multiple different .cpp files that needs to be controlled by the same flag-file, you can just call IsBehaviorFlagEnabled("that_file") from each of them; no need to have every call site refer to the same global boolean variable if you don't want them to.
Extra credit: If you're using a bug-tracker and therefore have bug/feature ticket numbers assigned to various issues, you can creep the elegance a little bit further by also adding a class like this one:
/** This class encapsulates a feature that can be selectively disabled/enabled by putting an
* "enable_behavior_xxxx" or "disable_behavior_xxxx" file into the ~/MyProgram_Settings folder.
*/
class ConditionalBehavior
{
public:
/** Constructor.
* #param bugNumber Bug-Tracker ID number associated with this bug/feature.
* #param defaultState If true, this beheavior will be enabled by default (i.e. if no corresponding
* file exists in ~/MyProgram_Settings). If false, it will be disabled by default.
* #param switchAtVersion If specified, this feature's default-enabled state will be inverted if
* GetMyProgramVersion() returns any version number greater than this.
*/
ConditionalBehavior(int bugNumber, bool defaultState, int switchAtVersion = -1)
{
if ((switchAtVersion >= 0)&&(GetMyProgramVersion() >= switchAtVersion)) _enabled = !_enabled;
std::string fn = defaultState ? "disable" : "enable";
fn += "_behavior_";
fn += to_string(bugNumber);
if ((IsBehaviorFlagEnabled(fn))
||(IsBehaviorFlagEnabled("enable_everything")))
{
_enabled = !_enabled;
printf("Note: %s Behavior #%i\n", _enabled?"Enabling":"Disabling", bugNumber);
}
}
/** Returns true iff this feature should be enabled. */
bool IsEnabled() const {return _enabled;}
private:
bool _enabled;
};
Then, in your ExtensionsAPI.cpp file, you might have something like this:
// Extensions API feature is tracker #4321; disabled by default for now
// but you can try it out via "touch ~/MyProgram_Settings/enable_feature_4321"
static const ConditionalBehavior _feature4321(4321, false);
// Also tracker #4222 is now enabled-by-default, but you can disable
// it manually via "touch ~/MyProgram_Settings/disable_feature_4222"
static const ConditionalBehavior _feature4222(4222, true);
[...]
void DoTheExtensionsAPIStuff()
{
if (_feature4321.IsEnabled() == false) return;
[... otherwise do the extensions API stuff ...]
}
... or if you know that you are planning to make your Extensions API enabled-by-default starting with version 4500 of your program, you can set it so that Extensions API will be enabled-by-default only if GetMyProgramVersion() returns 4500 or greater:
static ConditionalBehavior _feature4321(4321, false, 4500);
[...]
... also, if you wanted to get more elaborate, the API could be extended so that IsBehaviorFlagEnabled() can optionally return a string to the caller containing the contents of the file it found (if any), so that you could do shell commands like:
echo "opengl" > ~/MyProgram_Settings/graphics_renderer
... to tell your program to use OpenGL for its 3D graphics, or etc:
// In Renderer.cpp
std::string rendererType;
if (IsDebugFlagEnabled("graphics_renderer", &rendererType))
{
printf("The user wants me to use [%s] for rendering 3D graphics!\n", rendererType.c_str());
}
else printf("The user didn't specify what renderer to use.\n");

ColdFusion function variable name and CfBuilder

I need to call a function of an object and pass it a variable. Because I need to make multiple call to function of this object I've tried to make one only handler that invoke the specific function by the form value I pass it. The code works, but CFBuilder show me that there is an error (missing semicolon on the last row). I'm on Railo.
local.myReport = seoUtility.init();
local.func = form.action;
local.report = local.myReport[local.func](form.user);
So the question is: this code is correct? I could simply ignore the cfbuilder error icon?
If you don't want CFBuilder to nag you about the syntax, you can change to this:
local.myReport = seoUtility.init();
local.func = local.myReport[form.action];
local.myReport.func = local.func;
local.report = local.myReport.func(form.user);
This sets local.func to the instance of seoUtility as a reference to the actual function you want to call, preserving its relationship to the parent object. This way the offending []() syntax isn't needed.
However, this only works if seoUtility.init() is returning a fresh instance every time, as opposed to a singleton shared by the application, in which case there would be a race condition on all calls to local.myReport.func().

What is valPtr in ctor of wxTextValidator good for?

I'm using a simple numeric text validator wxTextValidator along with a wxTextControl. I wonder what the 2nd parameter is good for:
wxTextValidator(long style = wxFILTER_NONE, wxString* valPtr = NULL)
I simply passed the reference to a member variable:
myTextControl_->SetValidator( wxTextValidator(wxFILTER_NUMERIC, &myValue_) );
I'm using wxWidgets 2.8.12, from the documentation I figured that the myValue_ variable would receive the validated content of the text control, but this does not happen in my application.
Am I doing something wrong or does the valPtr parameter not receive the content of the text control?
The myvalue_ variable should receive the value entered if you call wxValidator::Validate or wxValidator::TransferFromWindow. This happens automatically if you close the dialog with the default OnOK() handler. Otherwise you have to do it yourself.
Ravenspoint has already answered the initial question but I'd just like to add that wxValidator can be used either for validating or for data transfer -- or for both at once. In fact, some validators, such as wxGenericValidator are only used for data transfer (it doesn't make much sense to validate a check box or a radio button!). So the name of this class is somewhat misleading as it describes at most half, and probably less than that, of its uses.

Java El and persistent XSS

First of all this is just a POC that seems to be working fine so far, basically I would like to know what you think of this kind of solution.
The problem:
I have this app with lot of EL code and now I'm supposed to prevent XSS errors my current solution so far (does not mean its the only thing I'm going to fix though) only involves preventing XSS in an EL context.
code below is in a jsp page:
This is your car color ${car.color}
car object is set as follows:
ModelAndView mv = new ModelAndView("page3");
String xss = "<script>window.alert('XSS!!');</script>";
Car c = new Car(xss);
mv.addObject("car", c);
return mv;
this way an alert message should popup, nothing new here...
my proposal (which is working ) is as follows
This is your car color${car.color.preventXSS}
this means like "adding" a preventXSS property to every String (I'm not modifying String class), I'm achieving this through a custom EL Resolver which is basically as follows
try {
value = context.getELResolver().getValue(context, base, property);
} catch (PropertyNotFoundException e) {
if ((base instanceof String) && property.equals(PREVENT_XSS)) {
context.setPropertyResolved(true);
value = ESAPI.encoder().encodeForHTML(base.toString());
}
}
where 'base' is in this case has the value <script>window.alert('XSS!!');<;/script>
and 'PREVENT_XSS' is the constant for 'preventXSS' which is the last property in our EL expression.
BTW I'm using OWASP esapi encoder for dealing with XSS, if needed this can be improved by adding other different encodings like encodeForHTMLAttribute and many other that OWASP's esapi supports.
note1: I know I can use an EL function to achieve the same but I wanted to just add 'property' preventXSS without having to include a jsp taglib directive in every page.
note2: I also know about the c:out jstl tag.
Yeah, the solution that you are proposing works, however one issue that I see is that the additional property can be confusing at maintenance time, due to the fact that is not following the EL standards. If you are using Spring MVC, you can take a look of the following approaches to prevent XSS:
Referece 1
Referece 2
Referece 3