Can problemHandler catch Exception of trying to convert empty string to map? - jackson

I need to create a validator for JSON input and I want to try to defer Exception to be thrown as late as I could. Many Exceptions can be disable by DeserializationFeature like READ_UNKNOWN_ENUM_VALUES_AS_NULL. For other Exceptions, I am thinking if I could use DeserializationProblemHandler to catch all of them so that I have same place to write logic for all fields.
However, the handler is not able to catch all kind of invalid string. Like I want to convert a string to a list. Handler can find "12" is unexpected token but it will not work for string like "" or "foo" or "{".
Is there any way to set some rule like conversion failure using fall back null for all fields? Then I can use the returned object to collect error type of all fields.

Related

What's the difference between string template and log framework's placeholder in Kotlin?

And now, I am trying to rewrite my java application in Kotlin. And then, I met the log statement, like
log.info("do the print thing for {}", arg);
So I have two ways to do the log things in Kotlin like log.info("do the print thing for {}", arg) and log.info("do the print thing for $arg"). The 1st is delegate format to framework like Slf4j or Log4j; the 2nd is using Kotlin string template.
So what's the difference and which one's performance is better?
In general, these two ways produce the same log, unless the logging library is also configured to localise the message and parameters when formatting the message, which Kotlin's string interpolation does not do at all.
The crucial difference lies in the performance, when you turn off logging (at that particular level). As SLF4J's FAQ says:
There exists a very convenient alternative based on message formats.
Assuming entry is an object, you can write:
Object entry = new SomeObject();
logger.debug("The entry is {}.", entry);
After evaluating whether to log or not, and only if the decision is
affirmative, will the logger implementation format the message and
replace the '{}' pair with the string value of entry. In other words,
this form does not incur the cost of parameter construction in case
the log statement is disabled.
The following two lines will yield the exact same output. However, the
second form will outperform the first form by a factor of at least 30,
in case of a disabled logging statement.
logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
Basically, if the logging is disabled, the message won't be constructed if you use parameterised logging. If you use string interpolation however, the message will always be constructed.
Note that Kotlin's string interpolation compiles to something similar to what a series of string concatenation (+) in Java compiles to (though this might change in the future).
"foo $bar baz"
is translated into:
StringBuilder().append("foo ").append(bar).append(" baz").toString()
See also: Unable to understand why to use parameterized logging

How to do a fail fast in Kotlin properly?

I want to fail fast if a specific function is returning null. I have no case where default value would make processing meaningful.
This is the snippet:
val entityAttributes = entity.optJSONObject("Attributes") ?: run {
LOG.error("Could not find 'Attribute' entry in Entity object")
return
}
So if entity.optJSONObject("Attributes") returns null (which it does desipite the opt*) I want to escape from the function scope.
Is the way I did it the proper one? I am fairly new to Kotlin and want to get used to the proper ways of doing these things as early as possible.
You can return from the function early like you do above. If your function returns something besides Unit, then you'd have to return some default value.
Throwing an exception allows you to exit a function without returning anything, but the exception will crash the program if you don't catch it somewhere. Sometimes this is exactly what you want to happen if the error is something that should never happen, because then you'll catch it during testing and be able to fix it before releasing your application.
Use the global error(cause: Any) function and it will immediately throw an IllegalStateException.

QueryDSL + PathBuilder + cast to string

I am filtering PrimeFaces DataTables using dynamic filters.I have this working using Spring org.springframework.data.jpa.domain.Specification.Now I am wondring how to do the same using QueryDSL.
Using specification I can use javax.persistence.criteria.Root to get a javax.persistence.criteria.Join, use javax.persistence.criteria.Expression.as(Class<String> type) to cast it to String and finally use javax.persistence.criteria.CriteriaBuilder.like(Expression<String> x, String pattern, char escapeChar).
How do I do the same in QueryDSL ? I can get PathBuilder using new PathBuilder<T>(clazz, "entity") (do you really have to use the variable here? I would like my class to be generic...) but then the com.mysema.query.types.path.PathBuilder.get(String property) returns new PathBuilder instead of an Expression.
If I try to use com.mysema.query.types.path.PathBuilder.getString(String property) I get java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Integer].
Seems like the part I am missing is the cast.
I'm quite sure someone was dealing with the same thing already.
Thanks.
Edit: Stack trace for IllegalArgumentException
Trying to search for text "1" inside integer column using com.mysema.query.types.path.PathBuilder.getString(String property) - that's where I need the cast to happen :
Caused by: java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [java.lang.Integer]
at org.hibernate.ejb.AbstractQueryImpl.validateParameterBinding(AbstractQueryImpl.java:375)
at org.hibernate.ejb.AbstractQueryImpl.registerParameterBinding(AbstractQueryImpl.java:348)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:375)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:442)
at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:72)
at com.mysema.query.jpa.impl.JPAUtil.setConstants(JPAUtil.java:44)
at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:130)
at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:97)
at com.mysema.query.jpa.impl.AbstractJPAQuery.list(AbstractJPAQuery.java:240)
at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.findAll(QueryDslJpaRepository.java:102)
...
To get a valid condition you will need to take the types of the properties into account, e.g.
pathBuilder.getNumber(Integer.class, property).stringValue().like(likePattern)
I was researching a similar topic until I came across this aged question. I hope my answer will be helpful to some.
I think the possible solution lies (exclusively) outside of QueryDSL. You can use common Java reflection to obtain the field type, something like
Class type = clazz.getDeclaredField(criteria.getKey()).getType();
// don't forget to catch exception if field doesn't exist ..
switch(type.getSimpleName()) {
case "String":
StringExpression exp = entityPath.getString(...);
}
That way you can have a reasonably dynamic implementation.

