Java Style: Catching a bunch of slightly different errors - java

In a program I'm working on in Java where I have to read data from a file. The data is formatted so that each line contains all the necessary information to construct a new object. When I parse the data, I have a block of code that looks something like this:
String[] parts = file.nextLine().split(",");
String attr1 = parts[0];
int attr2, attr3;
try{
attr2 = Integer.parseInt(parts[1]);
} catch (NumberFormatException ex){
System.out.println("Could not parse attr2, got " + parts[1] + ".");
return;
}
try{
attr3 = Integer.parseInt(parts[2]);
} catch (NumberFormatException ex){
System.out.println("Could not parse attr3, got " + parts[2] + ".");
return;
}
ClassA attr4 = null, attr5 = null, attr6 = null;
try{
...
} catch (SomeExceptionType ex){
System.out.println("Could not parse attr4, got " + parts[3] + ".");
}
...
I find myself repeating the same simple try block over and over again. In an attempt to mitigate the situation and adhere to the DRY principle a bit more, I introduced some attempt methods:
int attr2 = attemptGetInt(parts, 1, "attr2");
int attr3 = attemptGetInt(parts, 2, "attr3");
ClassA attr4 = attemptGetClassA(parts, 3, "attr4");
...
// Somewhere in the class
public int attemptGetInt(String[] parts, int index, String name) throws SomeOtherException1{
try{
return Integer.parseInt(parts[index]);
} catch (NumberFormatException ex){
throw new SomeOtherException1("Could not parse " + name + ", got " + parts[index] + ".");
}
}
public ClassA attemptGetClassA(String[] parts, int index, String name) throws SomeOtherException2{
try{
return ...
} catch (SomeExceptionType ex){
throw new SomeOtherException2("Could not parse " + name + ", got" + parts[index] + ".");
}
}
...
Even this feels weird though, because there are a lot of different types I have to return that all sort of have the same but slightly different code and need to catch a slightly different error each time (i.e. I have to create an attemptGetClassB and attemptGetClassC and so on, a bunch of times with similar code each time).
Is there an elegant way of writing code like this?

If you have control over the format of the input file you might wish to change it to XML with a schema. That way the parser itself takes care of a lot of this type of checking for you.
However from the nature of the question I assume the format is fixed. In that case I would suggest splitting the syntax checking and parsing into separate steps for each line.
An easy way to do the syntax checking is using a regexp. Fairly complex syntax can be encoded in a regular expression so unless the files contain some sort of nesting (in which case DEFINITELY use XML instead) then it should be fairly straightforward.
The second step of parsing should then only return exceptions by exception :-) You still need to catch them but it's perfectly good form to gather all of your catches into a single block because it should only be used when debugging: in normal operations the syntax check will catch errors before this step.
My view is that this design is more intuitive and obvious. It may have a downside in error reporting if you specifically want to report on each error separately. In that case you'll need to break the string into substrings first (using a Scanner for example) and then syntax check each substring.
As a final note, opinions vary on this but my personal preference is not to use exception handling for conditions that occur in normal operations. They are not well suited for that (in my opinion). Better to do what I'm suggesting here: have explicit code to check error conditions before processing and then use exceptions for things that should not normally occur.

Related

Encoding a URL Query Parameter so it can have a '+'

