A spring aop pointcut can filter for the combination of an annotation and a return type? - annotations

#Pointcut(Execution(#com.annotions.MyAnnotation void *(..))
Would this be a valid pointcut, if I want only methods to be advised with the #MyAnnotation and have the return type void?

No, your pointcut would be invalid for several reasons, mostly because you cannot have tested it in a real application and just posted pseudo code here instead:
The #Pointcut annotation argument needs to be enclosed in double quotes because it is a String.
There is one closing parenthesis ) missing.
The keyword execution must be written in lower-case characters, yours starts with an upper-case one.
Other than that, i.e. if you write the pointcut like this, it would be correct:
#Pointcut("execution(#com.annotions.MyAnnotation void *(..))")
As an alternative, you can separate the two requirements into distinct pointcut specifiers like this:
#Pointcut("execution(void *(..)) && #annotation(com.annotions.MyAnnotation)")
In this case it might look a tad lengthy, but if your execution pointcut is more complex, it is nice to separate the annotation pointcut from it so as to make the overall pointcut more readable.
I think it could be helpful for you to read the Spring AOP and AspectJ manuals. Good luck and don't give up, it is going to get easier if you use AOP syntax more often.

Related

What's the correct way to convert from StringBuilder to String?

From what I've seen online, people seem to suggest that the toString() method is to be used, however the documentation states:
Creates a String representation of this object. The default representation is platform dependent. On the java platform it is the concatenation of the class name, "#", and the object's hashcode in hexadecimal.
So it seems like using this method might cause some problems down the line?
There is also mkString and result(). The latter of which seems to make the most sense. But I'm not sure what the differences between these 3 methods are and if that's how result() is supposed to be used.
The toString implementation currently just redirects to the result method anyway, so those two methods will behave in the same way. However, they express slightly different intent:
toString requests a textual representation of StringBuilders current state that is "concise but informative (and) that is easy for a person to read". So, theoretically, the (vague) specification of this method does not forbid abbreviating the result, or enhancing conciseness and readability in any other way.
result requests the actual constructed string. No different readings seem possible here.
Therefore, if you want to obtain the resulting string, use result to express your intent as clearly as possible.
In this way, the reader of your code won't have to wonder whether StringBuilder.toString might shorten something for the sake of "conciseness" when the string gets over 9000 kB long, or something like that.
The mkString is for something else entirely, it's mostly used for interspersing separators, as in "hello".mkString(",") == "h,e,l,l,o".
Some further links:
The paragraph with "hashcode in hexadecimal" describes the default. It is just documentation inherited from AnyRef, because the creator of StringBuilder didn't bother to provide more detailed documentation.
If you look into code, you'll see that toString is actually just delegating to result.
The documentation of StringBuilder also mentions result() in the introductory overview paragraph.
Just use result().
TL;DR; use result as stated in the docs.
toString MUST never be called in anything at all for another purpose other than a quick debug.
mkString is inherited from collections hierarchy and it will basically create another StringBuilder so is very inefficient.

JPA 2 criteria provide runtime type for gt operator

I am building a highly generic query mechanism on top of the JPA Criteria. I get as input an XML describing the query, something like this:
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Criteria xmlns='criteria' maxResults='2'>
<Expression>
<CompareRestriction propertyType='Date' operator='GREATER_THAN_OR_EQUALS' propertyName='deliveryDate'>2010-07-02</CompareRestriction>
<CompareRestriction propertyType='Float' operator='GREATER_THAN_OR_EQUALS' propertyName='weight'>10f</CompareRestriction>
<Restriction operator='NOT_NULL' propertyName='maxDiameter'/>
<LogicalExpression operator='OR'>
<LeftHandSideCompare propertyType="Integer" operator="EQUALS" propertyName="weight">31</LeftHandSideCompare>
<RightHandSide operator='NOT_NULL' propertyName='lastChangedDate'/>
</LogicalExpression>
<LogicalExpression operator='OR'>
<LeftHandSideCompare propertyType="Integer" operator="EQUALS" propertyName="weight">31</LeftHandSideCompare>
<RightHandSide operator='NOT_NULL' propertyName='lastChangedDate'/>
</LogicalExpression>
</Expression>
<Order propertyName='deliveryDate' type='DESC'/>
</Criteria>
and I parse this thing and build the corresponding criteria. Currently I am facing a problem with it comes to comparison operators (<,>,<=,=>) as I deal with different numerical types: I have fields with Float, Integer or Long value. So when I am mapping I do something like this:
switch (leftHandSideCompareRestriction.getOperator().value()) {
...
case "LESS_THAN" : innerPredicates.add(criteriaBuilder.gt(rootQuery.<Number>get(propName), NumberUtils.createNumber((value))));
case "LESS_THAN_OR_EQUALS" : innerPredicates.add(criteriaBuilder.gt(rootQuery.<Number>get(propName), NumberUtils.createNumber(value)));
...
}
The NumberUtils is the apache commons NumberUtils utility class
that returns a numerical type based on the input provided (Float, Integer, Long or Double). Now I need a mechanism to provide the type also for the
rootQuery<T>.get(propName)
at runtime, otherwise the JPA is complaining that I provided a Float instead of a Integer or the other way around. I tried several things and now I kind of ran out of ideas. I would highly appreciate and thoughts, ideas, suggestions about how to accomplish this in a robust fashion.
I seems that initially I missed something - I am not sure how. There some kind of issue in a different part. So, doing the query like this: it will work for sure. I tried with the following types:
Integer
Float
And it worked as expected for the following operations: >,<, <=, =>. In conclusion using Number and the NumberUtils fixes this issue in quite an elegant manner, as the appropriate type is created by the NumberUtils and JPA takes the top of the hierarchy for Number.

