Try/catch in JSP fails - java

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",
"", "",
"", ""
);
}

Related

Why does getInterpreter().adaptivePredict in generated parser return incorrect value?

I am creating custom language (EO language) plugin for IntelliJ. I use antlr4 adapter and I've already generated parser and lexer. I am working on syntax highlighting.
ANTLR4 plugin allows building tokens tree for EO code. I used this option and pasted simple EO program, the tree was built successfully. Nevertheless when I paste this code in IDEA I see an error.
After doing a research I found that problem appears in getInterpreter().adaptivePredict()
In my grammar there are 2 possible code variants (case 1 and case 2 in code below) but getInterpreter().adaptivePredict() returns 3.
Why it works like this?
May be my grammar is not correct but it works in ANTLR tree viewer (I checked several times and added picture in this post)
EO program
+alias org.eolang.io.stdout
+alias org.eolang.txt.sprintf
[args...] > main # This line is an abstraction. Highlighting error (">" is red, expecting '' or EOL)
[y] > leap
or. > #
and.
eq. (mod. y 4) 0
not. (eq. (mod. y 100) 0)
eq. (mod. y 400) 0
stdout > #
sprintf
"%d is %sa leap year!"
(args.get 0).as-int > year!
if. (leap year:y) "" "not "
It is how tree draws "abstraction" line in IDEA. It is correct.
Here is the code from my parser class.
public final AbstractionContext abstraction() throws RecognitionException {
AbstractionContext _localctx = new AbstractionContext(_ctx, getState());
enterRule(_localctx, 10, RULE_abstraction);
int _la;
try {
enterOuterAlt(_localctx, 1);
{
setState(99);
attributes();
setState(107);
_errHandler.sync(this);
/* ? */ System.out.println(getInterpreter().adaptivePredict(_input,14,_ctx)); // prints 3
switch ( getInterpreter().adaptivePredict(_input,14,_ctx) ) {
case 1:
{
{
setState(100);
suffix();
setState(104);
_errHandler.sync(this);
switch ( getInterpreter().adaptivePredict(_input,13,_ctx) ) {
case 1:
{
setState(101);
match(SPACE);
setState(102);
match(SLASH);
setState(103);
_la = _input.LA(1);
if ( !(_la==QUESTION || _la==NAME) ) {
_errHandler.recoverInline(this);
}
else {
if ( _input.LA(1)==Token.EOF ) matchedEOF = true;
_errHandler.reportMatch(this);
consume();
}
}
break;
}
}
}
break;
case 2:
{
setState(106);
htail();
}
break;
}
}
}
catch (RecognitionException re) {
_localctx.exception = re;
_errHandler.reportError(this, re);
_errHandler.recover(this, re);
}
finally {
exitRule();
}
return _localctx;
}
Here is part from EO.g4
abstraction
:
attributes
(
(suffix (SPACE SLASH (NAME | QUESTION))?)
| htail
)?
;
github link of project: https://github.com/yasamprom/EOplugin_antlrbased/blob/main/src/main/java/org/antlr/jetbrains/eo/parser/EOParser.java

Java to Python with Java2Python

