Java: Apache Velocity Parser Error on Curly Brace - java

I am working with Apache Velocity, and one of my templates is triggering a parser error. The lines that cause the exception are:
$slider.animate({height: configMap.extendedHeight})
.attr('title', configMap.extendedTitle);
And the error is
Oct 28, 2013 11:34:50 AM org.apache.velocity.runtime.log.CommonsLogLogChute log
SEVERE: ResourceManager.getResource() parse exception
org.apache.velocity.exception.ParseErrorException: Encountered ")\n .attr(\'title\', congifMap.extendedTitle);\n return true;\n } else if(sliderHeight === configMap.extendedHeight) {\n " at vml/Slider.vml[line 45, column 71]
Was expecting one of:
"," ...
")" ...
<WHITESPACE> ...
at org.apache.velocity.Template.process(Template.java:151)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:437)
at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514)
at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373)
...
I am new to VTL syntax, and don't see what the error could be caused by in the VTL reference manual
http://velocity.apache.org/engine/devel/vtl-reference-guide.html
Does anyone know what the cause of this is and how to fix it? Thank you in advance!

So apparently as of Velocity 1.7 you can exclude block from rendering with the #[[ ]]# directive. in this case one solution is
#[[
<script type="text/javascript">
var Slider = (function () {
var configMap = {
extendedHeight: 434,
extendedTitle: 'Click to retract',
retractedHeight: 16,
retractedTitle: 'Click to expand',
templateHtml: '<div class="slider"></div>'
}, $slider, toggleSlider, onClickSlider, initModule;
toggleSlider = function () {
var sliderHeight = $slider.height();
if(sliderHeight === configMap.retractedHeight) {
$slider.animate({height: configMap.extendedHeight})
.attr('title', configMap.extendedTitle);
return true;
} else if(sliderHeight === configMap.extendedHeight) {
$slider.animate({height: configMap.retractedHeight})
.attr('title', configMap.retractedTitle);
return true;
}
return false;
};
onClickSlider = function (event) {
toggleSlider();
return false;
};
initModule = function ($container) {
$container.html(configMap.templateHtml);
$slider = $container.find('.slider');
$slider.attr('title', configMap.retractedTitle)
.click(onClickSlider);
return true;
};
return {initModule: initModule};
})(jQuery);
jQuery(document).ready(
function () {
Slider.initModule(jQuery('#slider'));
}
);
</script>
]]#
However this still does not answer the first part of the question which is what the first error was actually about.

If $slider is a javascript variable, it will get into conflict with Velocity variables which also start with $: that may explain the parsing error exception.
To say it in another way: Velocity parses this template trying to get the $slider value from the engine.

Related

calling rest API(locally running) from nodejs failed

We created a rest API on python and it is locally running. And the 'http://127.0.0.1:5002/business' API is showing contents {"business name": "something"} if I open it on google chrome. However, when we call this API in nodejs, it always gives me the error. But if I use another API(exactly same code but different api in nodejs), it is working.
async function get_recommend_initial(){
//https://ViolaS.api.stdlib.com/InitialRecommendation#dev/
// // agent.add('providing recommendations...');
const options = {
method: 'GET'
,uri: 'http://127.0.0.1:5002/business'
// ,uri:'https://ViolaS.api.stdlib.com/InitialRecommendation#dev/'
// ,json: true
};
// return request(options).then(response => {
// console.log(response)
// return (response)
// }).catch(function (err) {
// console.log('No recommend data');
// console.log(err);
// });
return requestAPI(options).then(function(data)
{
let initial_recommendation = JSON.parse(data);
console.log(initial_recommendation);
//return initial_recommendation.information[0].name;
}).catch(function (err) {
console.log('No recommend data');
console.log(err);
});
}
1
The API that is created by python file which is running locally. You can see the API code figure by moving your mouth above 1. Thanks!!!
The python code is as follows:
app = Flask(__name__)
#Add resources to be much cleaner
api = Api(app)
features = {}
class Business(Resource):
def get(self):
return {'business name': 'something'} # Fetches first column that is Employee ID
def post(self):
some_json = request.get_json()
print(some_json)
countNumber = features.get('count',0) + 1
features['count'] = countNumber
return {'You sent': some_json,
'Count:':countNumber}, 201
def put(self):
some_json = request.get_json()
print(some_json)
#record the count number
countNumber = features.get('count',0) + 1
features['count'] = countNumber
features['ok'] = 'yes'
return {'You sent': some_json,
'Count:':countNumber,
'Ok:': features['ok']}, 201
api.add_resource(Business, '/business') # Route_1
if __name__ == '__main__':
app.run(port='5002')
The error is as following:
dialogflowFirebaseFulfillment
Error: Unknown response type: "undefined" at WebhookClient.addResponse_ (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:277:13) at WebhookClient.add (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:245:12) at Sys_Recommend (/srv/index.js:31:11) at <anonymous>
And the log is:
No recommend data