Parameterized logging in slf4j - how does it compare to scala's by-name parameters?

Here are two statements that seem to be generally accepted, but that I can't really get over:
1) Scala's by-name params gracefully replace the ever-so-annoying log4j usage pattern:
if (l.isDebugEnabled() ) {
logger.debug("expensive string representation, eg: godObject.toString()")
}
because the by-name-parameter (a Scala-specific language feature) doesn't get evaluated before the method invocation.
2) However, this problem is solved by parametrized logging in slf4f:
logger.debug("expensive string representation, eg {}:", godObject[.toString()]);
So, how does this work?
Is there some low-level magic involved in the slf4j library that prevents the evaluation of the parameter before the "debug" method execution? (is that even possible? Can a library impact such a fundamental aspect of the language?)
Or is it just the simple fact that an object is passed to the method - rather than a String? (and maybe the toString() of that object is invoked in the debug( ) method itself, if applicable).
But then, isn't that true for log4j as well? (it does have methods with Object params).
And wouldn't this mean that if you pass a string - as in the code above - it would behave identically to log4j?
I'd really love to have some light shed on this matter.
Thanks!
There is no magic in slf4j. The problem with logging used to be that if you wanted to log let's say
logger.debug("expensive string representation: " + godObject)
then no matter if the debug level was enabled in the logger or not, you always evaluated godObject.toString()which can be an expensive operation, and then also string concatenation. This comes simply from the fact that in Java (and most languages) arguments are evaluated before they're passed to a function.
That's why slf4j introduced logger.debug(String msg, Object arg) (and other variants for more arguments). The whole idea is that you pass cheap arguments to the debug function and it calls toString on them and combines them into a message only if the debug level is on.
Note that by calling
logger.debug("expensive string representation, eg: {}", godObject.toString());
you drastically reduce this advantage, as this way you convert godObject all the time, before you pass it to debug, no matter what debug level is on. You should use only
logger.debug("expensive string representation, eg: {}", godObject);
However, this still isn't ideal. It only spares calling toString and string concatenation. But if your logging message requires some other expensive processing to create the message, it won't help. Like if you need to call some expensiveMethod to create the message:
logger.debug("expensive method, eg: {}",
godObject.expensiveMethod());
then expensiveMethod is always evaluated before being passed to logger. To make this work efficiently with slf4j, you still have to resort back to
if (logger.isDebugEnabled())
logger.debug("expensive method, eg: {}",
godObject.expensiveMethod());
Scala's call-by-name helps a lot in this matter, because it allows you to wrap arbitrary piece of code into a function object and evaluate that code only when needed. This is exactly what we need. Let's have a look at slf4s, for example. This library exposes methods like
def debug(msg: => String) { ... }
Why no arguments like in slf4j's Logger? Because we don't need them any more. We can write just
logger.debug("expensive representation, eg: " +
godObject.expensiveMethod())
We don't pass a message and its arguments, we pass directly a piece of code that is evaluated to the message. But only if the logger decides to do so. If the debug level isn't on, nothing that's within logger.debug(...) is ever evaluated, the whole thing is just skipped. Neither expensiveMethod is called nor any toString calls or string concatenation happen. So this approach is most general and most flexible. You can pass any expression that evaluates to a String to debug, no matter how complex it is.

Why does Iterables.find() in Guava throw NoSuchElementException, instead of returning null?

