<?xml version="1.0" encoding="UTF-8"?><!-- generator="wordpress.com" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>aspectj &amp;laquo; WordPress.com Tag Feed</title>
	<link>http://en.wordpress.com/tag/aspectj/</link>
	<description>Feed of posts on WordPress.com tagged "aspectj"</description>
	<pubDate>Wed, 25 Nov 2009 09:44:43 +0000</pubDate>

	<generator>http://en.wordpress.com/tags/</generator>
	<language>en</language>

<item>
<title><![CDATA[AspectJ and Aspect Oriented Programming]]></title>
<link>http://davidc99.wordpress.com/2009/11/14/aspectj-and-aspect-oriented-programming/</link>
<pubDate>Sun, 15 Nov 2009 00:45:15 +0000</pubDate>
<dc:creator>DavidC99</dc:creator>
<guid>http://davidc99.wordpress.com/2009/11/14/aspectj-and-aspect-oriented-programming/</guid>
<description><![CDATA[I spent some time looking over AspectJ recently, and I&#8217;m somewhat impressed. Granted, I wasn]]></description>
<content:encoded><![CDATA[I spent some time looking over AspectJ recently, and I&#8217;m somewhat impressed. Granted, I wasn]]></content:encoded>
</item>
<item>
<title><![CDATA[Scala Anger AspectJ - An Intervention was in Order]]></title>
<link>http://coffeesgone.wordpress.com/2009/11/06/scala-anger-aspectj-an-intervention-was-in-order/</link>
<pubDate>Fri, 06 Nov 2009 05:01:50 +0000</pubDate>
<dc:creator>Sam Baskinger</dc:creator>
<guid>http://coffeesgone.wordpress.com/2009/11/06/scala-anger-aspectj-an-intervention-was-in-order/</guid>
<description><![CDATA[Scala is going into production at work! Very exciting, even if the details of the deployment put Sca]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://www.scala-lang.org/">Scala </a>is going into production at work! Very exciting, even if the details of the deployment put Scala in a humble introductory role. Amidst all this excitement a huge collection of stack traces slipped by my attention, most of which look akin to :</p>
<blockquote><p><code>java.lang.ClassCastException: org.aspectj.weaver.MissingResolvedTypeWithKnownSignature cannot be cast to org.aspectj.weaver.ReferenceType</code></p></blockquote>
<p>and the line:</p>
<blockquote><p><code>java.lang.RuntimeException: Can't find type scala.collection.mutable.ListBuffer$$anon</code></p></blockquote>
<p>Every time one of these exceptions show up they are related to an inner Java class. Of particular interest was <a href="http://dev.eclipse.org/mhonarc/lists/aspectj-users/msg11318.html">this message </a>I dug up in the <a href="https://dev.eclipse.org/mailman/listinfo/aspectj-users">aspectj-users mailing list </a>which suggests that <a href="http://www.eclipse.org/aspectj/">AspectJ </a>isn&#8217;t particularly intelligent about how it determines the outer class, which, Scala has many of!</p>
<p>The solution for this particular problem was to make a custom META-INF/aop.xml file the details of which are in the AspectJ <a href="http://www.eclipse.org/aspectj/doc/released/devguide/ltw-configuration.html">developer&#8217;s guide</a>! Simple, really&#8230; just a little elusive when staring at a giant stack trace in your QA system. Specifically, adding an <code>&#60;exclude&#62;scala..*&#60;/exclude&#62;</code> line did the trick in the <code>&#60;weaver&#62;</code> section. Notice that there are supposed to be 2 <em>dots</em> in the exclude tag value. The second dot is for regular expression matching.</p>
<p>Now for those wondering, AspectJ is being used in this instance for <a href="http://static.springsource.org/spring/docs/2.5.x/reference/aop.html#aop-aj-ltw"><em>loadtime weaving</em></a> of Java classes as they are loaded (hence the computation of inner or outer classes). What is very exciting is wiring up monitoring code and performance code around classes based on what package they are a part of, including the new Scala code! We just have to be aware that the inner-outer class assumption of Java aren&#8217;t quite the same. We also need to keep an eye on what possible performance impact this has in our Spring Application Context as we need AspectJ around for some <a href="http://static.springsource.org/spring/docs/2.5.x/reference/transaction.html#transaction-declarative-aspectj">transaction management</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Simple caching with Spring AOP]]></title>
<link>http://urmincek.wordpress.com/2009/09/18/simple-caching-with-spring-aop/</link>
<pubDate>Fri, 18 Sep 2009 18:39:53 +0000</pubDate>
<dc:creator>Igor Urminček</dc:creator>
<guid>http://urmincek.wordpress.com/2009/09/18/simple-caching-with-spring-aop/</guid>
<description><![CDATA[It&#8217;s recommended to read Simple caching with AspectJ before you continue. Only difference is i]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>It&#8217;s recommended to read <a href="http://urmincek.wordpress.com/2009/09/06/simple-caching-with-aspectj/">Simple caching with AspectJ</a> before you continue. Only difference is in using Spring AOP.<br />
At first we need to create spring-config.xml and define Spring beans and enable Spring AOP autoproxy for AspectJ:</p>
<pre class="brush: xml;">
&#60;?xml version=&#34;1.0&#34; encoding=&#34;UTF-8&#34;?&#62;
&#60;beans xmlns=&#34;http://www.springframework.org/schema/beans&#34;
	xmlns:xsi=&#34;http://www.w3.org/2001/XMLSchema-instance&#34;
	xmlns:aop=&#34;http://www.springframework.org/schema/aop&#34;
	xsi:schemaLocation=&#34;http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&#34;&#62;

	&#60;aop:aspectj-autoproxy /&#62;
	&#60;bean class=&#34;caching.springaop.CacheAspect&#34; /&#62;

	&#60;bean id=&#34;calc&#34; class=&#34;caching.springaop.Calculator&#34; /&#62;

&#60;/beans&#62;
</pre>
<p>Now we can use <code>Calculator</code> bean created by Spring:</p>
<pre class="brush: java;">
ApplicationContext ctx = new ClassPathXmlApplicationContext(&#34;spring-config.xml&#34;);
Calculator calc = (Calculator) ctx.getBean(&#34;calc&#34;);

// result will be calculated and stored in cache
logger.info(&#34;1 + 2 = &#34; + calc.sum(1, 2));

// result will be retrieved from cache
logger.info(&#34;1 + 2 = &#34; + calc.sum(1, 2));
</pre>
<p>Download full source code as a <a href="http://github.com/igo/demo-caching-with-spring-aop/zipball/master">zip</a> or <a href="http://github.com/igo/demo-caching-with-spring-aop/tarball/master">tar.gz</a> file or <a href="http://github.com/igo/demo-caching-with-spring-aop/tree/master">browse code online on GitHub</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Simple caching with AspectJ]]></title>
<link>http://urmincek.wordpress.com/2009/09/06/simple-caching-with-aspectj/</link>
<pubDate>Sun, 06 Sep 2009 13:15:57 +0000</pubDate>
<dc:creator>Igor Urminček</dc:creator>
<guid>http://urmincek.wordpress.com/2009/09/06/simple-caching-with-aspectj/</guid>
<description><![CDATA[Caching hasn&#8217;t been never so easy to implement before. AspectJ is one of the best (probably th]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Caching hasn&#8217;t been never so easy to implement before. AspectJ is one of the best (probably the best) technologies that can be used for implementing caching system.</p>
<p>There are several ways how to do caching. Object can directly set values to cache, can implement some caching interface or can be fancy and use annotations that sounds to me as a most elegant solution. With annotation you can annotate any method that should be cached. Could be something easier?</p>
<p>Let&#8217;s create <code>@Cacheable</code> annotation:</p>
<pre class="brush: java;">
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Cacheable {

}
</pre>
<p>With this annotation we can mark any expensive, time consuming methods whose results should be cached. For example let&#8217;s create <code>Calculator</code> class that has one very expensive and time consuming method. Every time we call this method with same input it will be executed. It&#8217;s a huge wasting of resources. So we will use our <code>@Cacheable</code> annotation on it&#8217;s function to prevent executing it when it&#8217;s not necessary.</p>
<pre class="brush: java;">
public class Calculator {

	private Logger logger = Logger.getLogger(Calculator.class);

	@Cacheable
	public int sum(int a, int b) {
		logger.info(&#34;Calculating &#34; + a + &#34; + &#34; + b);
		try {
			// pretend this is an expensive operation
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			logger.error(&#34;Something went wrong...&#34;, e);
		}
		return a + b;
	}

}
</pre>
<p>Next we need to create an aspect called <code>CacheAspect</code> that will handle caching. In this aspect we define pointcut that matches all methods annotated with <code>@Cacheable</code>, regardless of number and type of input arguments and return type:</p>
<pre class="brush: java;">
@Pointcut(&#34;execution(@Cacheable * *.*(..))&#34;)
private void cache() {}
</pre>
<p>It is a best practice to annotate empty methods with a pointcut. Function <code>cache()</code> can be considered as a name for a pointcut.<br />
As a last step we need to create an advice &#8211; a function that wraps calling of cacheable methods. This function will be actually called every time empty function <code>cache()</code> is invoked. Advise <code>aroundCachedMethods</code> will take a look into cache for a previously cached result and return it. If it couldn&#8217;t find anything then it will call our time consuming function and store result for next reuse.</p>
<pre class="brush: java;">
@Around(&#34;cache()&#34;)
public Object aroundCachedMethods(ProceedingJoinPoint thisJoinPoint)
		throws Throwable {
	logger.debug(&#34;Execution of Cacheable method catched&#34;);

	// generate the key under which cached value is stored
	// will look like caching.aspectj.Calculator.sum(Integer=1;Integer=2;)
	StringBuilder keyBuff = new StringBuilder();

	// append name of the class
	keyBuff.append(thisJoinPoint.getTarget().getClass().getName());

	// append name of the method
	keyBuff.append(&#34;.&#34;).append(thisJoinPoint.getSignature().getName());

	keyBuff.append(&#34;(&#34;);
	// loop through cacheable method arguments
	for (final Object arg : thisJoinPoint.getArgs()) {
		// append argument type and value
		keyBuff.append(arg.getClass().getSimpleName() + &#34;=&#34; + arg + &#34;;&#34;);
	}
	keyBuff.append(&#34;)&#34;);
	String key = keyBuff.toString();

	logger.debug(&#34;Key = &#34; + key);
	Object result = cache.get(key);
	if (result == null) {
		logger.debug(&#34;Result not yet cached. Must be calculated...&#34;);
		result = thisJoinPoint.proceed();
		logger.info(&#34;Storing calculated value '&#34; + result + &#34;' to cache&#34;);
		cache.put(key, result);
	} else {
		logger.debug(&#34;Result '&#34; + result + &#34;' was found in cache&#34;);
	}

	return result;
}
</pre>
<p>Download full source code as a <a href="http://github.com/igo/demo-caching-with-aspectj/zipball/master">zip</a> or <a href="http://github.com/igo/demo-caching-with-aspectj/tarball/master">tar.gz</a> file or <a href="http://github.com/igo/demo-caching-with-aspectj/tree/master">browse code online on GitHub</a>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[AspectWerkz - Declaring war on spaghetti code]]></title>
<link>http://janeve.wordpress.com/2009/09/02/aspectwerkz-declaring-war-on-spaghetti-code/</link>
<pubDate>Wed, 02 Sep 2009 14:44:45 +0000</pubDate>
<dc:creator>Janeve</dc:creator>
<guid>http://janeve.wordpress.com/2009/09/02/aspectwerkz-declaring-war-on-spaghetti-code/</guid>
<description><![CDATA[I got acquainted with Aspect Oriented Programming (AOP) concepts during my college days. It was my s]]></description>
<content:encoded><![CDATA[I got acquainted with Aspect Oriented Programming (AOP) concepts during my college days. It was my s]]></content:encoded>
</item>
<item>
<title><![CDATA[A busy yet unexciting couple of weeks]]></title>
<link>http://davidcarterca.wordpress.com/2009/06/26/a-busy-yet-unexciting-couple-of-weeks/</link>
<pubDate>Fri, 26 Jun 2009 21:08:33 +0000</pubDate>
<dc:creator>davidcarterca</dc:creator>
<guid>http://davidcarterca.wordpress.com/2009/06/26/a-busy-yet-unexciting-couple-of-weeks/</guid>
<description><![CDATA[I haven&#8217;t posted in a while. It&#8217;s not that I haven&#8217;t been doing anything, it]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I haven&#8217;t posted in a while. It&#8217;s not that I haven&#8217;t been doing anything, it&#8217;s just that what I was doing was the basic stock and trade of any programmer &#8211; coding.  J2EE with a bit of Google&#8217;s Web Toolkit (GWT) thrown in. And none of it pays the bills&#8230; just a hint to anyone out there with work that needs doing.</p>
<p>It&#8217;s not been a week without discovery though. I&#8217;ve been using Apache for quite a few years now and thought I knew it pretty well. Heck, I&#8217;ve even written Apache modules! But I&#8217;ve always been a bit of a small time user in that I&#8217;ve never worked on anything that really pushed it to the limits, except in a test environment. When I started testing my GWT application though, all that changed. Performance was sluggish, taking upwards of 30 seconds to load a page when tested remotely. This is obviously unacceptable, but I&#8217;d made no effort on the performance side, so I wasn&#8217;t really surprised. I&#8217;ve made a living developing and using tools that model the differences between a testing laboratory and the real world. And my real world consisted of multiple tiers that were actually multiple virtual machines running on my development machine and a DSL link (i.e. high speed on the requests, not on the responses) connected through DDNS. Of course it&#8217;s slow.</p>
<p><a href="http://developer.yahoo.com/yslow/">YSlow</a> to the rescue. It&#8217;s a great plugin for Firefox from the folks at Yahoo that measures why pages are slow to load and more importantly offers suggestions for improvement. The first thing it suggested was I use mod_deflate to compress my files. I didn&#8217;t even know you could do this! Where have I been? What a difference this made! I&#8217;m now down to about 3 seconds a page.</p>
<p>Of course, it had other suggestions as well, including cache settings, ETags, and so on. I&#8217;m not so worried about them yet, as I&#8217;m still in pretty active development, but they&#8217;re good to know. Overall, GWT is pretty cache friendly, but there are some files, such as my CSS files, that are still changing pretty quickly. It did surprise me though how limited the configuration options are for Apache when it comes to caching files. I can set options according to a mime type, but not according to a file pattern. This would be useful for caching files such as *.cache.* and *.nocache.*. These are questions that will have to be addressed either by module or by process before deployment, but I&#8217;m happily ignoring them for now.</p>
<p>The other tool that&#8217;s been really useful is <a href="http://getfirebug.com/">Firebug</a>. This was required for YSlow, but the best use I made of it was in debugging my CSS. It allowed me to look at individual elements and discover what styles were being applied. This is very useful when using GWT as the styles may not always be what you expect. It definitely reduced the amount of cursing I did.</p>
<p>Then again, perhaps the most significant event of the last couple of weeks is that there were no significant events. My life as a programmer has taught me to expect otherwise.</p>
<p>There&#8217;s another week or so of heads down development, but then I tackle interesting things again, such as instrumenting Geronimo with ARM. AspectJ, here we come!</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Senior Java Developer]]></title>
<link>http://spillerlaszlo.wordpress.com/?p=1577</link>
<pubDate>Mon, 20 Apr 2009 10:53:11 +0000</pubDate>
<dc:creator>Spiller László</dc:creator>
<guid>http://spillerlaszlo.wordpress.com/?p=1577</guid>
<description><![CDATA[Gained 6 years of experience in Java programming. His last project was the development of distribute]]></description>
<content:encoded><![CDATA[Gained 6 years of experience in Java programming. His last project was the development of distribute]]></content:encoded>
</item>
<item>
<title><![CDATA[Java developer looking for job]]></title>
<link>http://spillerlaszlo.wordpress.com/2009/04/20/java-developer-looking-for-job-2/</link>
<pubDate>Mon, 20 Apr 2009 10:47:26 +0000</pubDate>
<dc:creator>Spiller László</dc:creator>
<guid>http://spillerlaszlo.wordpress.com/2009/04/20/java-developer-looking-for-job-2/</guid>
<description><![CDATA[Has 3 years of experience in Java based software development. His role in the most recent project, w]]></description>
<content:encoded><![CDATA[Has 3 years of experience in Java based software development. His role in the most recent project, w]]></content:encoded>
</item>
<item>
<title><![CDATA[Programowanie aspektowe]]></title>
<link>http://pdziepak.wordpress.com/2009/03/17/programowanie-aspektowe/</link>
<pubDate>Tue, 17 Mar 2009 20:53:07 +0000</pubDate>
<dc:creator>Pawel Dziepak</dc:creator>
<guid>http://pdziepak.wordpress.com/2009/03/17/programowanie-aspektowe/</guid>
<description><![CDATA[Jednym z niepożądanych zjawisk dość często pojawiających się przy tworzeniu aplikacji w oparciu o pr]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Jednym z niepożądanych zjawisk dość często pojawiających się przy tworzeniu aplikacji w oparciu o programowanie zorientowane obiektowo jest nadmierny rozrost metod. Najczęściej muszą one wykonać szereg dodatkowych operacji (sprawdzenie uprawnień, poprawności danych, logowanie czynności, itp.) zanim przystąpią do wykonywania głównego zadania. Często można sobie z tym poradzić uwzględniając takie ewentualności w projekcie aplikacji, zwykle nie jest to jednak idealne rozwiązanie. W tym celu powstała idea <em>programowania zorientowanego aspektowo</em>, które jest przystosowane właśnie do radzenia sobie z tego typu problemami.</p>
<h3>Podstawowe założenia</h3>
<p>Programowanie zorientowane aspektowo w żadnej swojej formie nie wyklucza programowania obiektowego. Właściwie to jest jego uzupełnieniem dostarczającym dodatkowe elementy pozwalające inaczej spojrzeć na projekt aplikacji. Aspektowe języki programowania pozwalają na wskazanie miejsc w kodzie obiektowym w których mają zostać wykonane dodatkowe operacje. Istnieje wiele implementacji tego, lecz zdecydowanie najbardziej popularny jest <em>AspectJ</em> stworzony dla Javy. Wprowadza on następujące elementy:</p>
<ul>
<li><strong>pointcut</strong> &#8211; ogólny opis miejsca przecięcia kodu w którym mają zostać wykonane operacje definiowane przez aspekt. W większości sytuacji jest to wywołanie lub wykonanie kodu funkcji składowej, ale możliwe jest także zdefiniowanie pointcuta przy każdej operacji wykonanej przez metody w danej klasie. Pointcuty mogą także dotyczyć każdego dostępu do pola lub tworzeniu obiektu.</li>
<li><strong>joinpoint</strong> &#8211; konkretne miejsce przecięcia kodu w którym zostaną wstawione dodatkowe operacje definiowane przez dany aspekt.</li>
<li><strong>advice</strong> &#8211; definiuję operację jaka ma zostać wykonana w <em>joinpointach</em>. Kod opisany w <em>advices</em> jest najczęściej wstawiany przed lub po wywołaniu metody w klasie, ale także w przypadku rzucenia wyjątku lub oryginalna funkcja składowa zostaje całkowicie przez niego zastąpiona.</li>
</ul>
<p>W przypadku AspectJ a także wielu innych języków aspekt jest traktowany jak klasa. Oprócz wyżej opisanych elementów może zawierać funkcje składowe lub pola. Mogą być tworzone ich instancje, ale najczęściej aspekt jest singletonem. Dodatkowo można utworzyć hierarchię aspektów korzystając z dziedziczenia. Wiele implementacji pozwala także na istnienie abstrakcyjnych aspektów oraz wirtualnych <em>pointcutów</em>.</p>
<h3>Realizacja</h3>
<p>W przypadku Javy i AspectJ aspekty są realizowane w czasie kompilacji z niewielkim wsparciem refleksyjności dzięki czemu nie wpływają w dużym stopniu na wydajność. W przypadku AspectC++ w związku brakiem wsparcia dynamicznego metaprogramowania ze strony C++ kod aspektowy (napisany w AspectC++) jest najpierw tłumaczony do kodu obiektowego (C++) i dopiero wtedy kompilowany. Bibliotek wprowadzająca aspekty w C# LOOM.NET wykonuje wszystkie operacje z tym związane podczas działania programu, podobnie rzecz się ma w przypadku modułu Perla <em>Aspect</em>. Generalnie sposób realizacji jest inny dla różnych bibliotek i także powinien być świadomym wyborem ponieważ, może w dość dużym stopniu wpłynąć na wydajność programu.</p>
<h3>Zastosowanie</h3>
<p>Najbardziej oczywistymi zastosowaniami programowania aspektowego to wszelkiej maści loggery i narzędzia diagnostyczne. Można także użyć ich do kontrolowania zgodności otrzymanych danych z kontraktami, ale należy pamiętać, że wiele zalet aspektów jest zauważalna dopiero wtedy gdy odnoszą się do tych samych operacji wykonywanych w wielu metodach. Przykładem może być realizacja wzorca Obserwator, gdzie każda zmiana stanu obiektu obserwowanego wymaga poinformowania o niej obiekty obserwujące. W tym przypadku najlepszym rozwiązaniem jest wstawienie po wywołaniu każdej metody (nie oznaczonej jako <code>const</code>) klasy obiektu obserwowanego wywołania metody uaktualniającej obiekty obserwujące.</p>
<h3>Przykład</h3>
<p>Warto przedstawić prosty przykład użycia aspektów w realizacji wzorca Obserwator. Zwykłe podejście wymagałoby czegoś podobnego do kodu poniżej:</p>
<pre>
class Obserwowany {
	// ...
	public void metoda1(int wartość) {
		// ... operacje ...

		uaktualnijObserwatorów();
	}

	public void metoda2(string tekst) {
		// ... operacje ...

		uaktualnijObserwatorów();
	}
}
</pre>
<p>W przypadku AspectJ kod realizujący te same funkcje mógłby wyglądać następująco:</p>
<pre>
class Obserwowany {
	// ...
	public void metoda1(int wartość) {
		// ... operacje ...
	}

	public void metoda2(string tekst) {
		// ... operacje ...
	}
}

aspect WzorzecObserwator {
	pointcut operacja() : execution(public * Obserwowany.*(..));
	after() : operacja() {
		uaktualnijObserwatorów();
	}
}
</pre>
<p>Ten przykład bardzo dobrze prezentuje główne założenie aspektów. Jest nim pozbycie się często powtarzanego kodu niezwiązanego z głównym przeznaczeniem metody z jej kodu. Taka izolacja ma na celu sprawienie kodu bardziej przejrzystym i ułatwienie wprowadzenia ewentualnych zmian.</p>
<h3>Problemy</h3>
<p>Głównym problemem związanym z programowaniem aspektowym jest fakt, że sam pomysł jest stosunkowo młody i w związku z tym wsparcie jest wciąż niewielkie. O ile ze znalezieniem odpowiednich narzędzi nie powinno być problemów to kwestia przyzwyczajenia programistów i to, że języki modelowania takie jak UML nie zostały stworzone z myślą o aspektach sprawiają, że wciąż nie zyskało dużej popularności.</p>
<h3>Podsumowanie</h3>
<p>Programowanie aspektowe, mimo że z niskopoziomowego punktu widzenia nie zmienia praktycznie niczego, to bez wątpienia jest w stanie wprowadzić pewne uporządkowanie w miejscu gdzie typowe programowanie obiektowe pozostawiło dużą swobodę. Rozwiązanie ciekawe, ale jest tylko jednym z wielu sposobów na ominięcie pewnych problemów co sprawia, że nie odnosi, jak na razie, spektakularnych sukcesów.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[AspectJ: Everybody likes AOP]]></title>
<link>http://javaware.wordpress.com/2009/03/05/aspectj-everybody-likes-aop/</link>
<pubDate>Thu, 05 Mar 2009 08:30:19 +0000</pubDate>
<dc:creator>federico</dc:creator>
<guid>http://javaware.wordpress.com/2009/03/05/aspectj-everybody-likes-aop/</guid>
<description><![CDATA[Today I&#8217;d like to introduce a library that proved to be really useful in my last project at wo]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Today I&#8217;d like to introduce a library that proved to be really useful in my last project at work: what I&#8217;m talking about is AspectJ, a framework allowing you to introduce AOP (Aspect Oriented Programming) in your applications.</p>
<p>First of all, what is AOP?</p>
<blockquote><p><strong>Aspect-oriented programming</strong> (<strong>AOP</strong>) is a programming paradigm that increases <span class="mw-redirect">modularity</span> by allowing the separation of cross-cutting concerns, forming a basis for Aspect-oriented software development. Introduced after Object-oriented programming (OOP), it is a post-object-oriented programming paradigm.</p>
<p><em>Wikipedia</em></p></blockquote>
<p><!--more--></p>
<p>To explain what AspectJ is and how it works I will use an example that comes from the last project I worked on.</p>
<p>This was our requirement:</p>
<blockquote><p>Realize an monitoring infrastructure for the application, allowing you to trace where something went wrong and, in response to that, either take some corrective actions or just log what caused the error.</p></blockquote>
<p>Surely there are a whole lot of solutions out there: we could use Log4J to trace every little event in our application, just to mention one of them&#8230; But that would require a lot of &#8220;intrusive code&#8221;. AspectJ gives us a workaround for this case. Let&#8217;s see how it works.</p>
<p>Our sample class will be a really simple class representing a number:</p>
<blockquote><p>public class MyNumber {</p>
<p style="padding-left:30px;">double number;</p>
<p style="padding-left:30px;">public MyNumber(String number){</p>
<p style="padding-left:60px;">this.number = parse(number);</p>
<p style="padding-left:30px;">}</p>
<p style="padding-left:30px;">private double parse(String number){</p>
<p style="padding-left:60px;">return Double.parseDouble(number);</p>
<p style="padding-left:30px;">}</p>
<p style="padding-left:30px;">public double getNumber(){</p>
<p style="padding-left:60px;">return this.double;</p>
<p style="padding-left:30px;">}</p>
<p>}</p></blockquote>
<p>Just as a remainder, <em>Double.parseDouble()</em> method throws a <em>NumberFormatException</em> (unchecked exception) whenever the input String is not a valid number&#8230; So if you look at the code, this means that <em>this.number</em> could be not initialized. This will be our AspectJ class:</p>
<blockquote><p>@Aspect</p>
<p>public class MyNumberAj {</p>
<p style="padding-left:30px;">@Pointcut(&#8220;execution(* MyNumber.parse(..)) &#38;&#38; args(number)&#8221;)</p>
<p style="padding-left:30px;">private void monitorParse(String number){</p>
<p style="padding-left:30px;">}</p>
<p style="padding-left:30px;">@Before(&#8220;monitorParse(number)&#8221;)</p>
<p style="padding-left:30px;">public void start(String number){</p>
<p style="padding-left:60px;">System.out.println(&#8220;Trying to parse &#8221; + number);</p>
<p style="padding-left:30px;">}</p>
<p style="padding-left:30px;">@AfterReturning(pointcut=&#8221;monitorParse(number)&#8221;, returning=&#8221;parsedNumber&#8221;)</p>
<p style="padding-left:30px;">public void parseSucceded(String number, double parsedNumber){</p>
<p style="padding-left:60px;">System.out.println(&#8220;Succeded in parsing: &#8221; + number + &#8221; to &#8221; + parsedNumber);</p>
<p style="padding-left:30px;">}</p>
<p style="padding-left:30px;">@AfterThrowing(pointcut=&#8221;monitorParse(number)&#8221;, throwing=&#8221;exception&#8221;)</p>
<p style="padding-left:30px;">public void parseFailed(String number, JoinPoint jp, Throwable exception){</p>
<p style="padding-left:60px;">System.out.println(&#8220;Failed parsing: &#8221; + number);</p>
<p style="padding-left:60px;">MyNumber mn = (MyNumber) jp.getThis();</p>
<p style="padding-left:60px;">if(exception instanceof NumberFormatException){</p>
<p style="padding-left:90px;">mn.number = 0;</p>
<p style="padding-left:60px;">}</p>
<p style="padding-left:60px;">System.out.println(&#8220;Number value reset to: &#8221; + mn.getNumber());</p>
<p style="padding-left:30px;">}</p>
<p>}</p></blockquote>
<p>Ok, I introduced a bunch of new things&#8230; Most of the work here is define the correct annotations for what you need&#8230; Let&#8217;s see what they mean:</p>
<p>@Aspect: identifies MyNumberAj as an AspectJ class;</p>
<p>@Pointcut: it&#8217;s like saying to AspectJ &#8220;Stay here and tell me what happens, I will tell you what I need to know later on&#8221;, the <em>here</em> being the method within brackets;</p>
<p>@Before, @AfterReturning, @AfterThrowing: On the line above I wrote &#8220;[...]I will tell you what I need to know <em>later on</em>&#8220;. Ok, the time is now <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  By defining a Pointcut I&#8217;m placing an <em>Advice</em> on the method&#8217;s events and by defining, for example, Before, I&#8217;m saying &#8220;call me <strong>right after</strong> <em>parse()</em> method has been called <strong>but before</strong> executing the method&#8217;s code&#8221;&#8230; Based on this, AfterReturning and AfterThrowing are self-explaining, I hope.</p>
<p>Let&#8217;s examine the <em>parseFailed()</em> method: first of all, it is called <strong>only if</strong> the <em>parse()</em> method in <em>MyNumber </em>threw an exception. The code is really easy to understand, i&#8217;d just like to point out on the <em>MyNumber mn = (MyNumber) jp.getThis()</em> line, that obtains an instance of the class under watch from the <em>JoinPoint</em> object. Last, <em>this.number</em> wasn&#8217;t initialized because the <em>parse()</em> method threw an exception: I will initialize it now, after verifying that the exception thrown was really a <em>NumberFormatException</em>.</p>
<p>Whenever you write an <em>Advice</em> you need to keep in mind some gold rules:</p>
<ul>
<li>An <em>Advice</em> must have <strong>at least</strong> all the parameters as the method it is watching (<em>at least</em> because our advice may have some more parameters, as it happens for <em>parseFailed()</em> for example);</li>
<li>Parameters are obviously positional, <strong>and</strong> if you include JoinPoint and <em>returning</em> values (or <em>throwing</em> values) they should be placed as last. For example, <em>public void parseFailed(<span style="color:#0000ff;">String number</span>, <span style="color:#ff0000;">JoinPoint jp</span>, <span style="color:#008000;">Throwable exception</span>)</em>: method&#8217;s parameters are placed in first position(<em>String number</em>), even if there are more than one; then comes the JoinPoint and then the Throwable (or the return value). Should you misplace them, you will get a strange exception message which doesn&#8217;t help you at all in understanding what happened, so be careful.</li>
</ul>
<p>In conclusion, AspectJ <strong>is not merely another logging framework</strong> (remember that I modified an instance variable in one advice), it all depends on how you choose to use it.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[AJDT and Ant]]></title>
<link>http://colinhowe.wordpress.com/2009/02/27/ajdt-and-ant/</link>
<pubDate>Fri, 27 Feb 2009 12:55:49 +0000</pubDate>
<dc:creator>colinhowe</dc:creator>
<guid>http://colinhowe.wordpress.com/2009/02/27/ajdt-and-ant/</guid>
<description><![CDATA[I&#8217;ve just had one of those mornings where you spend hours trying to crack a problem and just g]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I&#8217;ve just had one of those mornings where you spend hours trying to crack a problem and just getting nowhere.</p>
<p>The problem was getting AspectJ to work under Ant but only by using the AJDT 1.6.3 Eclipse plugin. </p>
<p>Unfortunately, this is very poorly documented. Fortunately, this helps you make the right decision: <strong>don&#8217;t use AspectJ in Ant by relying on AJDT</strong>. </p>
<p>There is a very good reason for this (beyond it being hard to get working): you cannot rely on AJDT being available when compiling in anything other than Eclipse (e.g. from a CI server).</p>
<p>What&#8217;s the alternative? Download AspectJ and use these libraries directly in Ant &#8211; they&#8217;re well documented and <em>just work</em>.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Logging With AspectJ]]></title>
<link>http://thinkitdifferently.wordpress.com/2009/02/12/aopwithaspectj/</link>
<pubDate>Thu, 12 Feb 2009 12:45:00 +0000</pubDate>
<dc:creator>Kevin Cador</dc:creator>
<guid>http://thinkitdifferently.wordpress.com/2009/02/12/aopwithaspectj/</guid>
<description><![CDATA[Overview This page describes how Aspect Oriented Programming is used to create a log every time a me]]></description>
<content:encoded><![CDATA[Overview This page describes how Aspect Oriented Programming is used to create a log every time a me]]></content:encoded>
</item>
<item>
<title><![CDATA[Build-time weaving with @Configurable and Eclipse]]></title>
<link>http://agileenterprise.wordpress.com/2009/02/02/build-time-weaving-with-configurable-and-eclipse/</link>
<pubDate>Mon, 02 Feb 2009 19:06:04 +0000</pubDate>
<dc:creator>ricardoekm</dc:creator>
<guid>http://agileenterprise.wordpress.com/2009/02/02/build-time-weaving-with-configurable-and-eclipse/</guid>
<description><![CDATA[@Configurable is a very nice Spring 2.x feature that enables rich domain models with ORM tools like ]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-atconfigurable">@Configurable</a> is a very nice Spring 2.x feature that enables rich domain models with ORM tools like hibernate. I expect to expand on rich domains in a next post. For now I will explain how to use @Configurable.</p>
<p>@Configurable uses <a href="http://www.eclipse.org/aspectj/">AspectJ</a> aspects in order to inject dependencies in non managed classes, I mean, classes that aren&#8217;t instantiate by spring but directly by the programmer (with operator new) or by a ORM  framework.</p>
<p>There are two ways to enable AspectJ aspects. Run-time weaving (usually requires a special agent attached to the VM) and build-time weaving (no special configuration on the server required).</p>
<p>For build-time weaving AspectJ makes available a ant task that can be used along with eclipse.</p>
<p>Here goes a example:</p>
<pre><code>
&#60;project name="aspectwaving" default="compile" &#62;
&#60;taskdef resource="org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties"&#62;
&#60;classpath&#62;</code><code>
&#60;pathelement location="lib/aspectjtools.jar"/&#62;
&#60;/classpath&#62;
&#60;/taskdef&#62;

&#60;target name="compile" &#62;
&#60;!-- destDir: output folder. Xlingwarning, showWeaveInfo: detailed information about weaving --&#62;
&#60;iajc destDir="build/classes/" Xlintwarnings="true" showWeaveInfo="true" aspectPath="lib/spring-aspects.jar" debug="true"&#62;
&#60;inpath&#62;
</code><code>&#60;!-- Pathelement: output folder followed by the package containing the classes to be weaved --&#62;</code>
<code>&#60;pathelement location="build/classes/com/mycompany"/&#62;
&#60;/inpath&#62;
&#60;classpath&#62;
&#60;!-- JARs the target classes depend upon --&#62;
&#60;pathelement location="lib/aspectjrt.jar"/&#62;
&#60;pathelement location="lib/spring.jar"/&#62;
&#60;/classpath&#62;
&#60;/iajc&#62;
&#60;/target&#62;
&#60;/project&#62;
</code></pre>
<p>aspectjtools.jar and aspectjrt.jar comes with <a href="http://www.eclipse.org/aspectj/downloads.php">AspectJ distribution</a>. spring-aspects.jar come with <a href="http://www.springsource.org/download">Spring distribution</a>.</p>
<p>To integrate with Eclipse, select project properties -&#62; builders -&#62; new -&#62; ant build and select the build file as shown in the example above.</p>
<p>This aproach has few drawbacks:</p>
<ul>
<li>Eclipse don&#8217;t always runs the weaving when using &#8220;build automatically&#8221; option. A clean/build should resolve the problem.</li>
</ul>
<ul>
<li>If you don&#8217;t use &#8220;build automatically&#8221; option, each build will take extra five seconds for the weaving process. This is bad when using small development cycles like TDD.</li>
</ul>
<p>If the problems above bother you, you may use <a href="http://www.eclipse.org/ajdt/">AJDT</a> instead.</p>
<p>More info about configurable and rich domains can be found here:</p>
<p><a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html">Anemic Domain Models</a></p>
<p><a href="http://chris-richardson.blog-city.com/migrating_to_spring_2_part_3__injecting_dependencies_into_en.htm">Migrating to Spring 2: Part 3 &#8211; injecting dependencies into entities</a></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[RCP und AspectJ mittels Ant]]></title>
<link>http://miwoe.wordpress.com/2009/01/28/rcp-und-aspectj-mittels-ant/</link>
<pubDate>Wed, 28 Jan 2009 13:09:38 +0000</pubDate>
<dc:creator>miwoe</dc:creator>
<guid>http://miwoe.wordpress.com/2009/01/28/rcp-und-aspectj-mittels-ant/</guid>
<description><![CDATA[Ich habe einige Zeit damit verbracht in Erfahrung zu bringen, wie man AspectJ und RCP miteinander ko]]></description>
<content:encoded><![CDATA[Ich habe einige Zeit damit verbracht in Erfahrung zu bringen, wie man AspectJ und RCP miteinander ko]]></content:encoded>
</item>
<item>
<title><![CDATA[Getting started with AOP (AspectJ)]]></title>
<link>http://vermanitin.wordpress.com/2008/12/26/getting-started-with-aop-aspectj/</link>
<pubDate>Fri, 26 Dec 2008 16:10:40 +0000</pubDate>
<dc:creator>Neo</dc:creator>
<guid>http://vermanitin.wordpress.com/2008/12/26/getting-started-with-aop-aspectj/</guid>
<description><![CDATA[I am thinking of starting with AspectJ. A presentation by Gregor Kiczales http://video.google.com/vi]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>I am thinking of starting with AspectJ.</p>
<p>A presentation by Gregor Kiczales</p>
<p><a href="http://video.google.com/videoplay?docid=8566923311315412414">http://video.google.com/videoplay?docid=8566923311315412414</a></p>
<p>Some links :</p>
<ol>
<li><a href="http://www.eclipse.org/aspectj/downloads.php">http://www.eclipse.org/aspectj/downloads.php</a></li>
<li><a href="http://www.eclipse.org/aspectj/doc/released/progguide/index.html">http://www.eclipse.org/aspectj/doc/released/progguide/index.html</a></li>
<li><a href="http://www.eclipse.org/aspectj/doc/next/index.html">http://www.eclipse.org/aspectj/doc/next/index.html</a></li>
<li><a href="http://yakafokon.wordpress.com/2008/12/02/beans-binding-jsr-295-with-pojo-and-aop/">http://yakafokon.wordpress.com/2008/12/02/beans-binding-jsr-295-with-pojo-and-aop/</a></li>
<li><a href="http://wordpress.com/tag/aspectj/">http://wordpress.com/tag/aspectj/</a></li>
<li><a href="http://www.ibm.com/developerworks/library/j-aopwork1/">http://www.ibm.com/developerworks/library/j-aopwork1/</a></li>
<li><a href="http://www.java2s.com/Code/Java/Spring/AspectJExamplefromProSpring.htm">http://www.java2s.com/Code/Java/Spring/AspectJExamplefromProSpring.htm</a></li>
</ol>
<p>I would post something soon if I really do something with it <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Beans Binding (JSR 295) with POJO and AOP]]></title>
<link>http://yakafokon.wordpress.com/2008/12/02/beans-binding-jsr-295-with-pojo-and-aop/</link>
<pubDate>Tue, 02 Dec 2008 10:05:33 +0000</pubDate>
<dc:creator>yakafokon</dc:creator>
<guid>http://yakafokon.wordpress.com/2008/12/02/beans-binding-jsr-295-with-pojo-and-aop/</guid>
<description><![CDATA[(download the net beans project : BeansBindingTest.zip.ppt : rename to .zip before opening) Beans bi]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>(download the net beans project : <a href="http://yakafokon.wordpress.com/files/2008/12/beansbindingtestzip1.ppt">BeansBindingTest.zip.ppt</a> : rename to .zip before opening)</p>
<p>Beans binding (JSR 295) is about keeping two properties in sync. To take a Simple example, let say that you have a simple text field (the view) in a Swing form and that you want it to be kept in sync with a POJO (the data model).</p>
<p>In a small first part I show how this can be done the standard way and in a second part how we can enhanced it we some simple AOP.</p>
<p><strong>Part 1 : the standard way</strong></p>
<p>Here the simple user form that we will create and bind with our data model :</p>
<p><a href="http://yakafokon.wordpress.com/files/2008/12/beansbindingjrs295.png"><img class="alignnone size-full wp-image-25" title="beansbindingjrs295" src="http://yakafokon.wordpress.com/files/2008/12/beansbindingjrs295.png" alt="beansbindingjrs295" width="446" height="215" /></a></p>
<p>And here the PersonVO.java POJO to be used as data model :</p>
<pre class="brush: java;">

public class PersonVO {

  private String name;
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}
</pre>
<pre class="brush: java;">
public class PersonVOBindingEnabled extends PersonVO {
  protected PropertyChangeSupport props = new PropertyChangeSupport(this);
  public void addPropertyChangeListener( PropertyChangeListener l) {
    System.out.println(&quot;addPropertyChangeListener&quot;);
    props.addPropertyChangeListener(l);
  }

  public void removePropertyChangeListener( PropertyChangeListener l) {
    System.out.println(&quot;removePropertyChangeListener&quot;);
    props.removePropertyChangeListener(l);
  }

  public void setName(String newName) {
    String oldValue = getName();
    super.setName();
    props.firePropertyChange(&quot;name&quot;, oldName, newName);
  }
}
</pre>
<p>To bind the name attribute with the JTextField we use the Beans binding API :</p>
<pre class="brush: java;">
JTextField nameTextField =…

PersonVO aPersonVO = new PersonVO();

aPersonVO.setName(“Brian”);

…

BeanProperty nameProperty = BeanProperty.create(&quot;name&quot;);

Binding b = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, aPersonVO, nameProperty, nameTextField, BeanProperty.create(&quot;text&quot;));
</pre>
<p>And that&#8217;s it !</p>
<p>If you change the name attribute on the aPersonVO instance it will be sync in the JTextField and vice versa.</p>
<p>Yes but …</p>
<p>Having to extend the PersonVO so that it gets the PropertyChangeSupport is really annoying so it could be great if we could find a way to avoid it.</p>
<p><strong>Part 2 : Using AOP</strong></p>
<p>I have used AspectJ to automatically find my VO objects and add them all the necessary stuff for us :</p>
<pre class="brush: java;">
package beansbindingtest.aspects;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import org.apache.commons.beanutils.PropertyUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;

public @Aspect class PropertyChangeListenerAspect {
  public interface ChangeListener {

  public void addPropertyChangeListener( PropertyChangeListener l);
  public void removePropertyChangeListener( PropertyChangeListener l);
  public String getPropertyName(String setterMethodName);
  public PropertyChangeSupport getPropertyChangeSupport();
}

public static class ChangeListenerImpl implements ChangeListener {

  protected PropertyChangeSupport props = new PropertyChangeSupport(this);

  public void addPropertyChangeListener( PropertyChangeListener l) {
    System.out.println(&quot;addPropertyChangeListener&quot;);
    props.addPropertyChangeListener(l);
  }

  public void removePropertyChangeListener( PropertyChangeListener l) {
    System.out.println(&quot;removePropertyChangeListener&quot;);
    props.removePropertyChangeListener(l);
  }

  public String getPropertyName(String setterMethodName) {
    setterMethodName = setterMethodName.substring(3);
    String firstLetter = setterMethodName.substring(0, 1);
    setterMethodName = firstLetter.toLowerCase() + setterMethodName.substring(1);
    return setterMethodName;
  }

  public PropertyChangeSupport getPropertyChangeSupport() {
    return props;
  }
}

  @DeclareParents(value=&quot;beansbindingtest.datamodel.*&quot;,defaultImpl=ChangeListenerImpl.class)
  private ChangeListener implInterface;

  @Around(&quot;execution(void *..*VO.set*(..))&quot;)
  public void interceptSetterAndFirePropertyChange(ProceedingJoinPoint pjp) throws Throwable {
    System.out.println(&quot;before &quot; + pjp.getSignature().getName());
    String setterMethodName = pjp.getSignature().getName().substring(3);
    String firstLetter = setterMethodName.substring(0, 1);
    String propertyName = firstLetter.toLowerCase() + setterMethodName.substring(1);
    Object oldValue = null;
    try {
      oldValue = PropertyUtils.getProperty(pjp.getTarget(), propertyName);
    } catch (Exception e) {
      e.printStackTrace();
    }
    Object newValue = pjp.getArgs()[0];

    pjp.proceed();

    System.out.println(&quot;Firing event : &quot; + propertyName + &quot;; oldValue = &quot; + oldValue + &quot;; newValue = &quot; + newValue);
    PropertyChangeEvent pe = new PropertyChangeEvent(pjp.getTarget(), propertyName, oldValue, newValue);
    ((ChangeListener)pjp.getTarget()).getPropertyChangeSupport().firePropertyChange(pe);
    System.out.println(&quot;after &quot; + pjp.getSignature().getName());
  }

}
</pre>
<p>I have used the following jars :</p>
<ul>
<li>aspectjrt-1.5.4.jar</li>
<li>aspectjweaver-1.5.4.jar</li>
<li>commons-beanutils-1.8.0.jar</li>
<li>commons-logging-1.1.1.jar</li>
</ul>
<p>aop.xml has to be copied in the META-INF directory of your source.</p>
<p>And you need to add these args to the JVM when starting the application :</p>
<pre>-javaagent:[set your path here]/aspectjweaver-1.5.4.jar</pre>
<p>What is your opinion about using AOP for bean binding ?</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[AOP na prática: implementando um aspecto de auditoria]]></title>
<link>http://michelzanini.wordpress.com/2008/09/22/aop-na-pratica/</link>
<pubDate>Mon, 22 Sep 2008 01:42:02 +0000</pubDate>
<dc:creator>michelzanini</dc:creator>
<guid>http://michelzanini.wordpress.com/2008/09/22/aop-na-pratica/</guid>
<description><![CDATA[No último artigo apresentei os conceitos básicos da Programação Orientada a Aspectos. Nesse artigo p]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>No último artigo apresentei os conceitos básicos da Programação Orientada a Aspectos. Nesse artigo pretendo mostrar um exemplo prático de um problema muito comum em aplicações “enterprise”, a auditoria.</p>
<p>A auditoria é o processo de registrar todas as mudanças feitas pelos usuários para que se possa provar as ações tomadas por eles. Dessa forma é possível provar que o sistema não estava errado. Por exemplo, os dados sumiram porque alguém os excluiu.</p>
<p>Auditoria é uma responsabilidade “cross-cutting”, ou seja, se for programada de maneira tradicional estará espalhada por todo o sistema. Entretanto, é possível implementar tal funcionalidade utilizando técnicas de AOP, como veremos a seguir.</p>
<p>Dando continuidade ao artigo anterior, os exemplos estarão utilizando Spring e @AspectJ.</p>
<h2>Exemplo Inicial</h2>
<p>Começamos definindo uma interface geral para que nossos objetos de acesso ao banco de dados possam implementar, seguindo o padrão de projeto “Data Access Object”.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/entitydao1.png" alt="" /></p>
<p>Utilizamos o recurso de tipos genéricos para que nossas implementações possam inserir qualquer tipo de objeto do domínio. </p>
<p>Para não complicar o exemplo a implementação da interface apenas imprimirá no console para sabermos que o método foi executado, porém imagine que poderíamos estar executando código JDBC ou Hibernate/JPA em seu lugar. </p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/consoleclientedao.png" alt="" /></p>
<p>Agora implementaremos a primeira versão do nosso aspecto de auditoria, que simplesmente irá interceptar as execuções dos métodos inserir, atualizar e remover, imprimindo no console uma mensagem de aviso.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/aspectodeauditoria1.png" alt="" /></p>
<p>Note o uso do advice <strong>@AfterReturing</strong> para que o aspecto seja aplicado após uma execução com sucesso do método alvo. No pointcut interceptamos execuções de métodos de objetos que implementam a interface <strong>EntityDao</strong>, como a classe <strong>ConsoleClienteDao </strong> que criamos acima.</p>
<p>Para completar o exemplo mostramos o <strong>applicationContext.xml</strong> e o método Main para teste da aplicação.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/main.png" alt="" /></p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/appcontext.png" alt="" /></p>
<p>A execução do método main irá imprimir o seguinte no console:</p>
<p><code>executou inserirCliente<br />
depoisDeInserir<br />
executou atualizarCliente<br />
depoisDeAtualizar<br />
executou removerCliente<br />
depoisDeRemover</code></p>
<p>Agora, de posse de um exemplo muito simples, iremos melhora-lo para contemplar funcionalidades mais reais.</p>
<h2>Auditando dados da entidade</h2>
<p>Vamos criar uma superclasse abstrata para nossas entidades, dessa forma podemos utilizar o aspecto para obter informações de auditoria.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/entity.png" alt="" /></p>
<p>A classe <strong>Entity</strong> possui um id e um método a ser implementado pelas subclasses para obter uma String descritiva para auditoria. Em um sistema real poderíamos criar um POJO para substituir a String, de forma que ele poderia conter informações mais avançadas. Agora nossa classe <strong>Cliente</strong> passa a estender a classe <strong>Entity</strong>.</p>
<p>Para ter acesso aos dados da entidade que está sendo auditada podemos utilizar a expressão ‘args’ da sintaxe de pointcut do @AspectJ. Veja o exemplo abaixo.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/dadosaudit.png" alt="" /></p>
<p>Agora restringimos o método inserir a ter apenas um parâmetro, e do tipo <strong>Entity</strong>. Na expressão <strong>args(entity)</strong> definimos o nome do parâmetro, essa string deve coincidir com a variável declarada como parâmetro do método <strong>depoisDeInserir</strong>. Sendo assim, o objeto disponibilizado para o método é o mesmo passado como parâmetro do <strong>ConsoleClienteDao</strong>,  e podemos utiliza-lo para auditoria.</p>
<p>Outra forma possível de auditar os dados da entidade seria utilizar a API de reflection para obter todas as suas propriedades, e então, montar uma descrição com a concatenação de seus valores.</p>
<h2>Auditando mudanças nas atualizações</h2>
<p>Em geral na auditoria, quando um objeto sofre um update, é desejável auditar as mudanças realizadas. Mas como podemos saber as mudanças feitas antes do update ocorrer? Podemos fazer um select antes e comparar os dados antes e depois da atualização.</p>
<p>Isso pode ser facilmente contemplado utilizando um advice <strong>@Around</strong>. Antes da execução do método <strong>atualizar</strong> fazemos um select e obtemos o objeto em seu estado atual, depois da atualização com sucesso, comparamos os dois objetos utilizando reflection (ou alguma interface), e então, auditamos o resultado.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/antes.png" alt="" /></p>
<p>Para manter os exemplos simples apenas comparamos os objetos com o método equals. Alem disso, nenhum tratamento foi feito para evitar NullPointerExceptions. Note que o método <strong>proceed</strong> executa o método alvo e em caso de exceções, será propagado para fora do aspecto, sem chegar a executar as ultimas linhas do método.</p>
<h2>Filtrando quais classes participarão da auditoria</h2>
<p>Imagine que para uma determinada aplicação é necessário fazer auditoria em apenas alguns DAO’s. Mas queremos que nosso aspecto continue consistente, ou seja, não sofra alterações constantemente. Para tal, uma idéia interessante é a utilização de anotações para marcar o pointcut do aspecto. Veja o exemplo abaixo.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/anotacao.png" alt="" /></p>
<p>Veja a expressão <strong>@target(exemplo.AptoParaAuditoria)</strong>. Essa expressão significa que para o pointcut ser atingido a classe alvo tem que estar anotada com a anotação <strong>@AptoParaAuditoria</strong>. Dessa forma, a auditoria só ocorre quando desejado, nos DAO’s marcados com essa anotação. Também é possível criar filtros a nível de método utilizando a expressão <strong>@annotation(exemplo.AptoParaAuditoria)</strong>.</p>
<p>Para melhorar o exemplo ainda é possível criar um atributo na anotação, uma enumeração, para informar em quais operações serão auditadas: inserir, atualizar, remover ou todas.</p>
<h2>Obtendo informações do usuário corrente</h2>
<p>Em um sistema de auditoria não basta saber o que foi feito e onde, também é necessário saber quem fez a alteração. Ou seja, é necessário obter dados do usuário logado. Em uma aplicação web isso se torna difícil, pois é impossível obter um objeto <strong>HttpRequest</strong> ou <strong>HttpSession</strong> de dentro do aspecto de auditoria.</p>
<p>Para essas situações existe uma técnica muito utilizada na AOP, associar recursos a Thread corrente. Assim é no Spring na área de controle de transações. Quando uma transação é aberta pelo aspecto de transação é associado a Thread corrente um <strong>java.sql.DataSource</strong> ou, no caso do Hibernate, uma <strong>org.hibernate.classic.Session</strong>. Dessa forma, ao longo da execução da Thread, de todos os lugares, é possível obter o mesmo recurso de conexão (na mesma transação), para executar o acesso ao banco de dados.</p>
<p>Essa solução pode ser aplicada nesse caso. Podemos implementar um filtro http (<strong>javax.servlet.Filer</strong>) que associa o request a Thread corrente. Dessa forma, de dentro do aspecto, podemos acessar o <strong>HttpRequest</strong>. Na verdade, o Spring já possui tal filtro implementando dentro do <strong>spring-web.jar</strong>, basta declararmos no <strong>web.xml</strong>.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/filtro.png" alt="" /></p>
<p>Agora de dentro do aspecto de auditoria é possível acessar o request e a session desta forma:</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/09/request.png" alt="" /></p>
<h2>Conclusão</h2>
<p>A Programação Orientada a Aspectos é muito útil para funcionalidades como auditoria provendo sempre uma solução transparente. O Spring já nos traz vários recursos implementados que se utilizados de forma correta podem poupar muitos esforços. O @AspectJ está muito bem integrado com o Spring Framework, e o casamento das duas tecnologias pode trazer grandes benefícios.</p>
<p>Abraços,<br />
Michel Zanini.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[New episode from SE-Radio.net: Basic Introduction to AOP (Aspect Oriented Programming)]]></title>
<link>http://mauriziostorani.wordpress.com/2008/09/18/new-episode-from-se-radionet-basic-introduction-to-aop-aspect-oriented-programming/</link>
<pubDate>Thu, 18 Sep 2008 11:58:18 +0000</pubDate>
<dc:creator>Maurizio Storani</dc:creator>
<guid>http://mauriziostorani.wordpress.com/2008/09/18/new-episode-from-se-radionet-basic-introduction-to-aop-aspect-oriented-programming/</guid>
<description><![CDATA[I want to post the SE-Radio.net Episode 106 about AOP programming and two nice presentations from sl]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><img class="alignleft" style="margin:3px 8px;" src="http://www.oopsla.org/oopsla2007/podcasts/se-radio-logo-oopsla.gif" alt="se-radio.net logo" width="232" height="251" />I want to post the SE-Radio.net <a href="http://www.se-radio.net/podcast/2008-08/episode-106-introduction-aop" target="_blank">Episode 106</a> about AOP programming and two nice presentations from <a href="slideshare.net" target="_blank">slideshare.net</a>.</p>
<p>AOP  importance is increasing in the past few years, <a href="www.springframework.org" target="_blank">Spring </a>are using it in a widely manner and also OSGi have announced few month ago your Aspect bundle for weaving at run-time (<a href="www.eclipse.org/equinox/incubator/aspects/" target="_blank">Equinox Aspect</a>). So AOP have a grait impact on present programming and I think that it will have also with future programming.</p>
<p>This episode is a systematic introduction to Aspect Oriented Programming (in contrast to the <a href="http://se-radio.net/podcast/2006-04/episode-11-interview-gregor-kiczales" target="_blank">interview with Gregor Kiczales</a>). We discuss the fundamentals of AOP, define many of the relevant terms and also look at how and where AOP is used in practice, as well as at some current research trends.</p>
<h3 class="field-label">Host(s)</h3>
<div class="field-items">
<div class="field-item">Markus</div>
</div>
<h3 class="field-label">Guest(s)</h3>
<p><a href="http://www.kircher-schwanninger.de/christa/">Christa Schwanninger</a>,<br />
<a href="http://www.sea.uni-linz.ac.at/index.php?title=Dipl._Ing._%28FH%29_Dr._Iris_Groher">Iris Groher</a></p>
<p><span style='text-align:left;display:block;'><p><object type='application/x-shockwave-flash' data='http://wordpress.com/wp-content/plugins/audio-player/player.swf' width='290' height='24' id='audioplayer1'><param name='movie' value='http://wordpress.com/wp-content/plugins/audio-player/player.swf' /><param name='FlashVars' value='&amp;bg=0xf8f8f8&amp;leftbg=0xeeeeee&amp;lefticon=0x666666&amp;rightbg=0xcccccc&amp;rightbghover=0x999999&amp;righticon=0x666666&amp;righticonhover=0xffffff&amp;text=0x666666&amp;slider=0x666666&amp;track=0xFFFFFF&amp;border=0x666666&amp;loader=0x9FFFB8&amp;soundFile=http%3A%2F%2Fmedia.libsyn.com%2Fmedia%2Fseradio%2Fseradio-episode106-introductionToAOP.mp3' /><param name='quality' value='high' /><param name='menu' value='false' /><param name='bgcolor' value='#FFFFFF' /></object></p></span></p>
<p>Follow I have posted from <a href="http://www.slideshare.net" target="_blank">slideshare.net</a> two good presentations to AOP.</p>
<h3>Aspect-Oriented Programming and Depedency Injection</h3>
<p><!-- SlideShare error: doc is missing or has illegal characters /[^-_a-zA-Z0-9]/ --></p>
<h3>Aspect Oriented Software Development</h3>
<p><!-- SlideShare error: doc is missing or has illegal characters /[^-_a-zA-Z0-9]/ --></p>
<p>Have fun!</p>
<p style="text-align:right;"><em>[se-radio.net]</em></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[AOP utilizando @AspectJ e Spring]]></title>
<link>http://michelzanini.wordpress.com/2008/08/28/aop-utilizando-aspectj-e-spring/</link>
<pubDate>Thu, 28 Aug 2008 02:53:14 +0000</pubDate>
<dc:creator>michelzanini</dc:creator>
<guid>http://michelzanini.wordpress.com/2008/08/28/aop-utilizando-aspectj-e-spring/</guid>
<description><![CDATA[Nesse artigo vou explicar os conceitos básicos de AOP e mostrar um exemplo inicial de como isso é fe]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Nesse artigo vou explicar os conceitos básicos de AOP e mostrar um exemplo inicial de como isso é feito utilizando @AspectJ 5 e Spring.</p>
<p>A Programação Orientada a Aspectos (AOP) complementa a programação orientada a objetos, provendo uma nova forma de pensar sobre a arquitetura da aplicação.</p>
<p>Na programação orientada a objetos encapsulamos as responsabilidades em classes. Já na AOP, as responsabilidades são encapsuladas em um aspecto. Um aspecto permite a modularização de interesses que geralmente aparecem espalhados por várias classes do sistema (denominados de interesses transversais – <em>crosscutting concerns</em>), como o gerenciamento de transações, por exemplo.</p>
<p>Veja a imagem abaixo. Se compreendermos as linhas horizontais como classes, veremos que os interesses de segurança, transação, etc. são transversais, ou seja, repetidos entre várias classes. A AOP contribui no sentido de retirar essas funcionalidades das classes e encapsula-las em aspectos, sem alterar o comportamento do sistema.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/08/aop-cutting.png" alt="" /></p>
<h2>Conceitos</h2>
<p><strong>Aspect</strong>: é a unidade modular (funcionalidade) que encapsula interesses que atravessam vários objetos dentro do sistema.</p>
<p><strong>Join Point</strong>: é um ponto durante a execução do programa que poderá ser afetado pelo aspecto. Um join point pode ser, por exemplo, a execução de um método do programa.</p>
<p><strong>Point Cut</strong>: é uma expressão escrita em uma linguagem específica para a finalidade de selecionar join points (pontos de execução).</p>
<p><strong>Advice</strong>: quando um join point é atingido, e selecionado pelo point cut, uma ação será executada. Essa ação é determinada advice.</p>
<p><strong>Objeto Alvo</strong>: é o objeto que está sendo interceptado por um ou mais aspectos.</p>
<p><strong>Proxy AOP</strong>: é o objeto criado pelo framework AOP para implementar a ligação entre o aspecto e o objeto alvo.</p>
<p>Veja na imagem abaixo. Durante a execução do programa, vários join points serão “atingidos”. No suporte a @AspectJ do Spring Framework (veremos exemplos a seguir) um join point é sempre a execução de um método. Dessa forma, imagine que cada um dos 6 join points abaixo representem 6 diferentes métodos. Um point cut é uma expressão, em linguagem específica, que seleciona quais dos 6 métodos (join points) serão afetados pelo aspecto. Nesse caso, imagine que os 3 joint points verdes foram atingidos pela expressão pointcut. O advice é a ação que irá executar quando eles foram atingidos, nesse caso, o advice será executado 3 vezes.</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/08/point-cut.png" alt="" /></p>
<h2>Tipos de Advice</h2>
<p>No AspectJ existem 5 tipos diferentes de advice:</p>
<ul>
<li><strong>Before</strong>: ação do advice executa antes do join point.</li>
</ul>
<ul>
<li><strong>After returning</strong>: ação do advice executa depois do joint ser executado com sucesso, ou seja, sem lançar exceção.</li>
</ul>
<ul>
<li><strong>After throwing</strong>: ação do advice executa depois do joint ser executado com erro, ou seja, somente quando ele lançar uma exceção.</li>
</ul>
<ul>
<li><strong>After (finally)</strong>: ação do advice executa depois do joint ser executado independente de ter causado ou não exceção.</li>
</ul>
<ul>
<li><strong>Around</strong>: advice que envolve a execução de um joint point. Com ele é possível codificar ações antes e depois do join point. Inclusive é possível alterar valores passados como parâmetro, como retorno, ou nem mesmo chamar o método do objeto alvo.</li>
</ul>
<h2>Exemplo concreto utilizando o suporte a @AspectJ com Spring</h2>
<p>A partir da versão 2.0 do Spring Framework é suportado o uso do @AspectJ 5 de forma integrada ao seu container. Ainda é possível declarar aspectos por XML, como nas versões anteriores, porém agora é possível declarar aspectos com uso de anotações.</p>
<p>Para implementar um aspecto é necessário três coisas:</p>
<ul>
<li>Colocar os jars ‘aspectjrt.jar’ e ‘aspecjtweaver.jar’ no classpath, juntamente com os jars tradicionais do Spring.</li>
</ul>
<ul>
<li>Declarar no applicationContext.xml o uso de aspectos com declaração por anotações, dessa forma:&#60;aop:aspectj-autoproxy /&#62;.</li>
</ul>
<ul>
<li>Criar uma classe anotada com @Aspect para definir o aspecto. Utilizar uma anotação de advice (before, after ou around) e definir uma expressão point cut para selecionar quais joint points o aspecto afetará.</li>
</ul>
<p>Veja um exemplo abaixo:</p>
<p><img src="http://michelzanini.wordpress.com/files/2008/08/app-context-conceitos.png" alt="" /></p>
<p><img src="http://michelzanini.wordpress.com/files/2008/08/aspecto-exemplo.png" alt="" /></p>
<p>Repare que a expressão <strong>“execution(* xyz.abc.ClienteDao.*(..))”</strong> é o point cut e a anotação @Before é o advice. A linguagem do point cut é específica do @AspectJ e sua documentação pode ser encontrada no site da biblioteca. Explicando a expressão em detalhes:</p>
<ul>
<li><strong>execution</strong>: Qualquer execução de método.</li>
</ul>
<ul>
<li><strong>Primeiro asterisco da expressão</strong>: que tenha qualquer visibilidade e retorne qualquer tipo de parâmetro.</li>
</ul>
<ul>
<li><strong>xyz.abc</strong>: pacote que estão a(s) classe(s) que o point cut afetará.</li>
</ul>
<ul>
<li><strong>ClienteDao</strong>: a classe afetada pelo point cut.</li>
</ul>
<ul>
<li><strong>Segundo asterisco da expressão</strong>: qualquer método da classe ClienteDao.</li>
</ul>
<ul>
<li><strong> (..)</strong>: O método pode ter qualquer quantidade de parâmetros, de qualquer tipo.</li>
</ul>
<p>Dessa forma podemos dizer que o método ‘realizarAcao’ será executado antes que qualquer método da classe ClienteDao executar.</p>
<p>É importante lembrar que o suporte à @AspectJ do Spring, como mostrado no exemplo, só selecionará join points que forem beans gerenciados pelo Spring. Ou seja, no exemplo acima o &#8216;ClienteDao&#8217; tem que ser um bean no application context do Spring.</p>
<p>No próximo artigo veremos como implementar uma solução simples de auditoria utilizando AOP com Spring e @AspectJ.</p>
<p>Abraços,<br />
Michel Zanini.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Equinox Aspect: Example from Martin Lippert]]></title>
<link>http://mauriziostorani.wordpress.com/2008/07/19/equinox-aspect-example-from-martin-lippert/</link>
<pubDate>Sat, 19 Jul 2008 10:45:50 +0000</pubDate>
<dc:creator>Maurizio Storani</dc:creator>
<guid>http://mauriziostorani.wordpress.com/2008/07/19/equinox-aspect-example-from-martin-lippert/</guid>
<description><![CDATA[Martin Lippert is a senior consultant and coach at akquinet it-agile GmbH. His main work and researc]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://mauriziostorani.wordpress.com/wp-admin/www.eclipse.org/equinox/incubator/aspects"><img class="alignleft" style="margin:4px 8px;" src="http://mauriziostorani.files.wordpress.com/2008/06/equinox-aspects.jpg?w=265&#038;h=75" alt="Equinox Aspects image" width="265" height="75" /></a><span>Martin Lippert is a senior consultant and coach at akquinet it-agile GmbH. His main work and research focuses on Agile Software Development, Refactoring, Eclipse-Technology, OSGi, Spring and Aspect-Oriented Programming.</span></p>
<div>Martin posts, in your blog, a<a href="http://martinlippert.blogspot.com/2008/07/code-examples-from-aspect-weaving-for.html" target="_blank"> Code Examples from &#8220;Aspect Weaving for OSGi&#8221; Talk.</a></div>
<div>The code example is divided in:</div>
<ul>
<li><a href="http://martinlippert.blogspot.com/2008/07/code-examples-from-aspect-weaving-for.html" target="_blank"><span style="font-weight:bold;">Eclipse Monitor Demo</span></a></li>
<li><a href="http://martinlippert.blogspot.com/2008/07/code-examples-from-aspect-weaving-for.html" target="_blank"><span style="font-weight:bold;">Dependency Injection with Spring Dynamic Modules and Equinox Aspects</span></a></li>
</ul>
<h3><span style="font-weight:bold;">Eclipse Monitor Demo</span></h3>
<p>This demo features the relatively old Eclipse Monitor application that Chris Laffra wrote a while ago. It visualizes plugin activities within your Eclipse application and you can analyze what is going on. This monitor uses <a href="http://www.eclipse.org/equinox/incubator/aspects/" target="_blank">Equinox Aspects</a> to weave an aspect into all your bundles at load-time to gather the information of what is going on at runtime. It uses AspectJ advises for all methods and object creations. While this is a pretty heavy use of load-time weaving (you will notice a huge performance impact at first startup) it demos nicely the caching feature of Equinox Aspects. The second startup of your monitored app will perform very similar to a startup without any aspect weaving. (<a href="http://martinlippert.blogspot.com/search/label/Planet-Eclipse" target="_blank">more</a>)</p>
<h3><span style="font-weight:bold;">Dependency Injection with Spring Dynamic Modules and Equinox Aspects</span></h3>
<p>Spring provides this nice mechanism to inject dependencies in domain objects via the @Configurable annotation (see more here: <a href="http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-atconfigurable" target="_blank">http://static.springframework.org/spring/docs/2.5.x/reference/aop.html#aop-atconfigurable</a>).<br />
The main difference to general spring beans is that the creation of those domain objects is not done by the application context of Spring. Therefore Spring uses an aspect to call the application context after object creation to inject all necessary dependencies. In plain old Spring applications this aspect is woven into the system using load-time weaving.<br />
Wouldn&#8217;t that be a nice mechanism to inject dependencies into Eclipse extensions (like views or editors)? Just annotate your extension with @Configurable and define the dependencies to be injected inside the application context of your bundle (using the Spring Dynamic Modules stuff)? (<a href="http://martinlippert.blogspot.com/search/label/Planet-Eclipse" target="_blank">more</a>)</p>
<p style="text-align:right;"><em>[http://martinlippert.blogspot.com]</em></p>
<p><!-- AddThis Button BEGIN --><br />
<a title="Bookmark and Share" href="http://www.addthis.com/bookmark.php?wt=nw&#38;pub=flamel&#38;url=http://mauriziostorani.wordpress.com/2008/07/19/equinox-aspect-example-from-martin-lippert&#38;title=Equinox Aspect: Example from Martin Lippert" target="_blank"><img src="http://s9.addthis.com/button1-bm.gif" border="0" alt="Bookmark and Share" width="125" height="16" /></a><br />
<!-- AddThis Button END --></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Problems with IntelliJ AspectJ plugin - SOLVED]]></title>
<link>http://stigl.wordpress.com/2008/07/12/problems-with-intellij-aspectj-plugin/</link>
<pubDate>Sat, 12 Jul 2008 19:34:22 +0000</pubDate>
<dc:creator>stigl</dc:creator>
<guid>http://stigl.wordpress.com/2008/07/12/problems-with-intellij-aspectj-plugin/</guid>
<description><![CDATA[I&#8217;ve looked into Oval Java Validation Framework, which seems quite nifty. The problem with it ]]></description>
<content:encoded><![CDATA[I&#8217;ve looked into Oval Java Validation Framework, which seems quite nifty. The problem with it ]]></content:encoded>
</item>
<item>
<title><![CDATA[OSGi and AspectJ into Equinox Aspects]]></title>
<link>http://mauriziostorani.wordpress.com/2008/06/28/osgi-and-aspectj-into-equinox-aspects/</link>
<pubDate>Sat, 28 Jun 2008 17:49:46 +0000</pubDate>
<dc:creator>Maurizio Storani</dc:creator>
<guid>http://mauriziostorani.wordpress.com/2008/06/28/osgi-and-aspectj-into-equinox-aspects/</guid>
<description><![CDATA[In software engineering, the programming paradigms of aspect-oriented programming (AOP), and aspect-]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p><a href="http://mauriziostorani.files.wordpress.com/2008/06/equinox-aspects.jpg"><img class="alignleft size-medium wp-image-124" style="border:2px solid #E58712;float:left;margin:3px;padding:3px;" src="http://mauriziostorani.wordpress.com/files/2008/06/equinox-aspects.jpg?w=265" alt="equinox-aspects-" width="265" height="75" /></a>In software engineering, the programming paradigms of <strong>aspect-oriented programming</strong> (<strong>AOP</strong>), and aspect-oriented software development (<strong>AOSD</strong>) attempt to aid programmers in the separation of concerns, specifically cross-cutting concerns, as an advance in <span class="mw-redirect">modularization</span>. AOP does so using primarily language changes, while AOSD uses a combination of language, environment, and method.</p>
<p>Separation of concerns entails breaking down a program into distinct parts that overlap in functionality as little as possible. All programming methodologies—including procedural programming and object-oriented programming—support some separation and encapsulation of <em>concerns</em> (or any area of interest or focus) into single entities. For example, procedures, packages, classes, and methods all help programmers encapsulate concerns into single entities. But some concerns defy these forms of encapsulation. Software engineers call these <em>crosscutting concerns</em>, because they &#8220;cut&#8221; across multiple modules in a program.</p>
<p>Any AOP language has some crosscutting expressions that encapsulate the concern in one place. The difference between AOP languages lies in the power, safety, and usability of the constructs provided. For example, interceptors that specify the methods to intercept express a limited form of crosscutting, without much support for type-safety or debugging. AspectJ has a number of such expressions and encapsulates them in a special class, an aspect. For example, an aspect can alter the behavior of the base code (the non-aspect part of a program) by applying <span class="mw-redirect">advice</span> (additional behavior) at various join points (points in a program) specified in a quantification or query called a pointcut (that detects whether a given join point matches). An aspect can also make binary-compatible structural changes to other classes, like adding members or parents.</p>
<p>Many AOP languages support method executions and field references as join points. In them the developer can write a pointcut to match, for example, all field-set operations on specific fields, and code to run when the field is actually set. Some also support things like defining a method in an aspect on another class. AOP languages can be compared based on the join points they expose, the language they use to specify the join points, the operations permitted at the join points, and the structural enhancements that can be expressed.</p>
<p><strong>AspectJ</strong> is an aspect-oriented extension created at PARC for the Java programming language. It is available in Eclipse Foundation open-source projects, both stand-alone and integrated into <span class="mw-redirect">Eclipse</span>. AspectJ has become the widely-used de-facto standard for AOP by emphasizing simplicity and usability for end users. It uses Java-like syntax and has included IDE integrations for displaying crosscutting structure since its initial public release in 2001.</p>
<p><strong>Equinox Aspects</strong>: the goal is to allow developers to use the Equinox together with   AspectJ by combining the benefits of both worlds. Using a load-time weaving extension   you are able to add AspectJ aspects to your bundle-based system just by putting them   into general OSGi bundles. It does not matter if the pointcuts you defined inside the   aspects contain join points that are defined by classes within the same bundle or any   other bundle in your installation. The load-time weaving extension will take care that   your aspects are woven with the appropriate classes at load-time.</p>
<h3 class="post-title entry-title"><a href="http://martinlippert.blogspot.com/2008/05/finally-aspects-become-dynamic.html" target="_blank">Finally aspects become dynamic</a> (Martin Lippert)</h3>
<p>I recently committed some changes to the <a href="http://www.eclipse.org/equinox/incubator/aspects/" target="_blank">Equinox Aspects</a> project which allows the Equinox Aspects runtime to handle dynamically uninstalled aspects correctly with regards to the woven bundles in the system. Having this it was only a small step to also deal with dynamic updates to aspect bundles as well as woven bundles at runtime. And now, finally, we are there: real dynamics for aspects. You can install, update and uninstall aspects at runtime as you like and the Equinox Aspects runtime takes care that everything will be woven and re-woven correctly. This is really really cool and a huge step towards real OSGi-enabled AOP, I think.</p>
<p>But what happens if aspect bundles are installed, updated or uninstalled at runtime? All other bundles that need to be woven, that need to be re-woven or that need to be un-woven from the aspect are updated automatically by the aspect runtime using the OSGi mechanisms. This means also that your system should be able to deal with OSGi dynamics and bundles coming and going (which is not a trivial thing to do). So be a good citizen of the OSGi world and your bundles will behave well when aspects are coming and going at runtime&#8230; <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3 class="post-title entry-title"><a href="http://martinlippert.blogspot.com/2008/07/code-examples-from-aspect-weaving-for.html" target="_blank">Code Examples from &#8220;Aspect Weaving for OSGi&#8221; Talk</a></h3>
<h3 class="post-title entry-title"><a href="http://martinlippert.blogspot.com/2008/07/blog-post.html" target="_blank">Slides from &#8220;Aspect Weaving for OSGi&#8221; Talk</a></h3>
<h4>References:</h4>
<p>[http://martinlippert.blogspot.com]</p>
<p>[wikipedia.org]</p>
<p>[http://www.eclipse.org/equinox/incubator/aspects/]</p>
<p><!-- AddThis Button BEGIN --><br />
<a title="Bookmark and Share" href="http://www.addthis.com/bookmark.php?wt=nw&#38;pub=flamel&#38;url=http://mauriziostorani.wordpress.com/2008/06/28/osgi-and-aspectj-into-equinox-aspects&#38;title=OSGi and AspectJ into Equinox Aspects" target="_blank"><img src="http://s9.addthis.com/button1-bm.gif" border="0" alt="Bookmark and Share" width="125" height="16" /></a><br />
<!-- AddThis Button END --></p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Mencicipi JUnit dan AspectJ]]></title>
<link>http://budsus.wordpress.com/2008/04/24/mencicipi-junit-dan-aspectj/</link>
<pubDate>Thu, 24 Apr 2008 15:23:19 +0000</pubDate>
<dc:creator>Budi Susanto</dc:creator>
<guid>http://budsus.wordpress.com/2008/04/24/mencicipi-junit-dan-aspectj/</guid>
<description><![CDATA[Kebetulan saja saya mengajar Metodologi RPL di sekolahan saya, dan salah dua materinya adalah tentan]]></description>
<content:encoded><![CDATA[Kebetulan saja saya mengajar Metodologi RPL di sekolahan saya, dan salah dua materinya adalah tentan]]></content:encoded>
</item>
<item>
<title><![CDATA[AspectJ для журналирования]]></title>
<link>http://schnorrer.wordpress.com/2008/04/06/aspectj-simple-example/</link>
<pubDate>Sun, 06 Apr 2008 15:42:30 +0000</pubDate>
<dc:creator>levi</dc:creator>
<guid>http://schnorrer.wordpress.com/2008/04/06/aspectj-simple-example/</guid>
<description><![CDATA[Задача: покрутить AOP на как можно более простом примере. Для этого возьмем: 1) Файл AspectTest.java]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Задача: покрутить AOP на как можно более простом примере.</p>
<p><strong>Для этого возьмем:</strong></p>
<p>1) Файл AspectTest.java с подопытным классом</p>
<pre class="brush: java;">
package ajtest;

class AspectTest {
    public void printKrivetko() {
        System.out.println(&quot;Я криветко <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> &quot;);
    }

    public void printMedved() {
        System.out.println(&quot;Я медвед 8]&quot;);
    }

    public static void main(String[] args) {
        AspectTest app = new AspectTest();
        app.printKrivetko();
        app.printMedved();
    }
}
</pre>
<p>2) Файл PrintLogging.aj с простым аспектом</p>
<pre class="brush: java;">
package ajtest;

// наш простой аспект
public aspect PrintLogging {

    // наш простой адвайс
    after() returning:
        call(void AspectTest.print*()) {
        System.out.println(&quot;^^^ вызыван какой-то метод print*&quot;);
    }
}
</pre>
<p>3) Файл build.xml с несложным проектом</p>
<pre class="brush: xml;">
&lt;project name=&quot;ajtest&quot; default=&quot;ajx&quot; basedir=&quot;.&quot;&gt;
    &lt;!-- определяем директории для исходников и скомпилированных классов --&gt;
&lt;property name=&quot;src&quot; location=&quot;src&quot;/&gt;
&lt;property name=&quot;build&quot; location=&quot;build&quot;/&gt;

    &lt;!-- определяем таск iajc --&gt;
    &lt;taskdef
        resource=&quot;org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties&quot;&gt;
        &lt;classpath&gt;
&lt;pathelement location=&quot;lib/aspectjtools.jar&quot;/&gt;
        &lt;/classpath&gt;
    &lt;/taskdef&gt;

    &lt;!-- цель для компиляции основных классов --&gt;
    &lt;target name=&quot;compile&quot;&gt;
        &lt;javac srcdir=&quot;${src}&quot; destdir=&quot;${build}&quot;/&gt;
    &lt;/target&gt;

    &lt;!-- цель для добавления AOP-функциональности --&gt;
    &lt;target name=&quot;ajx&quot; depends=&quot;compile&quot;&gt;
        &lt;iajc sourceroots=&quot;${src}&quot;
              destdir=&quot;${build}&quot;
              classpath=&quot;lib/aspectjrt.jar&quot;
        /&gt;
    &lt;/target&gt;
&lt;/project&gt;
</pre>
<p>4) Библиотеки aspectjrt.jar и aspectjtools.jar из последнего стабильного <a href="http://www.eclipse.org/aspectj/downloads.php">билда</a>.</p>
<p><strong>Все это разложим по директориям:</strong></p>
<pre>+ build
+ src
&#124;- + ajtest
   &#124;- AspectTest.java
   &#124;- PrintLogging.aj
+ lib
&#124;- aspectjrt.jar
&#124;- aspectjtools.jar
build.xml</pre>
<p><code> </code><br />
<strong>И соберем <a href="http://ant.apache.org/bindownload.cgi">ant</a>-ом:</strong><br />
<code>ant</code></p>
<p><strong>Запускаем</strong> (сообщения, создаваемые внутри аспекта, отправляются в стандартный вывод):<br />
<code>java -cp build;lib/aspectjrt.jar ajtest.AspectTest</code></p>
<p><strong>В консоли должно появиться следующее:</strong><br />
<code>Я криветко <img src='http://s.wordpress.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
^^^ вызыван какой-то метод print*<br />
Я медвед 8]<br />
^^^ вызыван какой-то метод print*</code></p>
<p>It&#8217;s working.</p>
</div>]]></content:encoded>
</item>
<item>
<title><![CDATA[Aspect Oriented Programming - real life examples]]></title>
<link>http://piotrga.wordpress.com/2008/04/01/aspect-oriented-programming-real-live-examples/</link>
<pubDate>Tue, 01 Apr 2008 14:55:17 +0000</pubDate>
<dc:creator>Piotr Gabryanczyk</dc:creator>
<guid>http://piotrga.wordpress.com/2008/04/01/aspect-oriented-programming-real-live-examples/</guid>
<description><![CDATA[Some time ago, on my previous blog, I wrote a short series of articles showing real live examples of]]></description>
<content:encoded><![CDATA[<div class='snap_preview'><p>Some time ago, on my <a href="http://www.jroller.com/piotrga/">previous blog</a>, I wrote a short series of articles showing real live examples of using AOP. It is time to group them together and share with you again:</p>
<ul>
<li>Introduction and caching example <a href="http://www.jroller.com/piotrga/entry/transparent_caching_with_aspectj">Transparent Caching with AspectJ</a></li>
<li><a href="http://www.jroller.com/piotrga/entry/tracing_history_of_bean_with">Tracing history of bean with AspectJ in 10 minutes</a></li>
<li><a href="http://www.jroller.com/piotrga/entry/retry_if_failed_with_aop">Retry if failed pattern with AspectJ in 10 minutes</a></li>
<li><a href="http://www.jroller.com/piotrga/entry/configurable_without_spring_in_10">@Configurable without Spring in 10 minutes</a></li>
</ul>
<p><strong>Enjoy!</strong></p>
</div>]]></content:encoded>
</item>

</channel>
</rss>