Unable to call java methods from asp pages:

i have the following problem with this simple asp page:
<%
Dim javaTestObj set javaTestObj = GetObject("java:test")
if javaTestObj.mstrLogin("pepe", "pepe") then
Response.write("It Works!")
end if
%>
the Java class is the following:
public class test{
String pepe;
public test()
{
pepe="pepepepe";
}
public boolean mstrLogin(String usname, String uspass)
{
if((usname+uspass)==pepe)
return true;
else
return false;
}}
I have the compiled .class in every directory i've read it should be (C:\ClassPath\; C:\windows\java\trustedlib\ and in the same directory as the asp page) but i get no results =(
Any ideas of how it would work? I'm using IIS and the browser gives me this error:
Error type:
Microsoft VBScript compilation error (0x800A0401)
expected instruction end:
/login/pruebajava.asp, line 2, column 16
Dim javaTestObj set javaTestObj = GetObject
("java:test")
---------------^
It might be that you just accidently omitted the colon (:) character, but the first line should read
Dim javaTestObj : set javaTestObj = GetObject("java:test")
because in classic ASP you are not allowed to declare and set a variable in the same statement
Dim myVariable = "hello World" '//Error! Not allowed.
Dim myOtherVar
myOtherVar = "hello World" '//OK
Dim myVar : myVar = "Hello World" '//OK

Play 1.2.2 - are tags inside tags no longer allowed?

I am developing an application in play and in my selenium tests I use several tags for repetitive tasks. Two tags are:
app/views/tags/loginAs.html
*{ Tag for running selenium tests when being logged in }*
#{if !_keepData}
#{braindumpFixture delete:'all', load:'users.yml' /}
#{/if}
#{selenium}
... some selenium code to log into the application
#{/selenium}
app/views/tags/braindumpFixture.html
%{
if(_delete == 'all') {
play.test.Fixtures.deleteAll()
} else if(_delete) {
play.test.Fixtures.delete(_delete)
}
}%
%{
if(_load) {
play.test.Fixtures.load(_load)
}
// finally make sure the index is correctly updated.
new application.jobs.CompleteReindexJob().doJob();
}%
These work without a problem in Play 1.1. After switching to play 1.2.2, I get the following exception when running a selenium test that uses loginAs:
test/selenium/AddCard.test.html
*{ Tests adding a simple card }*
#{loginAs login:'foobar#foobar.com', password:'foobar' /}
#{selenium}
open('#{Application.index()}')
... more selenium stuff here
#{/selenium}
The exception being:
play.exceptions.TemplateExecutionException: Cannot get property 'data' on null object
at play.templates.BaseTemplate.throwException(BaseTemplate.java:84)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:252)
at play.templates.GroovyTemplate$ExecutableTemplate.invokeTag(GroovyTemplate.java:374)
at /test/selenium/AddCard.test.html.(line:3)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:229)
at play.templates.Template.render(Template.java:26)
at play.templates.GroovyTemplate.render(GroovyTemplate.java:184)
at controllers.TestRunner.run(TestRunner.java:107)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:543)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:499)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:475)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:470)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:158)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.NullPointerException: Cannot get property 'data' on null object
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:229)
... 12 more
When I remove the #{if !_keepData} around the call to braindumpFixture I get an EmptyStackException:
play.exceptions.TemplateExecutionException
at play.templates.BaseTemplate.throwException(BaseTemplate.java:84)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:252)
at play.templates.Template.render(Template.java:26)
at play.templates.GroovyTemplate.render(GroovyTemplate.java:184)
at controllers.TestRunner.run(TestRunner.java:107)
at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:543)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:499)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:475)
at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:470)
at play.mvc.ActionInvoker.invoke(ActionInvoker.java:158)
at Invocation.HTTP Request(Play!)
Caused by: java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:85)
at java.util.Stack.pop(Stack.java:67)
at play.templates.TagContext.exitTag(TagContext.java:31)
at play.templates.GroovyTemplate$ExecutableTemplate.invokeTag(GroovyTemplate.java:380)
at /test/selenium/AddCard.test.html.(line:3)
at play.templates.GroovyTemplate.internalRender(GroovyTemplate.java:229)
... 9 more
I wonder if something fundamentally changed with tags in Play 1.2 and I just overlooked it in the documentation or if this might be a bug. Any ideas on solving this riddle are welcome.
The issue is the #{fixture} tag. It will kill the internal stack when loading an yml file. See https://play.lighthouseapp.com/projects/57987-play-framework/tickets/1026-using-tags-inside-tags-is-broken-since-play-121#ticket-1026-3.
As a workaround you can create a modified version of the fixture tag:
%{
if(_delete == 'all') {
play.test.Fixtures.deleteAll()
} else if(_delete) {
play.test.Fixtures.delete(_delete)
}
}%
%{
if(_load) {
// Workaround (save the stack)
stack = play.templates.TagContext.currentStack.get();
play.test.Fixtures.load(_load)
// Workaround (restore the stack)
play.templates.TagContext.currentStack.set(stack);
}
}%
%{
if(_arg && _arg instanceof String) {
try {
play.Play.classloader.loadClass(_arg).newInstance()
} catch(Exception e) {
throw new play.exceptions.TagInternalException('Cannot apply ' + _arg + ' fixture because of ' + e.getClass().getName() + ', ' + e.getMessage())
}
}
%}
I am not aware that anything should have changed to stop this from working, so would expect this is a bug.