I love Google Guava and use it a lot, but there is one method I always find me writing..
public static <T> T tryFind(Iterable<T> iterable, Predicate<T> predicate){
for(T t : iterable){
if(predicate.apply(t)){
return t;
}
}
return null;
}
To me this seems to be a very useful addition to Iterables (also to Iterators for that matter), so I'm wondering why it's missing. Also, while I can see the point of having a method that throws NoSuchElementException, perhaps to distinguish between finding a null and not finding the element, that situation only comes up if the predicate you are using is
public boolean apply(T t){
return t==null;
}
which doesn't seem to be a common case.
So why did guava designers chose to have this behavior, instead of just returning null if it can't find it?
Here is the javadoc for [Iterables.find()][1]
[1]: http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#find(java.lang.Iterable, com.google.common.base.Predicate)
We're adding another overload of find() which accepts a default value.
Likely because null is a valid return value. Generally speaking, unless there is a good reason to not support null then it should be supported. If it is supported then you have to handle the case where it exists.
Instead of tryFind() you can use filter and check if it returns an empty collection.
I found that always working with collections is cleaner than directly asking objects.
In my opinion, the NoSuchElementException is better than a late and very difficult to debug NPE...
In most cases, when you are searching an object in a "collection", you know that you would probably find it.
If the object you're looking for is not in the "collection", you're facing an exceptional case... According to me, the NoSuchElementException feedback is more explicit than the meaningless "null".
The default value which will be introduced in a future guava release would be an efficient shortcut to treat the exceptionnal case.
Find would make sense if it could not to find rather finding default value.
Optional<T> Iterables.find(Iterable<T>, Predicate<? super T>)

