Velocity - How to avoid ParseErrorException when using jQuery? - java

I'm trying to add a jQuery post to some JavaScript on a web page. The entire page is built up of several Velocity templates. Everything has been fine until I've tried to add the jQuery post, now I get:
org.apache.velocity.exception.ParseErrorException: Encountered "," at line 282, column 24 of /WEB-INF/velocity/www/comments.vm
Was expecting one of:
"(" ...
<RPAREN> ...
<ESCAPE_DIRECTIVE> ...
~~~snip~~~
Line 282 is $.post(... and column 24 appears to be the first "," character. Initially I had the JSON on this line, but I moved it up (to the var myJSONObject ... line)as I thought the error related to invalid JSON (tabs at the start of the line gave a misleading column number).
var myJSONObject = {"body": "", "action": "postcomment", "submitted": "true", "ajax": "true"};
myJSONObject.body = $("body").val();
$.post("$!{articleurl}", myJSONObject, function(result){
btn.textContent='Comment sent successfully.';
});
Minor Update
I changed the following lines:
var url = "$articleurl";
$.post(url, myJSONObject, function(result){
~~~snip~~~
The parse exception still focuses on the first ",". I'm assuming the issue is that Velocity thinks it should be able to resolve $.post - when in fact, it's jQuery. I've used jQuery in other Velocity VM templates without any problem. Is there a way to get Velocity to ignore certain lines / statements when parsing?
Update 2
I found this link about escaping references in Velocity, but it does not resolve my issue. Adding a "\" before $.post gives me the exact same error, but the column is one extra, because of the character added at the start of the line.

You can wrap your javascript with #[[ ... ]]# which tells Velocity to not parse the enclosed block (new in Velocity 1.7)
#[[
<script>
...
</script>
]]#

Ok, there appears to be two solutions for this:
First, with jQuery we can just avoid using the global alias $ and instead use the jQuery object directly:
jQuery.post(url, myJSONObject, function(result){
~~~snip~~~
In my case, the above works great. But I suspect in other scenarios (non-jQuery) this may not be possible. In which case, we can 'hide' our character within a valid Velocity reference like this:
#set( $D = '$' )
${D}
Source: http://velocity.apache.org/engine/devel/user-guide.html#escapinginvalidvtlreferences
I'd still like to know why the backslash escape didn't work, but the above will at least get me moving again. :)

I think this is a bug in version 1.6.x, because it works fine in 1.7(If it did not, please tell me, I test it many times..), according to the reference, the $ takes effect only when it is followed by a-zA-Z. I want to try do debug what happened really, but the translation code is generated by Java CC tool, it is too hard to recognize the logic...

you must create a js file with your javascript code
and import your js file into your vm code

I couldn't get it to work with any of the other fixes like escaping "$" in velocity unfortunately. I got it working by loading an external js-file with the jQuery instead of writing jQuery directly in velocity. Worked out for me at least, hope it helps someone :)
/björn

Related

Selenium via java - sendKeys doesn't send specific chars to input

I'm having a strange condition where i'm trying to type into input by using sendKeys , the reuslt is that specific chars doesn't seem to be implemented in the input at all.
What i'm trying to do:
webDriver.findElement(By.id("additionalInfo(token_autocompleteSelectInputId)")).sendKeys("(test)");
the result is that input field is now : test) and the missing char is '(' .
If i will try
webDriver.findElement(By.id("additionalInfo(token_autocompleteSelectInputId)")).sendKeys("((((((((((")
the result is that the input is empty.
Anyone ever faced this issue before? it is happening on a very specific input in the app, couldn't find anything related to it in the html code.
Thanks in advance.
Edit: I can manually type ( in the input field.
Maybe it's a special character for selenium, have you tried using escape characters? Something like backslash before it if it allows it.
Edit: I found some issue report on github from last year, not sure if they agreed to not fix it. Executing a script to type "(" seems to be an alternative.
Source: https://github.com/seleniumhq/selenium/issues/674
try declaring the key as a string first
String keyToSend = "(test)";
webDriver.findElement(By.id("additionalInfo(token_autocompleteSelectInputId)")).sendKeys(keyToSend);
In this case you should try using JavascriptExecutor as below :-
WebElement el = webDriver.findElement(By.id("additionalInfo(token_autocompleteSelectInputId)"));
((JavascriptExecutor)webDriver).executeScript("arguments[0].value = arguments[1]", el, "(test)");
Hope it helps..:)

Error when using Esapi validation

I hope someone could help me with some issue.
I'm using OWASP ESAPI 2.1.0 with JavaEE, to help me to validate some entries in a web application. At some point I needed to validate a Windows file path, so I added a new property entry in the 'validation.properties' like this one:
Validator.PathFile=^([a-zA-Z]:)?(\\\\[\\w. -]+)+$
When I try to validate, for example, a string like "C:\TEMP\file.txt" via ESAPI, I get a ValidationException:
ESAPI.validator().getValidInput("PathFile", "C:\\TEMP\\file.txt", "PathFile", 100, false);
Alternatively, I also tried the java.util.regex.Pattern class to test the same regular expression with the same string example and it works OK:
Pattern.matches("^([a-zA-Z]:)?(\\\\[\\w. -]+)+$", "C:\\TEMP\\file.txt")
I must say that I added other regex in 'validation.properties' and worked OK. Why this one is so hard? Could anyone help me out with this one?
This is happening because the call to validator().getValidInput("PathFile", "C:\\TEMP\\file.txt", "PathFile", 100, false); wraps a call to ESAPI.encoder().canonicalize() that is transforming the input to the char sequence (Not literal String!) C:TEMP'0x0C'ile.txt before it passes to the regex engine.
Except for the second "\" getting converted to the char 0x0c this is normally desired behavior. That could be a bug in ESAPI.
What you want, is to make a call to ESAPI.validator().getValidDirectoryPath()

How to inject HTML into {0} of springMessageText in Velocity?

I'm using Apache Velocity in an internationalized Spring MVC website.
I want to use "Redirecting in X seconds" as the phrase (message key) that my translators will translate. The X will obviously be a variable number of seconds, and Javascript will update the page every second to count it down.
I thought I'd do this:
#springMessageText("Redirecting in {0} seconds" ["<span class='seconds'>5</span>"])
But this displays:
Redirecting in <span class='seconds'>5</span> seconds
(without parsing the HTML).
I need to be able to put the HTML tag in there because that is how javascript will know which part of the translated phrase to update.
What am I doing wrong?
UPDATED ANSWER:
I created a custom macro file called custom.vm:
#macro( springMessageHtml $code, $args, $defaultValue)
$springMacroRequestContext.getMessage($code, $args.toArray(), $defaultValue, false)
#end
In my velocity.properties file, I changed this line to reference it:
velocimacro.library=org/springframework/web/servlet/view/velocity/spring.vm,/velocity/custom.vm
And now in my views (like sample.vm), I can call it like:
#springMessageHtml("Redirecting in {0} seconds" ["<span class='seconds'>5</span>"])
OLDER ANSWER:
I found an answer here: http://feima2011.wordpress.com/2011/01/18/misc-notes/
#set($args = ["<span class='seconds'>5</span>"])
$springMacroRequestContext.getMessage("Redirecting in {0} seconds",
$args.toArray(), "", false)
#springMessageText is just a macro that calls $springMacroRequestContext.getMessage() anyway; by calling it directly, I'm able to specify that last parameter (a boolean for whether to escape the HTML).
Now I'm able to have unescaped HTML. Maybe eventually I'll code a new macro called #springMessageHtml, and it will call $springMacroRequestContext.getMessage() with the escapeHtml parameter set to False. Then in my view, I'd only need 1 line of code.

Workaround on Scraping HTML by diving into js source code

I learn about jSoup recently and would like to dive more into it. However, I have met obstacle handling webpages with javascript (I have no knowledge in js, yet :/).
I have read that htmlunit would be the correct tool to perform webbrowser actions, but I figured out that I would need no knowledge in js if I can find out the JSON object obtained in the webpage using the javascript.
For example, this page:
among the source files, one of them is tooltips.js. In this file, variable rgNeededFeeds is generated and called in method LoadHeropediaData(), which is the method to generate the whole URL link for getting the json object.
URL = URL + 'jsfeed/heropediadata?feeds='+strFeeds+'&v=3633666222511362823&l=english';
I could not get my mind on what is actually strFeeds. I have tried various combinations but it doesn't work (it returned an empty array...). Or, my guess is totally off?
What I actually need is the data it displays on top when you click on one of the "items". The info in the "hover" would do too, but it lack the "recepi" info. And I'm presuming that by getting the json object from the full URL above, well, basically all data infos should be in that json.
Anyways, this is only based on what I understand from staring at those source files for hours. Do correct me if I'm wrong. (I'm in Java by the way)
**p/s: I would also like to take this opportunity to express my thanks to Balusc, he has been everywhere when I have doubts on jSoup. :>*
strFeeds is nothing but one of these two strings : itemdata or abilitydata
You can find this in tooltips.js at line 38-45
var rgNeededFeeds = [];
$.each( [ 'item', 'ability' ],
function( i, ttType ){
icons = GetIconCollection( ttType );
if ( icons.length ){
rgNeededFeeds.push( ttType+'data' );
//..............
}
}
)
ttType is the value of an iteration over the array [ 'item', 'ability' ] which concatenated with the string data is pushed into the array rgNeededFeeds
The function LoadHeropediaData is called at the end of the function above with rgNeededFeeds as parameter :
LoadHeropediaData( rgNeededFeeds );
Aside note : If you begin to start scraping websites, learning javascript will be MANDATORY.
NOTE : you're right, the JSON contains all the information needed...