I am using Java2Python package to translate a Java project to Python, and I've got an error.
[root#localhost Desktop]# j2py ConfigurationManager.java ConfigurationManager.py
File "/usr/bin/j2py", line 113
except (IOError, ), exc:
^
SyntaxError: invalid syntax
File /usr/bin/j2py, line 113
try:
if filein != '-':
source = open(filein).read()
else:
source = sys.stdin.read()
except (IOError, ), exc:
code, msg = exc.args[0:2]
print 'IOError: %s.' % (msg, )
return code
If there is any information needed, please tell me.
update
File "/usr/bin/j2py", line 115
print 'IOError: %s.' % (msg, )
^
SyntaxError: invalid syntax
Try this :
except (IOError) as exc:
for arg in exc.args:
print(str(arg))
code = exc.args[0]
return code
Here I assume that you want to return 1st value in exc.args

fi.foyt.foursquare.api.FoursquareApiException: org.json.JSONException: JSONObject["icon"] not a string

I am taking the foursquare sample java code and the same sample values from git and running in my local machine, but getting the following exception.
Here is my code:
String ll = args.length > 0 ? args[0] : "44.3,37.2";
try {
FourSquareSampleMain fourSquareSample = new FourSquareSampleMain();
fourSquareSample.searchVenues(ll);
} catch (FoursquareApiException e) {
// TODO: Error handling
e.printStackTrace();
}
}
public void searchVenues(String ll) throws FoursquareApiException {
// First we need a initialize FoursquareApi.
FoursquareApi foursquareApi = new FoursquareApi("CLIENT_ID",
"CLIENT_SECRET", null);
// After client has been initialized we can make queries.
Result<VenuesSearchResult> result = foursquareApi.venuesSearch(ll, null, null, null, null, null, null, null,
null, null, null, null, null);
if (result.getMeta().getCode() == 200) {
CompactVenue[] venueList = result.getResult().getVenues();
System.out.println("Compact Venue List size : " + venueList.length);
// if query was ok we can finally we do something with the data
for (CompactVenue venue : venueList) {
// TODO: Do something we the data
System.out.println("Venue Name : " + venue.getName());
}
System.out.println("End of IF Loop: ");
} else {
// TODO: Proper error handling
System.out.println("Error occured: ");
System.out.println(" code: " + result.getMeta().getCode());
System.out.println(" type: " + result.getMeta().getErrorType());
System.out.println(" detail: " + result.getMeta().getErrorDetail());
}
}
The size of the venueList is always "0", but when I debugged it , it throws the below exception:
"org.eclipse.debug.core.DebugException: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred while retrieving component type of array."
But strange when I changed the latitude and longitude value,
String ll = "-33.883056 , 151.216667";// latlong surry hills sydney
I get the below exception:
fi.foyt.foursquare.api.FoursquareApiException: org.json.JSONException: JSONObject["icon"] not a string.
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:143)
at fi.foyt.foursquare.api.JSONFieldParser.parseValue(JSONFieldParser.java:194)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:141)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntities(JSONFieldParser.java:57)
at fi.foyt.foursquare.api.FoursquareApi.venuesSearch(FoursquareApi.java:1017)
at FourSquareSampleMain.searchVenues(FourSquareSampleMain.java:57)
at FourSquareSampleMain.main(FourSquareSampleMain.java:43)
Caused by: org.json.JSONException: JSONObject["icon"] not a string.
at org.json.JSONObject.getString(JSONObject.java:658)
at fi.foyt.foursquare.api.JSONFieldParser.parseValue(JSONFieldParser.java:202)
at fi.foyt.foursquare.api.JSONFieldParser.parseEntity(JSONFieldParser.java:141)
What am I missing here? please suggest.
I found a workaround for that. It's a patch, but it works. Details:
Info was taken from this post where same issue was identified and fixed
Take a look that diff that resolve the issue: https://github.com/wallabyfinancial/foursquare-api-java/compare/master...ganchix:master
Copy those 3 raw classes (Category, GeoCodeFeature and Icon) as they are and add them into your porject under the package fi.foyt.foursquare.api.entities and that's it
Note 1: when you replace classes (same package and class name) in yur project, the clasloader will use yours instead of the classes provided by the jar dependency, so, there is a quick fix.
I did that and it worked like a charm
Note 2: As soon as the sdk is updated, you should remove this patch and upgrade the sdk dependency
Hope it helps

Can not add user to a group with Ldap in Java

I am new with using Ldap API for Java and I want to add a user to a group but I'm failing all the time.
I am using this code for adding specific user to a specific group:
private void insertUserToGroup(List<DistinguishedName> memberOf, DistinguishedName newUserDN) {
try
{
// Loop all groups to put the user in.
for(DistinguishedName groupDn : memberOf) {
String encodedGroupDn = groupDn.encode(); // Example: "cn=GROUP_SKL, ou=roles"
String encodedUserDn = newUserDN.encode(); // Example: "cn=user_dfh, ou=external"
// Now. Add user to a group.
ModificationItem member[] = new ModificationItem[1];
member[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", encodedUserDn));
ldapTemplate.modifyAttributes(encodedGroupDn, member);
}
} catch ( InvalidAttributeValueException exc ) {
throw exc;
} catch ( NameAlreadyBoundException exc ) {
throw exc;
} catch ( NameNotFoundException exc ) {
throw exc;
} catch (Exception exc) {
throw exc;
}
}
The input arguments is list of groups and the user and you can see in the example comments how the DistinguishedName will look like.
1. And the exception i get when i run ldapTemplate.modifyAttributes(encodedGroupDn, member); is:
org.springframework.ldap.NameNotFoundException: [LDAP: error code 32 - 00000525: NameErr: DSID-031A11CC, problem 2001 (NO_OBJECT), data 0, best match of:
''
];
nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 - 00000525: NameErr: DSID-031A11CC, problem 2001 (NO_OBJECT), data 0, best match of:
''
];
remaining name 'cn=GROUP_SKL, ou=roles'
2. I have tried to run modifyAttributes(...) with other attributes like "description", "company" and that works for both Groups and Users but not the attribute "member".
3. So the question is. What name do it expect? Is the DistinguishedName wrong? Or is this way to add a user to a group totally wrong? Or is it some details I am missing?
Now I found the error.
All I needed was to use the full address for the User DN. So I think that 'member' attribute for the group must have the full address. So both DN looks like this now:
encodedGroupDn = "cn=GROUP_SKL, ou=roles"
encodedUserDn = "cn=user_dfh, ou=external, ou=main, dc=nr, dc=company, dc=local"
And that works!

Java: Apache Velocity Parser Error on Curly Brace

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.

Categories