is SFig language syntax efficient and clear (and better than Spring-Framework's XML DSL)?

ADDENDUM EDIT:
Have not accepted an answer to this as
there has not been any feedback from
experienced Spring Framework
developers.
I've been working on a replacement DSL to use for Spring-Framework applicationContext.xml files (where bean initialization and dependency relationships are described for loading up into the Spring bean factory).
My motivation is that I just flat out don't like Spring's use of XML for this purpose nor do I really like any of the alternatives that have been devised so far. For various reasons that I won't go into, I want to stay with a declarative language and not some imperative scripting language such as Groovy.
So I grabbed the ANTLR parser tool and have been devising a new bean factory DSL that I've dubbed SFig. Here's a link that talks more about that:
SFig™ - alternative metadata config language for Spring-Framework
And here is the source code repository site:
http://code.google.com/p/sfig/
I'm interested to know how I'm doing on the language syntax so far. Do you think SFig is both efficient and clear to understand? (I'm particularly concerned right now with the mulit-line text string):
properties_include "classpath:application.properties";
org.apache.commons.dbcp.BasicDataSource dataSource {
#scope = singleton;
#destroy-method = close;
driverClassName = "${jdbc.driverClassName}";
url = "${jdbc.url}";
username = "${jdbc.username}";
password = "${jdbc.password}";
defaultAutoCommit = true;
}
org.springframework.orm.ibatis.SqlMapClientFactoryBean sqlMapClient {
#scope = singleton;
#init-method = afterPropertiesSet;
#factory-method = getObject;
configLocation = "classpath:sqlmap-config.xml";
dataSource = $dataSource;
}
/* this string will have Java unescape encoding applied */
STRING str = "\tA test\u0020string with \\ escaped character encodings\r\n";
/* this string will remain literal - with escape characters remaining in place */
STRING regexp = #"(\$\{([a-zA-Z][a-zA-Z0-9._]*)\})";
/* multi-line text block - equates to a java.lang.String instance */
TEXT my_multi_line_text = ///
Here is a line of text.
This is yet another. Here is a blank line:
Now picks up again.
///;
/* forward use of 'props' bean */
java.util.HashMap map {
this( $props );
}
/* equates to a java.util.Propertis instance */
PROPERTIES props {
"James Ward" = "Adobe Flex evangelist";
"Stu Stern" = "Gorilla Logic - Flex Monkey test automation";
Dilbert = "character in popular comic strip of same title";
"App Title Display" = "Application: ${app.name}";
"${app.desc}" = "JFig processes text-format Java configuration data";
}
/* equates to a java.util.ArrayList instance */
LIST list {
this( ["dusty", "moldy", "${app.version}", $str] );
[234, 9798.76, -98, .05, "numbers", $props, ["red", "green", "blue"]];
}
I'll provide a bit of background on Spring and it's applicationContext.xml file - that will lend clarity to some of the things going on in SFig syntax.
The applicationContext.xml file is used to express bean initialization for beans that will be managed by the Spring bean factory. So given the example of beans seen in my SFig version of this file, in Java application code one might request the bean factory to make an instance of a bean like so:
SqlMapClient sqlMapClient = getBean("sqlMapClient");
The bean factory takes care of any instantiation and initialization that the bean requires - even to the point of injecting dependencies. In this case, a SqlMapClient bean needs an instance of a dataSource bean (which is also described and referenced in the SFig example).
A bean descriptor relays the following information to the bean factory:
the bean's Java class name
a bean ID by which to request or reference it
bean definition meta attributes (optional)
constructor initialization arguments (optional)
and/or property initializers
The '#' prefixes bean definition meta attributes. These are attributes that are used by the bean factory to manage the bean. For instance, #scope = singleton, would inform the bean factory to make a single instance of the bean, cache it, and hand out references to it when it is requested. The ones that can be set are the same ones defined by the Spring-Framework.
If a bean is to be initialized via a constructor, then that is expressed in SFig by a syntax that appears to be invoking this with arguments in parenthesis.
Or a bean can be initialized by setting its properties. Identifiers that are assigned to and not prefixed by '#' are bean properties.
When referencing a bean that is a required dependency, then it can be referred to by prefixing it's bean ID with '$'. Several examples of this appear in the SFig example.
The ${foo.bar} syle of variable appearing in string literals will be replaced by a Java property value. In this case, properties are loaded from the file application.properties via this line:
properties_include "classpath:application.properties";
Java System properties will be looked to next if not found in any included properties. This is a widely followed practices in many Java frameworks. The current XML-based applicationContext.xml file has a way of permitting this usage too.
Because java.util.Properties are often used to initialize beans, SFig provides the PROPERTIES as a special convenient syntax for declaring a Properties object. Likewise for java.util.List, which has the corresponding SFig LIST. Also, arrays of values can be declared within square brackets [...].
Additionally there is TEXT for declaring blocks of multi-line text. The '#' prefixing a string literal means to turn off escape encoding - a language syntax borrowed from C#.
One of the primary design objectives of the SFig DSL is to remain declarative in nature. I purposely am refraining from adding any imperative scripting features. The complexity of programming logic embedded in a text configuration file will imply possibility of having to debug it. Don't want to open yet another dimension of code debugging.
I haven't much experience with the Spring XML you refer, so you should take the following feedback with a pinch of salt.
As a second and third caveat:
providing a snippet of code will give a flavour of what the language and its semantics are. It is difficult to completely understand some of the choices you have already made (and with good reason), so any feedback here may be completely contradictory or impossible in the light of those choices.
language design is as much an art as a science, and so at this stage, any feedback you may get is likely to be quite subjective.
A larger, meta-, question: as a DSL are you trying to do configuration of Spring, or as a more general class of frameworks?
There: caveat emptor. Now my subjective and incomplete feedback ;)
I'm not sure I understand the reason why you have the # prefix for scope and destroy-method, but not driverClassName. Also the mix of both xml-case and camelCase isn't completely apparent to start with. Is the # prefix a type modifier, or are these keywords in the language?
I'm not completely sure of your intentions about the block header format. You have class name, then a function of that class; is the intention to specify what class your are going to use for a particular function?
e.g.
sqlMapClient: org.springframework.orm.ibatis.SqlMapClientFactoryBean {
# body.
}
or even:
sqlMapClient {
#class = org.springframework.orm.ibatis.SqlMapClientFactoryBean;
# is there a sensible (perhaps built-in) default if this is missing?
}
I like the variable substitution; I presume the values will come from System properties?
I like being able to specify string literals (without escaping), especially for the regular expressions you've shown. However, having multi-character quote or quote modifier seems a little alien. I guess you considered the single-quote (shell and Perl use single-quotes for literal strings).
On the other hand, I think the triple forward slash for multi-line TEXT is the right approach, but two reminiscent of comments in C-style languages. Python uses a triple " for this purpose. Some shell idioms have a multi-line text convention I would not copy.
I very much like the look of properties and config location, using what looks like a URI notion of addressing. If this is a URI, classpath://file.xml may be clearer. I may have the wrong end of the stick here, however.
I also very much like the notion of list and map literals you have, though I'm not sure where:
this comes into it (I guess a call to a Java constructor)
why some types are capitalized, and others are not. Do I take it that there is a default MAP type, which you can be more specific type if you wish to?
is Dilbert an unquoted string literal?
Finally, I'd point you to another configuration DSL, though perhaps more for sysadmin usage: Puppet.
Go well.