Featured FREE Whitepapers

What's New Here?

enterprise-java-logo

State Does Not Belong In The Code

What is “state” in your web application? It’s the data that gets stored (regardless of the destination – memory, database, file-system). The application itself must not store any state in the code. This means your classes should only have fields with objects that are also stateless. In other words – you should not store anything in your services, DAOs or controllers during the program flow. This is a complete “must” for your service layer. Why? Your application needs to be scalable. This means it needs to be run in a cluster, and state is the hardest thing to distribute. If you minimize the places where state is stored, you minimize the complexity of clustering. But state should exist, and here is where it is fine to have it:the database – be it SQL, NoSQL or even a search engine, it’s the main thing that stores state. It is the thing that is supposed to support clustering, or a huge dedicated machine that handles requests from multiple other “code” servers. The code communicates with the database, but the code itself does not store anything for more than one client request; cache – caching is relatively easy to distribute (it’s basically key-value). There are many ready-to-use solutions like EhCache and memcached. So instead of computing a result, or getting it from the DB on each request, you can configure caching and store the result in memory. But again – code does not store anything – it just populates and queries the cache; HTTP session – in web components (controllers, managed beans, whatever you call it). It is very similar to caching, though it has a different purpose – to allow identifying subsequent actions by the same user (http itself is stateless). But as your code runs on multiple machines, the load-balancer may not always send subsequent requests to the same server. So the session should also be replicated across all servers. Fortunately, most containers have that option built-in, so you just add one configuration line. Alternatively you can instruct the load-balancer to use a “sticky session” (identify which server to send the request depending on the session cookie), but it moves some state management to the load-balancer as well. Regardless of the option you choose, do not put too much data in the session the file system – when you store files, you need them to be accessible to all machines. There are multiple options here, including SAN or using a cloud storage service like Amazon S3, which are accessible through an APIAll these are managed outside the code. Your code simply consumes them through an API (the Session API, the cache API, JDBC, S3/file system API). If the code contained any of that state (as instance-variables of your objects) the application would be hard to support (you’d have to manage state yourself) and will be less scalable. Of course, there are some rare cases, where you can’t go without storing state in the code. Document these and make sure they do not rely on working in a cluster. But what can go wrong if you store state in the objects that perform the business logic? You have two options then:synchronize access to fields – this will kill performance, because all users that make requests will have to wait in queue for the service to manage its fields; make new instance of your class for each HTTP request, and manage the instances somehow. Managing these instances is the hard part. People may be inclined to choose the session to do it, which means the session grows very large and gets harder to replicate (sharing a lot of data across multiple machines is slower, and session replication must be fast). Not to mention the unnecessarily increased memory footprint.Here’s a trivial example of what not to do. You should pass these kinds of values as method arguments, rather than storing them in the instance: class OrderService { double orderPrice;void processOrder(OrderDto order) { for (Entry entry : order.getEntries() { orderPrice += entry.getPrice(); } boolean discounts = hasDiscounts(order); } boolean hasDiscounts(OrderDto order) { return order.getEntries().length > 5 && orderPrice > 200; } }So, make all your code stateless – this will ensure at least some level of scalability. Reference: State Does Not Belong In The Code from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog....
spring-logo

Spring Thread Pool Services

Thread Pools are very important to execute synchronous & asynchronous processes. This article shows how to develop and monitor Thread Pool Services by using Spring. Creating Thread Pool has been explained via two alternative methods. Used Technologies : JDK 1.6.0_21 Spring 3.0.5 Maven 3.0.2 STEP 1 : CREATE MAVEN PROJECT A maven project is created as below. (It can be created by using Maven or IDE Plug-in).STEP 2 : LIBRARIES Spring dependencies are added to Maven’ s pom.xml. <!-- Spring 3 dependencies --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency>For creating runnable-jar, below plugin can be used. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>1.3.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>com.otv.exe.Application</mainClass> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>META-INF/spring.handlers</resource> </transformer> <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer"> <resource>META-INF/spring.schemas</resource> </transformer> </transformers> </configuration> </execution> </executions> </plugin>STEP 3 : CREATE TASK CLASS A new TestTask Class is created by implementing Runnable Interface. This class shows to be executed tasks. package com.otv.task; import org.apache.log4j.Logger; /** * @author onlinetechvision.com * @since 17 Oct 2011 * @version 1.0.0 * */ public class TestTask implements Runnable { private static Logger log = Logger.getLogger(TestTask.class); String taskName; public TestTask() { } public TestTask(String taskName) { this.taskName = taskName; } public void run() { try { log.debug(this.taskName + " : is started."); Thread.sleep(10000); log.debug(this.taskName + " : is completed."); } catch (InterruptedException e) { log.error(this.taskName + " : is not completed!"); e.printStackTrace(); } } @Override public String toString() { return (getTaskName()); } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } }STEP 4 : CREATE TestRejectedExecutionHandler CLASS TestRejectedExecutionHandler Class is created by implementing RejectedExecutionHandler Interface. If there is no idle thread and queue overflows, tasks will be rejected. This class handles rejected tasks. package com.otv.handler; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import org.apache.log4j.Logger; /** * @author onlinetechvision.com * @since 17 Oct 2011 * @version 1.0.0 * */ public class TestRejectedExecutionHandler implements RejectedExecutionHandler { private static Logger log = Logger.getLogger(TestRejectedExecutionHandler.class); public void rejectedExecution(Runnable runnable, ThreadPoolExecutor executor) { log.debug(runnable.toString() + " : has been rejected"); } }STEP 5 : CREATE ITestThreadPoolExecutorService INTERFACE ITestThreadPoolExecutorService Interface is created. package com.otv.srv; import java.util.concurrent.ThreadPoolExecutor; import com.otv.handler.TestRejectedExecutionHandler; /** * @author onlinetechvision.com * @since 17 Oct 2011 * @version 1.0.0 * */ public interface ITestThreadPoolExecutorService { public ThreadPoolExecutor createNewThreadPool(); public int getCorePoolSize(); public void setCorePoolSize(int corePoolSize); public int getMaxPoolSize(); public void setMaxPoolSize(int maximumPoolSize); public long getKeepAliveTime(); public void setKeepAliveTime(long keepAliveTime); public int getQueueCapacity(); public void setQueueCapacity(int queueCapacity); public TestRejectedExecutionHandler getTestRejectedExecutionHandler(); public void setTestRejectedExecutionHandler(TestRejectedExecutionHandler testRejectedExecutionHandler); }STEP 6 : CREATE TestThreadPoolExecutorService CLASS TestThreadPoolExecutorService Class is created by implementing ITestThreadPoolExecutorService Interface. This class creates a new Thread Pool. package com.otv.srv; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import com.otv.handler.TestRejectedExecutionHandler; /** * @author onlinetechvision.com * @since 17 Oct 2011 * @version 1.0.0 * */ public class TestThreadPoolExecutorService implements ITestThreadPoolExecutorService { private int corePoolSize; private int maxPoolSize; private long keepAliveTime; private int queueCapacity; TestRejectedExecutionHandler testRejectedExecutionHandler; public ThreadPoolExecutor createNewThreadPool() { ThreadPoolExecutor executor = new ThreadPoolExecutor(getCorePoolSize(), getMaxPoolSize(), getKeepAliveTime(), TimeUnit.SECONDS, new ArrayBlockingQueue(getQueueCapacity()), getTestRejectedExecutionHandler()); return executor; } public int getCorePoolSize() { return corePoolSize; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public int getMaxPoolSize() { return maxPoolSize; } public void setMaxPoolSize(int maxPoolSize) { this.maxPoolSize = maxPoolSize; } public long getKeepAliveTime() { return keepAliveTime; } public void setKeepAliveTime(long keepAliveTime) { this.keepAliveTime = keepAliveTime; } public int getQueueCapacity() { return queueCapacity; } public void setQueueCapacity(int queueCapacity) { this.queueCapacity = queueCapacity; } public TestRejectedExecutionHandler getTestRejectedExecutionHandler() { return testRejectedExecutionHandler; } public void setTestRejectedExecutionHandler(TestRejectedExecutionHandler testRejectedExecutionHandler) { this.testRejectedExecutionHandler = testRejectedExecutionHandler; } }STEP 7 : CREATE IThreadPoolMonitorService INTERFACE IThreadPoolMonitorService Interface is created. package com.otv.monitor.srv; import java.util.concurrent.ThreadPoolExecutor; public interface IThreadPoolMonitorService extends Runnable { public void monitorThreadPool(); public ThreadPoolExecutor getExecutor(); public void setExecutor(ThreadPoolExecutor executor); }STEP 8 : CREATE ThreadPoolMonitorService CLASS ThreadPoolMonitorService Class is created by implementing IThreadPoolMonitorService Interface. This class monitors created thread pool. package com.otv.monitor.srv; import java.util.concurrent.ThreadPoolExecutor; import org.apache.log4j.Logger; /** * @author onlinetechvision.com * @since 17 Oct 2011 * @version 1.0.0 * */ public class ThreadPoolMonitorService implements IThreadPoolMonitorService { private static Logger log = Logger.getLogger(ThreadPoolMonitorService.class); ThreadPoolExecutor executor; private long monitoringPeriod; public void run() { try { while (true){ monitorThreadPool(); Thread.sleep(monitoringPeriod*1000); } } catch (Exception e) { log.error(e.getMessage()); } } public void monitorThreadPool() { StringBuffer strBuff = new StringBuffer(); strBuff.append("CurrentPoolSize : ").append(executor.getPoolSize()); strBuff.append(" - CorePoolSize : ").append(executor.getCorePoolSize()); strBuff.append(" - MaximumPoolSize : ").append(executor.getMaximumPoolSize()); strBuff.append(" - ActiveTaskCount : ").append(executor.getActiveCount()); strBuff.append(" - CompletedTaskCount : ").append(executor.getCompletedTaskCount()); strBuff.append(" - TotalTaskCount : ").append(executor.getTaskCount()); strBuff.append(" - isTerminated : ").append(executor.isTerminated()); log.debug(strBuff.toString()); } public ThreadPoolExecutor getExecutor() { return executor; } public void setExecutor(ThreadPoolExecutor executor) { this.executor = executor; } public long getMonitoringPeriod() { return monitoringPeriod; } public void setMonitoringPeriod(long monitoringPeriod) { this.monitoringPeriod = monitoringPeriod; } }STEP 9 : CREATE Starter CLASS Starter Class is created. package com.otv.start; import java.util.concurrent.ThreadPoolExecutor; import org.apache.log4j.Logger; import com.otv.handler.TestRejectedExecutionHandler; import com.otv.monitor.srv.IThreadPoolMonitorService; import com.otv.monitor.srv.ThreadPoolMonitorService; import com.otv.srv.ITestThreadPoolExecutorService; import com.otv.srv.TestThreadPoolExecutorService; import com.otv.task.TestTask; /** * @author onlinetechvision.com * @since 17 Oct 2011 * @version 1.0.0 * */ public class Starter { private static Logger log = Logger.getLogger(TestRejectedExecutionHandler.class); IThreadPoolMonitorService threadPoolMonitorService; ITestThreadPoolExecutorService testThreadPoolExecutorService; public void start() { // A new thread pool is created... ThreadPoolExecutor executor = testThreadPoolExecutorService.createNewThreadPool(); executor.allowCoreThreadTimeOut(true); // Created executor is set to ThreadPoolMonitorService... threadPoolMonitorService.setExecutor(executor); // ThreadPoolMonitorService is started... Thread monitor = new Thread(threadPoolMonitorService); monitor.start(); // New tasks are executed... for(int i=1;i<10;i++) { executor.execute(new TestTask("Task"+i)); } try { Thread.sleep(40000); } catch (Exception e) { log.error(e.getMessage()); } for(int i=10;i<19;i++) { executor.execute(new TestTask("Task"+i)); } // executor is shutdown... executor.shutdown(); } public IThreadPoolMonitorService getThreadPoolMonitorService() { return threadPoolMonitorService; } public void setThreadPoolMonitorService(IThreadPoolMonitorService threadPoolMonitorService) { this.threadPoolMonitorService = threadPoolMonitorService; } public ITestThreadPoolExecutorService getTestThreadPoolExecutorService() { return testThreadPoolExecutorService; } public void setTestThreadPoolExecutorService(ITestThreadPoolExecutorService testThreadPoolExecutorService) { this.testThreadPoolExecutorService = testThreadPoolExecutorService; } }STEP 10 : CREATE Application CLASS Application Class is created. This class runs the application. package com.otv.start; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author onlinetechvision.com * @since 17 Oct 2011 * @version 1.0.0 * */ public class Application { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Starter starter = (Starter) context.getBean("Starter"); starter.start(); } }STEP 11 : CREATE applicationContext.xml applicationContext.xml is created. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Beans Declaration --> <bean id="TestTask" class="com.otv.task.TestTask"></bean> <bean id="ThreadPoolMonitorService" class="com.otv.monitor.srv.ThreadPoolMonitorService"> <property name="monitoringPeriod" value="5" /> </bean> <bean id="TestRejectedExecutionHandler" class="com.otv.handler.TestRejectedExecutionHandler"></bean> <bean id="TestThreadPoolExecutorService" class="com.otv.srv.TestThreadPoolExecutorService"> <property name="corePoolSize" value="1" /> <property name="maxPoolSize" value="3" /> <property name="keepAliveTime" value="10" /> <property name="queueCapacity" value="3" /> <property name="testRejectedExecutionHandler" ref="TestRejectedExecutionHandler" /> </bean> <bean id="Starter" class="com.otv.start.Starter"> <property name="threadPoolMonitorService" ref="ThreadPoolMonitorService" /> <property name="testThreadPoolExecutorService" ref="TestThreadPoolExecutorService" /> </bean> </beans>STEP 12 : ALTERNATIVE METHOD TO CREATE THREAD POOL ThreadPoolTaskExecutor Class provided by Spring can also be used to create Thread Pool. <bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <property name="corePoolSize" value="1" /> <property name="maxPoolSize" value="3" /> <property name="queueCapacity" value="3" /> </bean> <bean id="testTaskExecutor" class="TestTaskExecutor"> <constructor-arg ref="threadPoolTaskExecutor" /> </bean>STEP 13 : BUILD PROJECT After OTV_Spring_ThreadPool Project is build, OTV_Spring_ThreadPool-0.0.1-SNAPSHOT.jar will be created. STEP 14 : RUN PROJECT After created OTV_Spring_ThreadPool-0.0.1-SNAPSHOT.jar file is run, below output logs will be shown : 18.10.2011 20:08:48 DEBUG (TestRejectedExecutionHandler.java:19) - Task7 : has been rejected 18.10.2011 20:08:48 DEBUG (TestRejectedExecutionHandler.java:19) - Task8 : has been rejected 18.10.2011 20:08:48 DEBUG (TestRejectedExecutionHandler.java:19) - Task9 : has been rejected 18.10.2011 20:08:48 DEBUG (TestTask.java:25) - Task1 : is started. 18.10.2011 20:08:48 DEBUG (TestTask.java:25) - Task6 : is started. 18.10.2011 20:08:48 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 2 - CompletedTaskCount : 0 - TotalTaskCount : 5 - isTerminated : false 18.10.2011 20:08:48 DEBUG (TestTask.java:25) - Task5 : is started. 18.10.2011 20:08:53 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 3 - CompletedTaskCount : 0 - TotalTaskCount : 6 - isTerminated : false 18.10.2011 20:08:58 DEBUG (TestTask.java:27) - Task6 : is completed. 18.10.2011 20:08:58 DEBUG (TestTask.java:27) - Task1 : is completed. 18.10.2011 20:08:58 DEBUG (TestTask.java:25) - Task3 : is started. 18.10.2011 20:08:58 DEBUG (TestTask.java:25) - Task2 : is started. 18.10.2011 20:08:58 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 3 - CompletedTaskCount : 2 - TotalTaskCount : 6 - isTerminated : false 18.10.2011 20:08:58 DEBUG (TestTask.java:27) - Task5 : is completed. 18.10.2011 20:08:58 DEBUG (TestTask.java:25) - Task4 : is started. 18.10.2011 20:09:03 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 3 - CompletedTaskCount : 3 - TotalTaskCount : 6 - isTerminated : false 18.10.2011 20:09:08 DEBUG (TestTask.java:27) - Task2 : is completed. 18.10.2011 20:09:08 DEBUG (TestTask.java:27) - Task3 : is completed. 18.10.2011 20:09:08 DEBUG (TestTask.java:27) - Task4 : is completed. 18.10.2011 20:09:08 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 0 - CompletedTaskCount : 6 - TotalTaskCount : 6 - isTerminated : false 18.10.2011 20:09:13 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 0 - CompletedTaskCount : 6 - TotalTaskCount : 6 - isTerminated : false 18.10.2011 20:09:18 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 0 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 0 - CompletedTaskCount : 6 - TotalTaskCount : 6 - isTerminated : false 18.10.2011 20:09:23 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 0 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 0 - CompletedTaskCount : 6 - TotalTaskCount : 6 - isTerminated : false 18.10.2011 20:09:28 DEBUG (TestTask.java:25) - Task10 : is started. 18.10.2011 20:09:28 DEBUG (TestRejectedExecutionHandler.java:19) - Task16 : has been rejected 18.10.2011 20:09:28 DEBUG (TestRejectedExecutionHandler.java:19) - Task17 : has been rejected 18.10.2011 20:09:28 DEBUG (TestRejectedExecutionHandler.java:19) - Task18 : has been rejected 18.10.2011 20:09:28 DEBUG (TestTask.java:25) - Task14 : is started. 18.10.2011 20:09:28 DEBUG (TestTask.java:25) - Task15 : is started. 18.10.2011 20:09:28 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 3 - CompletedTaskCount : 6 - TotalTaskCount : 12 - isTerminated : false 18.10.2011 20:09:33 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 3 - CompletedTaskCount : 6 - TotalTaskCount : 12 - isTerminated : false 18.10.2011 20:09:38 DEBUG (TestTask.java:27) - Task10 : is completed. 18.10.2011 20:09:38 DEBUG (TestTask.java:25) - Task11 : is started. 18.10.2011 20:09:38 DEBUG (TestTask.java:27) - Task14 : is completed. 18.10.2011 20:09:38 DEBUG (TestTask.java:27) - Task15 : is completed. 18.10.2011 20:09:38 DEBUG (TestTask.java:25) - Task12 : is started. 18.10.2011 20:09:38 DEBUG (TestTask.java:25) - Task13 : is started. 18.10.2011 20:09:38 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 3 - CompletedTaskCount : 9 - TotalTaskCount : 12 - isTerminated : false 18.10.2011 20:09:43 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 3 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 3 - CompletedTaskCount : 9 - TotalTaskCount : 12 - isTerminated : false 18.10.2011 20:09:48 DEBUG (TestTask.java:27) - Task11 : is completed. 18.10.2011 20:09:48 DEBUG (TestTask.java:27) - Task13 : is completed. 18.10.2011 20:09:48 DEBUG (TestTask.java:27) - Task12 : is completed. 18.10.2011 20:09:48 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 0 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 0 - CompletedTaskCount : 12 - TotalTaskCount : 12 - isTerminated : true 18.10.2011 20:09:53 DEBUG (ThreadPoolMonitorService.java:39) - CurrentPoolSize : 0 - CorePoolSize : 1 - MaximumPoolSize : 3 - ActiveTaskCount : 0 - CompletedTaskCount : 12 - TotalTaskCount : 12 - isTerminated : trueSTEP 15 : DOWNLOAD OTV_Spring_ThreadPool Reference: How to develop and monitor Thread Pool Services by using Spring from our JCG partner Eren Avsarogullari at the Online Technology Vision blog....
apache-camel-logo

Apache Camel – A little Scala DSL example

So we have a Scala DSL in Apache Camel for many years now, and I guess its about time I wrote a little blog entry about this (has been on my todo list for a while). So the Scala DSL is of course using the Scala programming language which has many bells and whistles over plain Java. However the uptake of the Scala DSL is not very high, as the Java and XML DSL’s is good enough for most people. Anyway I guess one of the nice thing about the Scala DSL would be using closures as expressions and predicates etc. So let’s do a little example using the Filter EIP pattern and use a closure as the filter predicate. When using the Scala DSL you should use the org.apache.camel.scala.dsl.builder.RouteBuilder, which is the Scala empowered DSL. So in the following we have a FilterRoute class where we use the Scala DSL, when we define the createMyFilterRoute function. class FilterRoute { def createMyFilterRoute = new RouteBuilder { from("direct:start") .filter(_.in("gold") == "true") .to("mock:gold") } }As you can see from the code above, inside the scope of RouteBuilder we have the Scala DSL at our disposal. Then we use the Filter EIP which accepts a function with the Exchange as parameter, which gets defaulted into the _ symbol. The result of that function is the evaluated as a predicate, using the Scala powerful (but a bit scary) type system with implicit type converter and case matching etc. The in(“gold”) is a function on a Exchange wrapped we have in the Scala DSL which adds additional methods on the Camel Exchange (RichExchange), the in is a function that look up a header. To unit test this route I wanted to use the existing and powerful camel-test module. This module offers the CamelTestSupport class you can extend for your unit tests. So the unit tests can be almost like in Java, but you would need to add the trait org.apache.camel.scala.dsl.RouteBuilderSupport which helps bridge the Scala RouteBuilder with the Java RouteBuilder, that the CamelTestSupport expects and uses. The code below shows an unit test example. class FilterRouteTest extends CamelTestSupport with RouteBuilderSupport {override def createRouteBuilder() = new FilterRoute().createMyFilterRoute@Test def testFilterRouteGold() { getMockEndpoint("mock:gold").expectedMessageCount(1) template.sendBodyAndHeader("direct:start", "Hello World", "gold", "true") assertMockEndpointsSatisfied() }@Test def testFilterRouteNotGold() { getMockEndpoint("mock:gold").expectedMessageCount(0) template.sendBodyAndHeader("direct:start", "Hello World", "gold", "false") assertMockEndpointsSatisfied() }}As you can see we use the RouteBuilderSupport trait, and then override the createRouteBuilder function to return the Scala DSL empowered RouteBuilder we created previously. The rest of the code is standard and plain Java code with JUnit @Test annotations. This example is provided in the source code of the camel-scala module, as part of a unit test. If you are a Scala fan and interested in Camel as well, then the Camel community could use people who are dedicated to Scala and help with the Scala DSL. The Camel team is often busy with other issues in our lives, so we only have a bit time to have fun and play with Scala. Reference: Apache Camel – A little Scala DSL example from our JCG partner Claus Ibsen at the Claus Ibsen riding the Apache Camel blog....
jetbrains-intellijidea-logo

Tomcat & IntelliJ – Deploy war files outside webapps folder

At present I am working on developing an Android application that needs to be supported by a slew of REST services hosted in the cloud. I chose Google App Engine based on its support for Java, Groovy and most importantly Spring. I developed a Spring MVC based REST application and used ContentNegotiatingViewResolver to negotiate content based on request URL extensions. For example, an XML response will be returned if the request URL ends with .xml, a JSON response for .json and an HTML response if he URL doesn’t have any extension. Don’t get me started on Accept Header versus URL extension based content negotiation. That is a rant for another day. I was attempting to Serialize a Map<Enum, List<Model>>. All was well and I was able to retrieve both HTML and JSON representations, but when I tested retrieving the XML representation, JAXB complained that it cannot handle a Map instance in the root although Jackson was totally cool about it. As usual, Googling revealed that JAXB expected a Container class at its root which I didn’t want to create. I didn’t want to give up either. So, I tried my luck using XStreamMarshaller. This time GAE complained that XStream used a restricted API. WTH? Just out of curiosity, I wanted to check if XStreamMarshaller would work as expected when used outside of GAE. So, I created a Tomcat context file “myapp.xml” with the following definition and carefully placed it inside TOMCAT_HOME/conf/Catalina/localhost. I could have just started Tomcat from TOMCAT_HOME/bin/startup.bat to check if it works, but being an IDEA addict, I created a Run Configuration for the IDEA Tomcat plugin and started the server from inside IDEA. But the app refused to even be discovered, let alone be deployed. After a few frustrated attempts, I tried starting Tomcat directly outside IDEA. Thankfully the app got deployed successfully and to my surprise, the XStreamMarshaller skillfully streamed out the serialized XML. Problem Solved! <?xml version='1.0' encoding='utf-8'?> <Context docBase="PATH_TO_MY_APP" reloadable="true" path="/myapp"> </Context>But, why didn’t the app get deployed when I started Tomcat from inside IDEA? After all, I have linked IDEA to my local Tomcat installation and the script it executes is clearly in my TOMCAT_HOME/bin folder. Then, why why why in the world does the app refuse to be discovered? The solution came in the form of CATALINA_BASE. It seems that IDEA copies the contents of TOMCAT_HOME/conf folder into its HOME folder with some name like Unnamed_MyApp and sets this folder to be the CATALINA_BASE. That explains why “myapp.xml” is so totally ignored by Tomcat. Then, I navigated to “Tomcat Run Configuration -> Startup/Connection -> Environment Variables” and added CATALINA_BASE as an environment variable and pointed it to your local TOMCAT_HOME folder. After this configuration change IDEA started Tomcat as expected and my app was both discovered and deployed. Another Problem Solved! But the real problem – JAXB complaining about Map and GAE rejecting XStreamMarshaller as restricted – is yet to be solved. Maybe I should try one of the CastorMarshaller, XmlBeansMarshaller or JibxMarshaller. Any ideas? Reference: Tomcat & IntelliJ – Deploy war files outside webapps folder from our JCG partner Ganeshji Marwaha at the Ganesh blog....
google-app-engine-logo

Google Appengine Staging Server Howto

Out of the box, Google’s App Engine supports versioned deployments. You can switch back and forth between revisions very easily, which is a great feature for properly testing an application before going live. There is one major problem: All versions of the application share the same datastore. So if you’re migrating your data you run a serious risk of influencing your current production application. Hence the need for a proper staging environment. It’s no secret, I am a fan of Google’s App Engine. Once you get used to its peculiarities, it has a number of major advantageous. Since I started incorporating some of the continuous integration/lean startup ideas in my own project. I’ve run into the shared datastore issue and the need for a properly isolated staging environment has become apparent. Here’s how I did it. Setting up the Staging Application It’s possible to use namespaces to create an isolated datastore, however I didn’t want to create additional code for testing. So I took another approach, which I believe is a lot easier and less error-prone:In the appengine control panel, create a second application. You have 10 free ones so that shouldn’t be a problem. I added the “-staging” suffix to the name of the application under test, so I won’t mistake one for the other. If you want to start from a copy of the existing datastore, you can export the entire datastore using the Python development kit. Even if you’re using the Java development kit, it’s worth setting this up. It allows you to make backups of your datastore, which might come in handy when something is really messed up. Next, import the database into your staging application using the same tool. And finally, deploy your application to the staging application. If you’re using Eclipse, just change the application id, if not, you can find the property in the appengine-web.xml.A small note on using production data in your tests: Be very careful about it. You may want to anonymize some of the data and remove anything that could be remotely confidential. That should be it. There really wasn’t much to it, but you now should have a fully functioning copy of your production application. Surf around a little to make sure everything is working swiftly. When you’re happy, lets automate it. Automating Deployments I was about to throw out Maven, but I’ve now created a setup that I’m pretty happy with. So Maven is here to stay for now. As are the Maven Eclipse plugin and the GAE plugin for Maven. It’s thanks to the maven-gae-plugin that I could automate the staging and production deployments. Which has given me a very reproducible build and deployment set up. To seamlessly create a build for both the staging and production server, I’m using Maven profiles and its ability to filter resources while copying them. In the appengine-web.xml I added a gae.application variable: <?xml version="1.0" encoding="utf-8"?> <appengine-web-app xmlns="http://appengine.google.com/ns/1.0"> <application>${gae.application}</application> ...Next up I enabled filtering of the appengine-web.xml (all of the next few bits go into the pom.xml): <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <webResources> <resource> <directory>src/main/webapp</directory> <filtering>true</filtering> <includes> <include>**/appengine-web.xml</include> </includes> </resource> </webResources> </configuration> </plugin>In the properties section, I added the default application, which is the staging one. This gives me the assurance that I’ll always be deploying to the staging environment, unless I really want to go to production: <properties> <gae.application>myapp-staging</gae.application> </properties>And for the production deployment I created a profile: <profiles> <profile> <id>production</id> <properties> <gae.application>myapp</gae.application> </properties> </profile> </profiles>With this configuration, I can easily run the local development server: > mvn gae:run Deploy to the staging server: > mvn gae:deploy And when I’m happy, deploy it to the production server: > mvn gae:deploy -Pproduction In addition to the name of the application, you can also configure other properties that differ between a test setup and a production one. For instance, I use the PayPal development servers locally and on the staging server, but the real PayPal site in production. Conclusion With a pretty simple Maven configuration, it’s possible to create a very reproducible build and deployment environment. Add a continuous integration server and you’re on your way to the perfect lean setup. Reference: A Google Appengine Staging Server Howto from our JCG partner Peter Backx at the Streamhead blog....
spring-logo

Spring MVC – Flash Attributes

Latest Spring Framework incarnation (3.1) brought interesting feature called Flash Attributes. It is remedy for the problem mentioned a long time ago, in one of my posts: Spring MVC – Session Attributes handling. This problem can be described in few words: if we want to pass the attributes via redirect between two controllers, we cannot use request attributes (they will not survive the redirect), and we cannot use Spring’s @SessionAttributes (because of the way Spring handles it), only ordinary HttpSession can be used, which is not very convenient. Below you will find an example of Flash Attributes usage, before you start reviewing it, read Using flash attributes section of Spring documentation. Suppose that we have two controllers: AController and BController, first one will prepare some data and pass to the second using Flash Attributes after the form submission. On the AController we will have something like this: @RequestMapping(method = RequestMethod.POST) public String handleFormSubmission(..., final RedirectAttributes redirectAttrs) { ... redirectAttrs.addFlashAttribute("AttributeName", value); return "redirect:to_some_url_handled_by_BController"; }When the form will be submitted, attribute value will be stored as Flash Attribute named “AttributeName”, and thanks to the Spring, will be passed to BController, where it can be used for example in following way: @Controller ... @SessionAttributes("AttributeName") public class SearchCriteriaHandler { ... @RequestMapping(method = RequestMethod.GET) public void handleGetRequest(@ModelAttribute("AttributeName") final SomeType value) { ... } ... }Before your handler method will be called, Spring Framework will populate the Model with the available Flash Attributes – at this point value passed from AController will become a model attribute for the BController. Note, that because we also defined this attribute as the Session Attribute, it will be automatically stored for future usage within this controller, after the GET request handling. Let me say that I was waiting for this feature for the long time, ;) Related Posts: Spring MVC – Session Attributes handling Reference: Spring MVC – Flash Attributes from our JCG partner Micha? Ja?tak at the Warlock’s Thoughts blog....
java-logo