Serializing Exceptions WCF + Silverlight

I have a WCF service I use to submit bugs for my project. Snippet of the data class:
Private _exception As Exception
<DataMember()> _
Public Property Exception As Exception
Get
Return _exception
End Get
Set(ByVal value As Exception)
_exception = value
End Set
End Property
I have a Silverlight app that uses the WCF service to send any bugs home if and when they occur. This is the error I'm testing with:
Dim i As Integer = 5
i = i / 0
The problem is SL is banging on with this message:
System.ServiceModel.CommunicationException was unhandled by user code
Message=There was an error while trying to serialize parameter :bug. The InnerException message was 'Type 'System.OverflowException' with data contract name 'OverflowException:http://schemas.datacontract.org/2004/07/System' is not expected. Add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.
Is there some trick to get a generic .NET Exception (any InnerException) to serialize properly? I'm not doing anything funky with the exception - it's just a plain 'ol exception
Thanks for any help.
I doubt very much that you can serialize a .NET-specific type like an Exception. I recommend you create your own class to hold the parts of the exception you want serialized.
This may be a problem with implicitly casting the OverflowException into a System.Exception.
The data contract serializer is very specific. This can be good and bad.
I would try just throwing a new System.Exception to see if this works OK.
If this is the case, you may need to dumb down the exception, creating a new System.Exception with the original exception message in it.
Or, like John said, you might have a better go of it if you create a custom error class that holds the exception info.

Proper use of try .. catch

Should I be using this method of throwing errors:
if (isset($this->dbfields[$var])) {
return $this->dbfields[$var];
} else {
throw new FieldNotFoundException($var);
}
or this style:
try {
return $this->dbfields[$var];
} catch (Exception $e) {
throw new FieldNotFoundException($var);
}
...or something else altogether?
quick explanation of the code: $this->dbfields is an array. isset() checks if a variable is set, in this case, whether the array element exists.
The second example is bad. You're taking a lot of overhead to catch an exception when, as you demonstrate, it's just as easy to prevent the exception in the first place. Plus you also assume you know why that exception was thrown - if there was some other exception, like say an out of memory or something, you're reporting it as a "field not found" even if it wasn't.
Keep in mind that try/catch in languages like C++ and Java are very expensive because of all the state they have to save and restore. Python, on the other hand, has very cheap exceptions and they positively encourage you to use a try/except for simple validation. But even so, catching everything and pretending it's one type of exception is still bad.
//First let's do the checks.
if(!isset($this->dbfields[$var]))
throw new FieldNotFoundException($var);
//Now we're in the clear!
return $this->dbfields[$var];
Catching "Exception" is not, most of the time, considered a good practice, out of the two you displayed, I would use option 1.
Catching all exceptions may hide a different exception and mask it as a FileNotFoundException.
I prefer the first one, but if dbfields[$var] throws something reasonable when you access a non-existent element, then I'd prefer just returning it without checking.
I don't particularly like changing the exception type unless I have a good reason -- also if you do, make sure to try to preserve the original exception and stack trace.
Just re-read your explanation.
I guess your method there in #1 is going to catch any exceptions that might be thrown and simply return a bool. I definitely don't like the catching of the generic exception most of the time, so #2 wouldn't be my choice.
"...or something else altogether?"
Neither is very good, so something else would be appropriate.
Fix version 2 to catch the correct exception, not every possible exception. Post that as option 3. I'll upvote something that catches a specific exception instead of Exception.
This is far from language-agnostic.
Some languages won't throw errors for accessing non-existant fields, and the preferred pattern depends a lot on the implementations of the arrays, tables, objects, etc.