Apparently, in the move from Spring Boot 1 to Spring Boot 2 (Spring 5), the encoding behavior of URL parameters for RestTemplates changed. It seems unusually difficult to get a general query parameter on rest templates passed so that characters that have special meanings such as "+" get properly escaped. It seems that, since "+" is a valid character, it doesn't get escaped, even though its meaning gets altered (see here). This seems bizarre, counter-intuitive, and against every other convention on every other platform. More importantly, I can't figure out how to easily get around it. If I encode the string first, it gets double-encoded, because the "%"s get re-encoded. Anyway, this seems like it should be something very simple that the framework does, but I'm not figuring it out.
Here is my code that worked in Spring Boot 1:
String url = "https://base/url/here";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
for (Map.Entry<String, String> entry : query.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
HttpEntity<TheResponse> resp = myRestTemplate.exchange(builder.toUriString(), ...);
However, now it won't encode the "+" character, so the other end is interpreting it as a space. What is the correct way to build this URL in Java Spring Boot 2?
Note - I also tried this, but it actually DOUBLE-encodes everything:
try {
for (Map.Entry<String, String> entry : query.entrySet()) {
builder.queryParam(entry.getKey(), URLEncoder.encode(entry.getValue(),"UTF-8" ));
}
} catch(Exception e) {
System.out.println("Encoding error");
}
In the first one, if I put in "q" => "abc+1#efx.com", then, exactly in the URL, I get "abc+1#efx.com" (i.e., not encoded at all). However, in the second one, if I put in "abc+1#efx.com", then I get "abc%252B1%2540efx.com", which is DOUBLE-encoded.
I could hand-write an encoding method, but this seems (a) like overkill, and (b) doing encoding yourself is where security problems and weird bugs tend to creep in. But it seems insane to me that you can't just add a query parameter in Spring Boot 2. That seems like a basic task. What am I missing?
Found what I believe to be a decent solution. It turns out that a large part of the problem is actually the "exchange" function, which takes a string for a URL, but then re-encodes that URL for reasons I cannot fathom. However, the exchange function can be sent a java.net.URI instead. In this case, it does not try to interpolate anything, as it is already a URI. I then use java.net.URLEncoder.encode() to encode the pieces. I still have no idea why this isn't standard in Spring, but this should work.
private String mapToQueryString(Map<String, String> query) {
List<String> entries = new LinkedList<String>();
for (Map.Entry<String, String> entry : query.entrySet()) {
try {
entries.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
} catch(Exception e) {
log.error("Unable to encode string for URL: " + entry.getKey() + " / " + entry.getValue(), e);
}
}
return String.join("&", entries);
}
/* Later in the code */
String endpoint = "https://baseurl.example.com/blah";
String finalUrl = query.isEmpty() ? endpoint : endpoint + "?" + mapToQueryString(query);
URI uri;
try {
uri = new URI(finalUrl);
} catch(URISyntaxException e) {
log.error("Bad URL // " + finalUrl, e);
return null;
}
}
/* ... */
HttpEntity<TheResponse> resp = myRestTemplate.exchange(uri, ...)

Checkmarx SQL injection high severity issue

I am getting a high severity issue in this method:
public void recordBadLogin(final String uid, final String reason, final String ip) throws DataAccessException {
if (Utils.isEmpty(uid)) {
throw new DataAccessException("User information needed to update , Empty user information passed");
}
try {
String sql = (String) this.queries.get(IUtilDAO.queryKeyPrefix + UtilDAO.RECORD_FAILED_LOGIN);
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("uid", uid.trim());
paramMap.put("reason", (reason != null ? reason.trim() : "Invalid userid/password"));
paramMap.put("ip", ip);
this.namedJdbcTemplate.update(sql, paramMap);
} catch (Exception e) {
throw new DataAccessException("Failed to record bad login for user " + uid, e);
}
}
This line of code is causing the issue:
String sql = (String) this.queries.get(IUtilDAO.queryKeyPrefix + UtilDAO.RECORD_FAILED_LOGIN);
queries is a properties object and the prepared statement is being retrieved given IUtilDAO.queryKeyPrefix + UtilDAO.RECORD_FAILED_LOGIN. And those 2 arguments are constants. Logically I don't see how this can cause an SQL injection issue as the prepared statement is being retrieved from a dictionary. Does anyone have an idea if this is a false positive or if there is an actual vulnerability present?
It's hard to tell from the example given, but I'd guess that the properties object was tainted by untrusted data. Most code flow analysis tools will taint the entire data structure if any untrusted data is placed in it.
Technically this is a "false positive". But architecturally it's something that should be fixed - it's generally a bad idea to mix trusted and untrusted data together in the same data structure. It makes it easy for future developers to misunderstand the status of a particular element, and makes it harder for both humans and tools to code review for security issues.