Try/catch in JSP fails

A try/catch statement in my Java code (embedded in JSP) fails with the following error:
An error occurred at line: 26 in the jsp file: /template/tampabay/includes/omniture-footer.jsp
Syntax error on token "}", delete this token
I am unable to determine why the following code produces that error:
<%!
/*
* Map the DTI categories to the appropriate SiteCatalyst category
* structure.
*/
ArrayList<HashMap> mapDTIToSiteCatalystCategories( ArrayList<HashMap> dti_categories ) {
ArrayList<HashMap> site_catalyst_categories = new ArrayList<HashMap>();
ArrayList<Integer> dti_category_ids = new ArrayList<Integer>();
for ( int i = 0; i < 4; i++ ) {
try {
dti_category_ids.add( Integer.parseInt( (String)dti_categories.get( i ).get( "id" ) ) );
}
catch ( NumberFormatException e ) {
dti_category_ids.add( -1 );
}
}
// - Snip -
}
The error corresponds to the twelfth line above ( the closing brace of the try statement ). However, the code looks syntactically correct to me. Aside from breach of protocol by embedding a scriptlet in JSP, can you help point out the error?
I have tried using variations of this code (removing the for loop and declaring separate variables) but the error persists whenever I try to use the try/catch statement.
EDIT:
I uploaded the complete code listing here.
EDIT 2:
I also receive the following error:
An error occurred at line: 44 in the jsp file: /template/tampabay/includes/omniture-footer.jsp
Syntax error, insert "}" to complete Block
This error corresponds to the fourth line below:
"", "Baseball",
"", ""
);
break;
case 120: // Baseball: Minors
site_catalyst_categories = addElements(
dti_category_ids.get( 0 ), "Sports",
I did not include it before because I assumed it was caused by the earlier error. However, in light of the comments, it may be relevant.
According to my IDE and my visual inspection, all of the braces are properly paired. However, the compiler disagrees.
It looks like, on line 131/132, there's a missing close curly for the try statement.
case 131:
try {
switch ( dti_category_ids.get( 2 ) ) {
case 252: // Colleges: Bulls ..snip..
case 253: // Colleges: Bulls ..snip..
case 254: // Colleges: Bulls ..snip..
default: // Log all others to the "College" section
}
break;
// HERE ... THERE'S NO } TO CLOSE THE try {
catch ( NumberFormatException e ) {
// Log all others to the "College" section
site_catalyst_categories = addElements(
dti_category_ids.get( 0 ), "Sports",
"", "College",
"", "",
"", ""
);
}

DJ Native Swing javascript command problems

Using DJ Native Swing it is possible to show a web page within a java application. When you do this it is also possible to communicate from the browser to the java runtime environment using the "command" protocol. The documentation has a code snippet which demonstrates it's usage:
function sendCommand( command ){
var s = 'command://' + encodeURIComponent( command );
for( var i = 1; i < arguments.length; s+= '&' + encodeURIComponent( arguments[i++] ) );
window.location = s;
}
As it looks here it seems to be a regular GET request to an url using the command protocol instead of http. Although when I create and image, script tag or just and ajax get request there is no response and the breakpoint in the java runtime isn't triggered.
I don't want to set the window.location because I don't want to navigate away from the page I am currently at. Using the link to navigate to a command url does work though but it also navigates away from the current page. The page uses OpenLayers and dojo. (I have also tried dojo.io.script)
After some work I have found a neat way to communicate with the java runtime which doesn't trigger a refresh of the page every time there is communication. It is inspired on the way JSONP works to get around the cross domain restriction in most browsers these days. Because an iFrame will also trigger a command:// url it possible to do a JSONP like action using this technique. The code on the client side (browser):
dojo.provide( "nmpo.io.java" );
dojo.require( "dojo.io.script" );
nmpo.io.java = dojo.delegate( dojo.io.script, {
attach: function(/*String*/id, /*String*/url, /*Document?*/frameDocument){
// summary:
// creates a new tag pointing to the specified URL and
// adds it to the document.
// description:
// Attaches the script element to the DOM. Use this method if you
// just want to attach a script to the DOM and do not care when or
// if it loads.
var frame = dojo.create( "iframe", {
id: id,
frameborder: 0,
framespacing: 0
}, dojo.body( ) );
dojo.style( frame, { display: "none" } );
dojo.attr( frame, { src: url } );
return frame;
},
_makeScriptDeferred: function(/*Object*/args){
//summary:
// sets up a Deferred object for an IO request.
var dfd = dojo._ioSetArgs(args, this._deferredCancel, this._deferredOk, this._deferredError);
var ioArgs = dfd.ioArgs;
ioArgs.id = dojo._scopeName + "IoScript" + (this._counter++);
ioArgs.canDelete = false;
//Special setup for jsonp case
ioArgs.jsonp = args.callbackParamName || args.jsonp;
if(ioArgs.jsonp){
//Add the jsonp parameter.
ioArgs.query = ioArgs.query || "";
if(ioArgs.query.length > 0){
ioArgs.query += "&";
}
ioArgs.query += ioArgs.jsonp
+ "="
+ (args.frameDoc ? "parent." : "")
+ "nmpo.io.java.jsonp_" + ioArgs.id + "._jsonpCallback";
ioArgs.frameDoc = args.frameDoc;
//Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
return dfd; // dojo.Deferred
}
});
When a request is sent to the java runtime a callback argument will be supplied and a webBrowser.executeJavascript( callbackName + "(" + json + ");" ); action can be executed to trigger the callback in the browser.
Usage example client:
dojo.require( "nmpo.io.java" );
nmpo.io.java.get({
// For some reason the first paramater (the one after the '?') is never in the
// paramater array in the java runtime. As a work around we stick in a dummy.
url: "command://sum?_",
callbackParamName: "callback",
content: {
numbers: [ 1, 2, 3, 4, 5 ].join( "," )
},
load: function( result ){
console.log( "A result was returned, the sum was [ " + result.result + " ]" );
}
});
Usage example java:
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
#Override
public void commandReceived(WebBrowserCommandEvent e) {
// Check if you have the right command here, left out for the example
// Parse the paramaters into a Hashtable or something, also left out for the example
int sum = 0;
for( String number : arguments.get( "numbers" ).split( "," ) ){
sum += Integer.parseInt( number );
}
// Execute the javascript callback like would happen with a regular JSONP call.
webBrowser.executeJavascript( arguments.get( "callback" ) + "({ result: " + sum + " });" );
}
});
Also with IE in the frame I can highly recommend using firebug lite, the dev tools for IE are not available.

Categories