Set up a Java EE 6 development environment

This tutorial explains in short how to set-up a typical environment to develop Java EE 6 based applications. There is no prerequesite to this tutorial other then a working Windows XP client with sufficient CPU power and memory. During the tutorial we will need to install the following components:Java 6 JDK Update 26 Eclipse IDE for Java EE Developers 3.6.2 (Helios) Maven 3.0.3 Glassfish 3.1I suggest that you create a folder where you drop all the stuff we need to set-up the environment. My Folder is C:\jee6. I will call that <dev_home> when I refer to it. Note: In one of my recent posts I explained how to set-up a Spring environment. This process is very simmilar, therefore I will only explain deviations in this Java EE set-up.In this tutorial we will create a little demo project. The sample application uses JSF 2.0, CDI 1.0, EJB 3.1 and JPA 2.0 (persistence unit included). The demo can be used to start development of your own enterprise project.Installing Java 6 JDKSee this blog post.Installing Eclipse IDE for Java EE DevelopersSee this blog post.Creating the Eclipse Projects using Maven 3See my Spring blog where I have explained how to set-up Maven and create a Spring project. The process to create a Java EE 6 project is almost equivalent. The only difference in setting up a Java EE environment is the archetype to use to create the Eclipse Project. When you create the Eclipse project use the following Maven command: mvn archetype:generate -DarchetypeGroupId=org.jboss.weld.archetypes -DarchetypeArtifactId=weld-jsf-jee -DarchetypeVersion=1.0.0-BETA1 -DgroupId=com.mycompany.jeeapp -DartifactId=jee-app-weld -Dversion=1.0-SNAPSHOT -DinteractiveMode=falseNote: I have also marked the differences in my Spring post to make it obvious where the Spring specifics are during Maven set-up and project creation.Note: At the time this blog post was created the weld-jsf-jee archetype was in beta state. You may use the 1.0 version when it is available. See here to find out if there is a newer version of this archetype.Installing Glassfish 3.1In a Java EE project you need a Java EE server. At the time this post was created Glassfish 3.1 was the only server available that provided the full Java EE 6 stack. Therefore I opt to use Glassfish. To Intall Glassfish to your local machine do the following: Download Glassfish 3.1Go to Glassfish Download page.Select Download GlassFish Server Open Source Edition 3.1. Then choose the Zip-Archive glassfish-3.1.zip (GlassFish Server 3.1 Open Source Edition Full Platform) In your <dev_home> create a folder called glassfish. Unzip the Zip-Archive hereConfigure Eclipse After you successfully downloaded a Glassfish copy you need to configure your Eclipse IDE to use Glassfish 3.1 as the target runtime environment. To do this follow these steps:Open Eclipse.In the Eclipse menu bar select “Window > Show View > Servers”. In the “Servers” view right click on the white space and select “New > Server”.Select the Link “Download additional server adapters”. Eclipse now downloads available server adapters.Select “Oracle Glassfish Server Tools” from the list.Accept the license and select “Finish”. The download begins.Restart Eclipse to activate the new adapter. When you re-enter Eclipse you see the Glassfish server tools front page.Close that view and go to the Workbench.In Eclipse go to the “Servers” view (remember: window available at the bottom) and right click in the white space, then select “New > Server”.Select GlassFish Server Open Source Edition 3 (Java EE 6) and select “Next”Select your home directory for the GlassFish instance you downloaded, that should be <dev_home>/glassfish/glassfish. Select “Finish” if possible. Otherwise, you may have to specify a domain. In that case select “Next”.The domain should be preselected, then click “Finish”.You should see in the “Servers” view that Glassfish was added. To start the server right click on Glassfish server and select “Debug”.  Go to the “Console” view (another window available at the bottom in the Eclipse workbench) and see how GlassFish talks to you :-). You may need to change into the server.log to see the log entries displayed. I have higlighted the toolbar button where you can change to the server log. To maximize and minimize the “Console” view you need to double click the “Console” tab. To verify installation go to your web browser and enter http://localhost:8080.Select the Link “goto the Administration Console” to enter the Admin Console.You can manage GlassFish in the Admin Console. Take a look around.Your environment is complete now. It’s time to get the demo application going.Starting and using the demo application In one of the previous steps we have created a Java EE based application with Maven. We have to import it into Eclipse. You can do this as follows: Import your Java EE applicationOpen Eclipse.In the menu bar select “File > Import”.Enter “Existing” into “Select an import source”.Select “Existing Projects into Workspace” and click “Next”.Select the root directory of the application you have just created with Maven. This should be <dev_home>\workspace\jee-app-weld. Then select “Finish”.The project will be imported. You will notice when you go to the “Markers” view that there are several errors. We have to fix those. Right click the Project “jee-app-weld” and select “Properties” from the context menu.Goto “Targeted Runtimes”.Select GlassFish and then press “OK”. This should clear all compile errors in your “Markers” viewBugfix the demo application Unfortunately, when this post was written the demo application archetype was in beta state. So you have to do some stuff to make it functioning properly. It’s a good exercise to get used to Eclipse.In Eclipse, press Ctrl+Shift+R. The “Open Resource” dialog shows up. In “Select an Item” enter “persistence.xml”, select it in the list below and press “Open”.Repeat the last two steps for the file “home.xhtml”.  You should have opened two files now: persistence.xml and home.xhtml Look at my fixed persistence.xml file and make yours look the same.I have changed the jta-data-source to the GlassFish setting (default was JBoss) and I have added the property eclipselink.ddl-generation.output-mode to the “Properties for EclipseLink” section. The property makes sure that the database is created on application start-up.  Save your changes with Ctrl+S (or in the menu bar File > Save). The second file to adopt is home.xhtml. Here I have changed <h:dataTable var="_widget" value="#widgets"> to <h:dataTable var="_widget" value="#{widgets}">.Save your changes with Ctrl+S (or in the menu bar File > Save).Note: see this blog entry about persistence.xml and this blog entry about home.xhtml for additional info for the solutions explained above.Configure Eclipse for deployment We are almost done. Now, you need to explain Eclipse that the GlassFish server is the deployment container. You do this as follows:In the “Servers” view right click on the Glassfish server and select “Add and Remove”.Select your application and press “Add” to move it in the right section.Press “Finish”. The last thing to do is to make sure Glassfish starts the integrated Derby database, so you can use the default JDBC datasource. In the menu bar go to “Window > Preferences”.Select “GlassFish Preferences” and select the checkbox to enable the JavaDB when the server starts. Then press OK.That’s it already in terms of preparing Eclipse. Now start the demo application. Starting and verifying the demo applicationSelect the Glassfish server in the “Servers” view and richt click into the context menu, then select “Debug” (make sure the Server is not running already, if so stop the Server first). See the “Console” view to verify that the application started properly. Again: double click the “Console” tab to maximize and minimize the view in the workbench. Make sure you see the server.log.Go to your web browser and enter http://localhost:8080/jee-app-weldYou’re done. You have created your own Java EE development environment. From here look around a litlle and build your own project.Reference: “Setting up a Java EE 6 development environment” from our JCG partner Niklas....
ow2-asm-logo