How to you implements mongoTemplate.findDistinct()?

Im trying to use the findDistinct function from mongoTemplate but i always retrieve an empty result list.
Can you help me out to spot the problem ? Or maybe you have a simpliest way to do it
NB:
I do have data in my collection
(on a basic find, i fetch more than 300 results in the list but all of this result are the same excepting on one key, i want all the distinct object from their NAME value for instance )
I tryied this :
List<DiffusionListImpl> list = new ArrayList<>();
try{
query = new Query(Criteria.where("CUSTOMERNUMBER").is(1));
list = mongoTemplate.findDistinct(query, KeyWhereIWantTheDistinct, collectionName,
KlassResultModel.class);
} catch (MongoException e) {
logger.error("MongoException: " + e);
} catch (Exception e) {
logger.error("Error: " + e);
}
return list;
My bad, i misread the documentation.
But i find it akward to have this kind of comportement of this function.
I have to make a call to the DB to fetch a list of distinct value and then make another Call of the same DB to retrieve the object.
Is there any way to do it in one call? (Performance issue)
It can be done in one DB call, use below code.
final List<DiffusionListImpl> result =
IteratorUtils.toList(this.mongoTemplate.getCollection("collectionName")
.distinct("fieldName", query.getQueryObject(), DiffusionListImpl.class)
.iterator());
for IteratorUtils you can use apache
import org.apache.commons.collections4.IteratorUtils;

How to catch and modify data over exception occurred during Stream usage

I am currently working over CSV exports. I am fetching header from properties file with below code -
String[] csvHeader = exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s ->messageSource.getMessage("report."+s, null, locale)).toArray(String[]::new);
The above code works well. But i need to find a way to handle exception and also fetch data from another file, if it is not found in above file. I am expecting to use somewhat below code -
try{
exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s ->messageSource.getMessage("report."+s, null, locale)).toArray(String[]::new);
}catch(NoSuchMessageException e){
// code to work over lacking properties
}
I want to catch the 's' element in catch block (or in other good way). So that i can fetch it from another file and also add its return to current csvHeader.
One way is to make for each element a try catch block like:
exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s -> {
String result;//Put the class to which you map
try{
result = messageSource.getMessage("report."+s, null, locale);
}catch(NoSuchMessageException e){
// code to work over lacking properties here you have access to s
}
return result;
}
).toArray(String[]::new);
Another solution will be to check for specific problems and then there is no need to catch exceptions. For example if s is null and then you want to get the data from another place:
exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s -> {
String result;//Put the class to which you map
if(null == s)// Some condition that you want to check.
{
//get info from another place
//result = ....
}
else
{
result = messageSource.getMessage("report."+s, null, locale);
}
return result;
}
).toArray(String[]::new);

com.ibm.icu.text.DecimalFormat always throws ParseException

With the following code I only want to allow positive numbers. For some reason i am not even able to parse the strings correctly:
DecimalFormat dfNoNegative = new DecimalFormat("#,##0.00");
dfNoNegative.setNegativePrefix("");
try {
System.out.println(dfNoNegative.parse("123.00"));
} catch (ParseException e) {
System.out.println(e.getMessage());
System.out.println(e.getErrorOffset());
e.printStackTrace();
}
Error message and ErrorOffset:
Unparseable number: "123.00"
6
Can anyone guide me where I am mistaken? An example for a working String would be good as well
My mistake was to dfNoNegative.setNegativePrefix(""); to nothing (""). This doesn't work, because the String started directly with the number and 123 is not "", and therefore it fails. Basically this method overwrites what should be used as negative prefix (default is -). If you set it to ! as example, System.out.println(dfNoNegative.parse("!123.00")); would print -123.

Categories