get all values using get paremeters in java

I'm passing the some values url from flex to java example:
URL format:
../mahesh/initUser.do?method=fwdAccDetails&securityId=mUuB3/p/ky5JhZPY5T8Znf01YCcIarIalQiGEXPMMsOkWDX+KtT4fx2gMML+uup8
After I'm tiring to get "securityId" values in java like
request.getParameter("securityId")
But I'm getting following values only
mUuB3/p/ky5JhZPY5T8Znf01YCcIarIalQiGEXPMMsOkWDX KtT4fx2gMML uup8
symbol getting empty space in java side..
Here is my Flex code:
navigateToURL(new URLRequest('../mahesh/initUser.do?method=fwdAccDetails&securityId='+value+'),'_s‌​elf');
I didn't get full values.. any one can help me how I will get correct values in Java..
You should use the encodeURIComponent()-Function to properly encode your securityId.
value = encodeURIComponent(value);
navigateToURL(new URLRequest('../mahesh/initUser.do?method=fwdAccDetails&securityId='+value+'),'_s‌​elf');
That way your String will be correct on the Java side.
If you want to read more about proper escaping, have a look at When are you supposed to use escape instead of encodeURI / encodeURIComponent? (Same arguments apply for Flex and JavaScript).
i just resolve my issue for following code in a javURLDecoder.decode(param1AfterEncoding.replace("+", "%2B"), "UTF-8").replace("%2B", "+")
Now its working fine only.. i dint other special character will work fine.. i will check it later..

Categories

Resources