Manipulating Java Class Files with ASM 4 – Part Two: Tree API

What is ASM tree API: ASM Tree API is the part of ASM that lets you create/modify the class in memory. The class is viewed as a tree of information. Like the whole class is an instance of ClassNode, which contain a list of FieldNode objects, a list of MethodNode objects etc. This article assumes that the reader has already read the first part here. A simple class through tree API: Let’s use tree API to create our first class. Again I am going to jump right into a code example, because there is nothing better than a code example. The generated class has a main method that prints “Hello World!”. TreeAPIDemo.java package com.geekyarticles.asm;import java.io.DataOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream;import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode;public class TreeAPIDemo { public static void main(String [] args) throws Exception{ ClassNode classNode=new ClassNode(4);//4 is just the API version number //These properties of the classNode must be set classNode.version=Opcodes.V1_6;//The generated class will only run on JRE 1.6 or above classNode.access=Opcodes.ACC_PUBLIC; classNode.signature="Lcom/geekyarticles/asm/Generated;"; classNode.name="com/geekyarticles/asm/Generated"; classNode.superName="java/lang/Object"; //Create a method MethodNode mainMethod=new MethodNode(4,Opcodes.ACC_PUBLIC|Opcodes.ACC_STATIC,"main", "([Ljava/lang/String;)V",null, null); mainMethod.instructions.add(new FieldInsnNode(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;")); mainMethod.instructions.add(new LdcInsnNode("Hello World!")); mainMethod.instructions.add(new MethodInsnNode(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V")); mainMethod.instructions.add(new InsnNode(Opcodes.RETURN));//Add the method to the classNode classNode.methods.add(mainMethod); //Write the class ClassWriter cw=new ClassWriter(ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES); classNode.accept(cw); //Dump the class in a file File outDir=new File("out/com/geekyarticles/asm"); outDir.mkdirs(); DataOutputStream dout=new DataOutputStream(new FileOutputStream(new File(outDir,"Generated.class"))); dout.write(cw.toByteArray()); dout.flush(); dout.close(); } }As you can see, the code is very simple. A primary advantage over BCEL is that unlike BCEL, ASM does not require you to add every constant explicitly to the constant pool. Instead, ASM takes care of the constant pool itself. Reading a class file: A ClassNode is a ClassVisitor. So, reading a class for use in tree API is as simple as creating a ClassReader object and using it to read a class file, while passing the ClassNode object in its accept method as a parameter. Once this is done, the ClassNode passed is fully initalized with all the information present in the class. In the following example, we will print all the methods in the class. TreeAPIClassReaderDemo.java package com.geekyarticles.asm;import java.io.FileInputStream; import java.io.InputStream;import org.objectweb.asm.ClassReader; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode;public class TreeAPIClassReaderDemo {public static void main(String[] args) throws Exception{ InputStream in=new FileInputStream("out/com/geekyarticles/asm/Generated.class"); ClassReader cr=new ClassReader(in); ClassNode classNode=new ClassNode(); //ClassNode is a ClassVisitor cr.accept(classNode, 0); //Let's move through all the methods for(MethodNode methodNodeclassNode.methods){ System.out.println(methodNode.name+" "+methodNode.desc); }}}Modifying a class file: Modifying a class file is a combination of the above two procedures. We first read the class in the usual way, make necessary changes to the data, and then write it back to a file. The following program implements an automatic injection of some logging code. Currently our Logger class only prints to the standard output. Every method annotated with @Loggable will be logged when they begin and when the return. In this we do not log the throw-exception. However that can also be implemented in the same manner by checking opcode ATHROW. LoggingInsertion.java package com.geekyarticles.asm;import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.Iterator;import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode;public class LoggingInsertion {public static void main(String[] args) throws Exception{ InputStream in=LoggingInsertion.class.getResourceAsStream("/com/geekyarticles/asm/LoggingTest.class");ClassReader cr=new ClassReader(in); ClassNode classNode=new ClassNode(); cr.accept(classNode, 0);//Let's move through all the methodsfor(MethodNode methodNodeclassNode.methods){ System.out.println(methodNode.name+" "+methodNode.desc); boolean hasAnnotation=false; if(methodNode.visibleAnnotations!=null){ for(AnnotationNode annotationNodemethodNode.visibleAnnotations){ if(annotationNode.desc.equals("Lcom/geekyarticles/asm/Loggable;")){ hasAnnotation=true; break; } } } if(hasAnnotation){ //Lets insert the begin logger InsnList beginList=new InsnList(); beginList.add(new LdcInsnNode(methodNode.name)); beginList.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/geekyarticles/asm/Logger", "logMethodStart", "(Ljava/lang/String;)V")); Iterator<AbstractInsnNode> insnNodes=methodNode.instructions.iterator(); while(insnNodes.hasNext()){ System.out.println(insnNodes.next().getOpcode()); } methodNode.instructions.insert(beginList); System.out.println(methodNode.instructions); //A method can have multiple places for return //All of them must be handled. insnNodes=methodNode.instructions.iterator(); while(insnNodes.hasNext()){ AbstractInsnNode insn=insnNodes.next(); System.out.println(insn.getOpcode()); if(insn.getOpcode()==Opcodes.IRETURN ||insn.getOpcode()==Opcodes.RETURN ||insn.getOpcode()==Opcodes.ARETURN ||insn.getOpcode()==Opcodes.LRETURN ||insn.getOpcode()==Opcodes.DRETURN){ InsnList endList=new InsnList(); endList.add(new LdcInsnNode(methodNode.name)); endList.add(new MethodInsnNode(Opcodes.INVOKESTATIC, "com/geekyarticles/asm/Logger", "logMethodReturn", "(Ljava/lang/String;)V")); methodNode.instructions.insertBefore(insn, endList); } } } }//We are done now. so dump the class ClassWriter cw=new ClassWriter(ClassWriter.COMPUTE_MAXS|ClassWriter.COMPUTE_FRAMES); classNode.accept(cw);File outDir=new File("out/com/geekyarticles/asm"); outDir.mkdirs(); DataOutputStream dout=new DataOutputStream(new FileOutputStream(new File(outDir,"LoggingTest.class"))); dout.write(cw.toByteArray()); dout.flush(); dout.close();}}LoggingTest.java package com.geekyarticles.asm;public class LoggingTest { public static void run1(){ System.out.println("run 1"); } @Loggable public static void run2(){ System.out.println("run 2"); } @Loggable public static void main(String [] args){ run1(); run2(); } }Logger.java package com.geekyarticles.asm;public class Logger { public static void logMethodStart(String methodName){ System.out.println("Starting method: "+methodName); } public static void logMethodReturn(String methodName){ System.out.println("Ending method: "+methodName); } }Loggable.java package com.geekyarticles.asm;import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Loggable {}If you run this program, the generated file will have a dependency on the class Logger. Manually copy the Logger class to the correct package in the out directory. If you run the generated class (which is a modified version of LoggingTest class), the following would be the output. bash-4.1$ java com.geekyarticles.asm.LoggingTest Starting method: main run 1 Starting method: run2 run 2 Ending method: run2 Ending method: mainNote that unlike normal Lists, an InsnList object can be modified while we iterate over it. Any changes are immidiately reflected. So, if some instructions are inserted after the current position, that will also be iterated over. Reference: Manipulating Java Class Files with ASM 4 – Part Two: Tree API from our JCG partner Debasish Ray Chawdhuri  at the Geeky Articles blog....
android-logo

Android – Read file from Assets

Description: First of all, let me give you a link: AssetManager, through this class we can easily access any files lying inside the Assets directory of android application. (or any sub-folders inside the Assets directory). Now, we can have an object of AssetManager class by using getAssets() method: AssetManager assetManager = getAssets();And the rest of the procedure i have given and described by making comments in the example so now go through the full solutions provided below with the output snap. Output:Solution: ReadFileAssetsActivity.java package com.paresh.readfileasset;import java.io.IOException; import java.io.InputStream;import android.app.Activity; import android.content.res.AssetManager; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.ImageView; import android.widget.TextView;/** * @author Paresh N. Mayani * @Website http://www.technotalkative.com */ public class ReadFileAssetsActivity extends Activity {/** Called when the activity is first created. */@Override public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.main);TextView txtContent = (TextView) findViewById(R.id.txtContent); TextView txtFileName = (TextView) findViewById(R.id.txtFileName); ImageView imgAssets = (ImageView) findViewById(R.id.imgAssets);AssetManager assetManager = getAssets();// To get names of all files inside the "Files" folder try { String[] files = assetManager.list("Files");for(int i=0; i<files.length; i++)="" {="" txtfilename.append("\n="" file="" :"+i+"="" name=""> "+files[i]); } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }// To load text file InputStream input; try { input = assetManager.open("helloworld.txt");int size = input.available(); byte[] buffer = new byte[size]; input.read(buffer); input.close();// byte buffer into a string String text = new String(buffer);txtContent.setText(text); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }// To load image try { // get input stream InputStream ims = assetManager.open("android_logo_small.jpg");// create drawable from stream Drawable d = Drawable.createFromStream(ims, null);// set the drawable to imageview imgAssets.setImageDrawable(d); } catch(IOException ex) { return; } } } </files.length;>main.xml Note: Please consider scrollview as ScrollView, textview as TextView….etc. Its just problem inside the code plugin. <!--?xml version="1.0" encoding="utf-8"?--><scrollview xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"><linearlayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"><textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" android:id="@+id/txtContent"><imageview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/imgAssets"><textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/txtFileName"> </textview></imageview></textview></linearlayout></scrollview>Download Full source code from here: Android – Read file from Assets Reference: Android – Read file from Assets from our JCG partner Paresh N. Mayani at the TechnoTalkative blog....
aspectj-logo

Implementing Active Record Pattern with Spring AOP

During class design we should take decisions about the assignment of responsibilities that will have every class. If we have chosen well, systems tend to be easier to understand, maintain and extend. Almost all of our projects have a persistence layer, either relational database, document stores, or simply XML files. And typically you will use DAO pattern to implement abstract interface between your business objects and your data store. In this post but I am going to explain another pattern that can be used instead of DAO pattern. Active record pattern is an architectural pattern that force you to implement CRUD operations on your model class, hence model class itself is responsible for saving, deleting, loading from database. There are many strategies to follow to implement this pattern, but for me, the best one is using Aspect Oriented Programming, because we are still maintaining separation of concerns favoring isolated unit testing, and not breaking encapsulation. Aspect-oriented programming entails breaking down program logic into distinct parts. These parts are known as crosscutting concerns because they “cut across” multiple abstractions in a program. Example of crosscutting concerns can be logging, transaction manager, error manager or splitting large datasets. For people that have worked with aspects not much secret here, to use them you simply create an aspect defining the advice and the pointcut, and your aspect is ready to be executed. I guess most of us use aspects-oriented programming as I have described in previous paragraph, but will be fewer that uses ITD (Inter-type Declarations) feature. Inter-type Declarations provide a way to express crosscutting concerns affecting the structure of modules enabling programmers to declare members of another class. As we say in my country “bad said but well understood“, ITD is a way to declare new components (attributes, methods, annotations) of a class from an aspect. AspectJ is an aspect-oriented extension for Java. AspectJ supports ITD, and for this reason will be used in this post. Moreover I recommend you install AJDT plugin because it will help you develop aspects and having a quick overview of which Java classes are aspecterized.If you have not understood what ITD is, don’t worry, it is a typical example of concept that is best understood with an example. Let’s start with simple example: Imagine having to model a car. You would have a car class, with some attributes, for this example three attributes (vin number, miles drived and model) is enough. public class Car {public void setVin(String vin) {this.vin = vin;} public String getVin() {return this.vin;} private String vin;public void setMileNum(int mileNum) { this.mileNum = mileNum;} public int getMileNum() {return this.mileNum;} private int mileNum;public void setModel(String model) {this.model = model;} public String getModel() {return this.model;} private String model;}It is a POJO with three attributes and their getters and setters. Now we want to add persistence layer, but in this case we are going to persist our POJOs in a XML file instead of a database. So Car objects should be transformed to XML stream. For this purpose JAXB annotations will be used. For those who don’t know, JAXB allows developers to map Java classes to XML representations and viceversa. I am sure that first idea that comes to your brain is annotating Car class with @XmlRootElement (annotation to map root element in JAXB). Don’t do that, use aspects. Your first mission is trying to maintain Car file as simple as possible. To add an annotation using ITD, is as simple as: public aspect Car_Jaxb {declare @type: Car: @XmlRootElement; }With @type you are exposing which member is annotated. In this case only class. Other possibilities are @method, @constructor and @field. Then elements pattern that should be annotated, in this case Car class, but you could use any regular expressions like org.alexsotob..*. Finally the annotation. Next step is using JAXB classes to marshalling/unmarshalling objects. In this example I am using spring-oxm package and briefly you will understand why. Spring-oxm is a part of spring-core that contains classes for dealing with O/X Mapping. This spring module contains one class for each Xml binding supported. In our case Jaxb2Marshaller is used as marshaller and unmarshaller. It is possible that you are thinking of creating a service class where you inject Jaxb2Marshaller instance. This service would include two methods (save and load) with Car class as argument or return value. Sorry but, doing this, you are implementing DAO pattern. Let’s implement Active Record pattern approach. And as you may suppose, aspectj comes to rescue you to avoid mixing concepts in same source file. Let’s update previous aspect file so all required logic by JAXB will be in same file. import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;import javax.xml.bind.annotation.XmlRootElement; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.oxm.jaxb.Jaxb2Marshaller;public aspect Car_Jaxb {declare @type: Car: @XmlRootElement;@Autowired transient Jaxb2Marshaller Car.marshaller;public void Car.save(OutputStream outputStream) throws IOException { this.marshaller.marshal(this, new StreamResult(outputStream)); }public Car Car.load(InputStream inputStream) throws IOException { return (Car)this.marshaller.unmarshal(new StreamSource(inputStream)); }}See that apart from annotating Car class we are creating two methods, and an annotated attribute. Attributes must follow same rule as methods, <class name> dot (.) and <attribute name>. Note that in this case attribute is transient because should not be bound in XML file. Last step is configuring marshaller in spring context file. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"><oxm:jaxb2-marshaller id="marshaller"> <oxm:class-to-be-bound name="org.alexsotob.itd.Car"/> </oxm:jaxb2-marshaller></beans>Not much secret. Now let’s code a unit test. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="/context.xml") public class CarOxmBehaviour {@Test public void shouldSaveCarToXml() throws Exception { //Given Car car = new Car(); car.setMileNum(1000); car.setModel("Ferrari"); car.setVin("1M8GDM9AXKP042788"); //From http://en.wikipedia.org/wiki/Vehicle_Identification_Number//When ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); car.save(byteArrayOutputStream);//Then String expectedMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><car><mileNum>1000</mileNum><model>Ferrari</model><vin>1M8GDM9AXKP042788</vin></car>"; String xmlMessage = byteArrayOutputStream.toString("UTF-8");assertThat(the(xmlMessage), isEquivalentTo(the(expectedMessage))); }}Run junit class and BOOM all red, with an amazing NullPointerException. Marshaller is created in Spring context, but not injected into Car class (Car is not managed by spring container, so is impossible to be injected). And now I suppose you are telling yourself: “I told you a service layer would be better, because it would be managed by Spring and autowired would work perfect.”. But wait and see. How about using spring-aspects module? Spring Aspects contains an annotation-driven aspect (@Configurable) allowing dependency injection of any object, whatever is or not controlled by container. So let’s apply last two changes and the application will run. First of all is creating a new aspectj file to annotate Car class as Configurable. import org.springframework.beans.factory.annotation.Configurable;public aspect Car_Configurable {declare @type: Car: @Configurable;}And finally modify spring context file to allow @Configurable annotation. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oxm="http://www.springframework.org/schema/oxm" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"><oxm:jaxb2-marshaller id="marshaller"> <oxm:class-to-be-bound name="org.alexsotob.itd.Car"/> </oxm:jaxb2-marshaller> <context:spring-configured></context:spring-configured> </beans>Adding <context:spring-configured></context:spring-configured> namespace is enough. As a result, any time you instantiate an object (via the “new” keyword), Spring will attempt to perform dependency injection on that object. Now run unit test again and green will invade your computer :D. ITD is a really nice solution to design classes with its own responsibilities. It gives you the oportunity of writing maintainable and understandable code, without loosing encapsulation. Of course you should take care of not to have high coupling in aspected classes, and convert them in “God Classes”. Note that implementing same approach but using relational database, it is as simple as changing Jaxb2Marshaller to EntityManager. I wish you have found this post useful. Download Full code Reference: Implementing Active Record Pattern with Spring AOP from our JCG partner Alex Soto at the One Jar To Rule Them All blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close