Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday, January 27, 2013

CLOJUG - First meeting

Hello all. Last Saturday, we had the first meeting of the Cali (CLO) Java Users Group. A new JUG located in the city Cali (Colombia) which focus in Java and Java-related technologies, networking with other communities in our city or country, sharing information and making friends. This initiative starts with three (3) members who are java lovers and experienced java developers. We're looking forward for the participation of students from local schools and universities as well as experienced java developers.




The project is still private on java.net, but, hopefully, it will be public on February. We are planning to have our JUG graduated during the first semester of 2013. Our meetings will be held on the last Saturday of each month (except on December). More information to come.


see ya!!

Saturday, January 12, 2013

Book Review: Oracle ADF Enterprise Application Development Made Simple

Book cover from
http://www.packtpub.com
Oracle ADF is a framework for building Rich Web applications with Java which is built on top of Java EE. So if you have previous experience in building Web applications using JSF you are likely to start developing with Oracle ADF pretty fast. On the contrary, if you are just beginning with Web development, the visual and declarative development that this framework offers will let you build your applications in a fast pace.
The latest release of the framework (as of today) is 11gR2 (11.1.2.3.0) and you can develop using Oracle JDeveloper or Eclipse with the Oracle Enterprise Pack for Eclipse  (OEPE) plugin. Oracle ADF is not free, but there is a smaller version of the framework that is free to develop and free to deploy (even on production) and is called ADF Essentials.

In this post, I'll be reviewing the book "Oracle ADF Enterprise Application Development Made Simple" written by Sten E. Vesterli and published by PACKT. I have to say that this book is not for beginners in the Oracle ADF field, it is aimed at Sr. Java developers or those with ADF background willing to take the next step or even Java architects, as it is not focused on development tips and tricks but on the set of tools and configurations that you need in order to manage the development lifecycle of an ADF application.

Chapter 1, ADF Proof of Concept, shows the steps you should follow in order to prove that ADF is the framework your team should use for that next project. It first briefly introduce you to ADF architecture and components that you should know in order to build your enterprise applications. Then it shows a case study that leads you to create a proof of concept from design to development. Again, this is not a development book, so it doesn't dive on some development concepts.

Chapter 2, Estimating the Effort, presents you a way to measure the cost and how long it will take to build the enterprise application using ADF. It describe some of the common techniques that some companies apply such as use cases or user stories and it states that the user is a critical success factor for the project. It presents three scenarios (optimistic, likely, pessimistic) and shows you the estimation for the case study presented on chapter one.
This chapter also presents a nice software to create UI designs before development called Balsamiq. The good thing about this software is that it produces a "hand-written" look so everyone knows that it is not the final design and that it can change.

Chapter 3, Getting Organized, teaches you that before start coding, you need to think about the skills and the team you need in order to create enterprise applications with ADF. Then it talks about the programming tasks you should be aware of when building such applications and presents you some third party tools you may use in order to enhance collaboration and control the development lifecycle. It finishes showing you how to structure your application so you don't end up with one big workspace but with small ones that you can then integrate.

Chapter 4, Productive Teamwork, introduces you to the Oracle Team Productivity Center, its advantages and quick configuration steps you should follow in order to install and start using this tool inside JDeveloper. I have to say that this tool is a must if you are working in teams and are developing ADF applications.

Chapter 5, Prepare to Build, tells you the basic libraries you need to build in order to make your application extensible in the future. This is a good chapter, because you start building the base structure of your application.

Chapter 6, Building the Enterprise Application, this is where the real development of the application begins. This chapter guides you to the several steps you should follow in order to start working with JDeveloper and the other integrated tools. The mentioned steps are detailed and applied to the case study. It gives you a real sense of what is to be made during development.

Chapter 7, Testing your Application, shows you several libraries and software you can use in order to create tests for your Business components, User Interfaces and for Stress/Performance tests. It gives you examples based on the case study built through out the book. Really easy to follow step by step tutorial and it gives you the tips to configure the tools to work with ADF.

Chapter 8, Look and Feel, guides you to defining the appearance of components without affecting their functionality. As you are building a modular ADF application, it shows you how easy it is to change the look and feel of your application based on Skinning.

Chapter 9, Customizing the Functionality, this is an advanced topic. It tells you how you can customize the same application for several clients. There is some theory about how it works and then hands on simple example that shows you what you need to do in order to customize your application.

Chapter 10, Securing your ADF Application, this chapter is about the many easy-to-use security features built into ADF. It shows you all the configurations you can make in order to have a fine-grained security in your ADF applications. IMPORTANT: the smaller version of ADF, ADF Essentials, is not bundled with this security mechanism, but you can use the Java EE security instead (more about this in future post).

Chapter 11, Package and Deliver, finally, the last step of the development cycle shows you what you should be considering when deploying your applications: cleaning your code, database connections, etc. And it gives you a list of application parameters you should set for a production environment. At the end, it illustrates you in how you can automate the process of compiling, running tests and deploying to the application server using Ant. Great tips for improving your software development process.

Appendix A, Internationalization, shows you the configurations you need in order to have your application available for other languages and zones. Again, easy to follow step by step tutorial.

As you can see, it is a complete book that goes through all the phases when developing applications using ADF, although, several concepts apply to other technologies. I really enjoyed this book, I'm and experience ADF developer and it helped me in architecting several projects, a 100% recommended. One more thing, the book is published in a lot of formats: printed book, kindle, PDF, ePub, so you have many options to read it. I have the kindle edition and it looks great on my kindle, paragraphs are well formatted and the source code is easy to read. There's only one thing, some tables does not fit the page on the kindle version, so you cannot read the last column.

For more information about this book go to:
http://www.packtpub.com/oracle-adf-enterprise-application-development/book

See ya!

Thursday, December 27, 2012

What's for Java in 2013?

Hi all. I just wanted to share some information about what's for the Java technology in 2013, this is from my point of view and from the conferences I've attended this year, but as the Oracle safe harbor statement says: "... While these forward-looking statements represent our current judgment on what the future holds, they are subject to risks and uncertainties that could cause actual results to differ materially ..."

  • A new Java User Group will be born in Cali, Colombia. So if you are around stay tuned. This is my contribution to the community, hopefully we'll get many active members and lots of hackathons, meetings and information sharing.
  • Java SE 6 End-Of-Life (EOL) is estimated for February 2013. It means that you won't get any other update for your Java SE 6 (unless you buy the Java SE Support), but it doesn't mean that Java SE 6 will disappear, you can still download this version in the Java Archive, but you are encouraged to update to Java SE 7, which has been around since July 2011.
  • Oracle will be promoting the Oracle Java Embedded Suite: a full suite for embedded devices which consists of Java SE Embedded 7 runtime, Java DB, Glassfish Server and Jersey WS Framework. You can install this suite on the Raspberry Pi for your projects... nice!
  • JavaFx will continue its development. There's lot of documentation online to learn this technology and you can even install JavaFx apps on embedded systems like the RaspberryPi, check this post by Stephen Chin.
  • Java EE 7 will be released on the first quarter of 2013, around April. Great new features, check them out!
  • Java 8 will be here! The new release of the Java SE will be announced during the second semester of the year, so you better start using Java SE 7 before you get outdated... 
  • Java One 2013 Save the Date: now we have dates for the conferences around the globe, I guess Java One LAD (Brazil) will be held on December at São Paulo.

A lot to come! I hope you can join or create a Java User Group in your area, or blog about the Java technology, or attend to the conferences... anything would be great for the community.


Happy new year!

Wednesday, December 26, 2012

Iterator Pattern and Java

Hello all, in this post we'll be checking on the Iterator Pattern. A design pattern that I know many of you have already used, but maybe you didn't realize it was pattern or didn't know its great value. According to the book Head First Design

The Iterator  Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlaying representation.

Whaaaaat? Well, it says that no matter what data structure (arrays, lists, hashtables,etc.) you are using, you can always traverse it in the same way if you implement this pattern. It gives you a uniform way of accessing the elements of your data structures (aggregates), but you don't have to know what kind of data structure you are traversing... nice!
Also, it sets the responsibility of iteration on the Iterator object not on your data structure, which simplifies the coding in your data structure.

Let's check the classic class diagram for the Iterator pattern:


The actual class diagram for the Iterator Pattern has a few changes, specially in the Iterator class (interface), where we now have different methods as we'll see in a minute, but first, lets review each of the previous classes (or interfaces):

  • Aggregate: This is the base class (or interface) of our data structures, you can think of it as the java.util.Collection interface, which defines a lot of methods for the collection classes.
  • ConcreteAggregate: This is the concrete data structure that we'll be iterating, for example, java.util.ArrayList, java.util.Vector, etc.
  • Iterator: Base class (or interface) for iterators. You can find one in Java at java.util.Iterator. You can notice that the Java version has different methods that we'll be discussing later in this post. Here you define de methods you need in order to traverse the data structures.
  • ConcreteIterator: As you want to traverse different data structures you need different iterators. So a concreteIterator is an Iterator for the data structure you want to traverse.  

Now, let's take a look at the Java implementation of the Iterator Pattern. The following diagram was generated using Architexa's Free Tool for Understanding Code and it shows the relations between some classes of the Java Collections Framework where we can see a structure similar to the classic class diagram:


The above diagram shows only one implementation of the pattern in Java, there are a lot more, but they always use the java.util.Iterator interface; this is the interface you should use in your implementations of the Iterator Pattern when coding in Java. Let's compare both diagrams:


Classic Diagram
ConcreteIterator

Notice that the methods of the Iterator object in the Java example are different from the methods in the classic class diagram:
  • There is no +First() method. If you need to go to the first element, you have to instance a new iterator.
  • The +IsDone() method has been renamed to +hasNext().
  • The +Next() and +CurrentItem() has been merged into +next().
  • The +remove() method has been added.

So, if you ever have to work with different data structures and need a uniform way to traverse them and/or access their items, think about the Iterator Pattern:

//... in a class
  /**
   * Traverse a list, hashtable, vector, etc. what ever that implements
   * the Iterator Pattern
   */
  public void traverse(Iterator iter)
  {
     while(iter.hasNext())
     {
 System.out.println(iter.next());
     }
  }

Of course, you will always have to create the ConcreteIterator class for your data structure, but if you are using classes from the Java Collections Framework, it's already done.

One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.


See ya!


References:

Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Wednesday, December 12, 2012

JavaOne LAD (Brazil) 2012 Days 2 and 3

Hi, I want to share my experiences in the last couple days at JavaOne LAD (Brazil). Day one has been already reviewed here.

Day Two

There was a conference about Oracle Developer Cloud Services which I liked a lot. Great move from Oracle who is moving all its apps and  infrastructure services to the cloud. With such product, you have software lifecycle tools ready to be used. Tools such as: source control management (GIT), issue tracking, Hudson CI and Wiki collaboration. The services is in Preview mode, so you have to contact Oracle in order to test it.




Next I attended a session called "Do You Like Coffee with Your Dessert? Java and the Raspberry Pi" (clever...) which introduced us to the "Raspberry Pi" a credit-card sized computer, imagine that! And you can embed java in it!! There were two live example of embedding Java in a Raspberry Pi. The first one, was a kiosk with all JavaOne LAD session information. Really nice kiosk with touch support and JavaFx.
The second one was a robot created by Vinicius Senger which uses Raspberry Pi and Glassfish Server so you can control the robot using REST WS, awesome!!





The final session of the day was given by Arun Gupta. "Java EE 7 Platform: More Productivity and Integrated HTML". Really nice session packed with the latest news about the JavaEE platform which is schedule to be released on the first quarter of 2013.

At night, Oracle invited the JUG leaders to a nice dinner. Pizza and beers for all of us and networking all around. Was great to meet several Brazil JUG Leaders and learn from their experiences and their culture.


Day Three

Last day of JavaOne LAD. Thanks to Otavio Santana who showed me the correct route to reach the expo center by Metrô as detailed in my previous post. Unfortunately, some sessions were rescheduled and I didn´t noticed that, so I missed the session "JavaFX: Implementing Multitouch with TUIO for Interactive Devices" who was given by Steven Lizarazo, the only Colombian speaker at JavaOne LAD. Congrats!

Next, Stephen Chin talked about JavaFx and HTML5, showing one demo about a JavaFx application which contains map (google map) interaction. It was nice to see how you can integrate both technologies. I skipped the next two conferences because I was presenting a quick demo about Fork/Join Framework at the OTN lounge.

The last conference I attended, was about SQA: "Testing JavaServer Faces Applications with Arquillian and Selenium" given by José Rodolfo Freitas. He showed several ways to test our applications using those frameworks. It was a crowded session, but there was no translation available... so I'm glad the slides were in english... Anyway, thanks José for checking if I was understanding portuguese. 

At the end of the day, the Community Keynote and the first ever Duke's Choice Awards where I was part of the judging panel.

The hosts of the event were Yara Senger and Bruno Sousa (the Brazil JavaMan), great JUG leaders in Brazil. They joked and talked about how we can get involved and participate in the future java by joining/creating a JUG or Adopting a JSR. They also presented some startups that leverage the power of Java for their business ideas.

The entertainment was provided by several JUG leaders who played in a band. They performed some Beatles and Java songs and it was really, really funnny. The Duke's choice Awards winners were presented. We had like 24 nominees, but only 3 could be selected as winners. It was a tough decision since there were a lot of innovation in all projects. I liked that we had several Java technologies competing, from Desktop to Web apps. And the winners were: Tqtvd tots, Cpqd and Tivit. I do have to write another post about the projects I liked the most but were not selected as winners, so you can meet them, specially two Colombian Projects: Kuwaiba and ZathuraCode.






As a regional JavaOne, it is different from the JavaOne SFO, it's smaller. Both events  Oracle OpenWorld and JavaOne are run in the same place, so some times you may find executives wearing suites and ties or developers wearing T-shirts and jeans... I heard from some other attendees that this year was a better JavaOne LAD.

What I liked:
Strong community (Brazil).
Oracle sent several speakers from JavaOne SFO.
Dinner invitation from Oracle ;)
Party invitation from Google :)
Hospitality from the JUG leaders I met.

What I didn't like:
Lack of participation from other south american countries. I mean, is JavaOne LAD (Latinamerican) but most of the attendees and speakers were from Brazil.
The food could be better or cheaper (or included in the full conference pass :p)
Poor twitter or website updates when sessions were rescheduled.
There were no Oracle stores.

Anyway, I hope I can make it for JavaOne LAD 2013 so I can go with other Colombian friends and why not, maybe we can have a first ever Duke's Soccer Cup at Brazil... nice!


see ya!

Tuesday, December 4, 2012

JavaOne Brazil 2012 Day One

Hello all, today I had the opportunity to attend JavaOne LAD (Brazil) 2012.

I'm writing this post right from my mobile device, so I'll be brief.
The community keynote was hosted by several java luminaries and Java Champions from Brazil such as
Fabiane Nardon, Yara Senger, Vinicius Senger, Bruno Souza and a special guest from jFokus. The talk was about getting involved with the java community: Jugs, Java Champions, JCP, etc. Inspiring.

The next conference was about The Internet of Things... Really interesting. You can find more about this at: Things-API.org

Unfortunately I was confused and I left early, missing the java technical keynote... Can't believe it!! grgr

Anyway, tomorrow is another day full of conferences and I'll be posting about the ones I like the most.

See ya!





Thursday, November 1, 2012

Duke's Choice Awards 2012 LAD nomination extended

Just to let you know, the nominations for the Duke's Choice Awards 2012 LAD has been extended, the new final date is Novemeber 7th, 2012.

The program looks for the most compelling implementations of Java technology. Innovation is the only criteria. The nomination form can be found on the Duke's Choice Java.net site


Winners will be announced on stage during JavaOne LAD (Brasil) December 4th through 6th, and will also be featured in the January/February issue of Java Magazine. Winners will receive a free JavaOne LAD full conference pass and a Duke's Choice Award Statue.

So, you are in Latin America (LAD) and have an innovative Java project? what are you waiting for? Remember the end date for nominations is November 07th, 2012.

Don't you know if you got what it takes? Check the 2011 winners (when there was only one global program).


see ya!

Sunday, October 14, 2012

Java 7: Meet the Fork/Join Framework

Free clip art from
http://www.freepik.com
JSR-166(y) is the official name of this new feature which is included in Java 7. If you notice there is a "y" in the name, this is because JSR-166 (Concurrency Utilities) is being added since Java 5, but it wont stop here as there are already plans to add new classes in Java 8 under the JSR-166(e). Check this page maintained by Doug Lea, the creator of JSR-166, for more information.

According to Wikipedia, Parallelism is the "simultaneous execution of some combination of multiple instances of programmed instructions and data on multiple processors" and Java has classes and interfaces to achieve this (sort of...) since DAY 1. You may know them as: java.lang.Thread, java.lang.Runnable, etc... What Concurrency Utilities (java.util.concurrent package) does is simplify the way we code concurrent tasks, so our code is much simpler and cleaner. As developers we haven't had to do anything when running our applications in machines with higher processing resources, obviously, the performance of our applications will improve, but are we really using the processing resources to the maximum? The answer is big NO.

This post will show you how the Fork/Join framework will help us in using the processing resources to the maximum when dealing with problems that can be divided into small problems and all the solutions to each one of those small problems produce the solution of the big problem (like recursion, divide and conquer).

What you need
NetBeans 7+ or any other IDE that supports Java 7
JDK 7+
Blur on an image, example from Oracle

The Basics
The Fork/Join framework focuses on using all the processing resources available in the machine to improve the performance of the applications. It was designed to simplify parallelism in Divide and Conquer algorithms. The magic behind the Fork/Join framework is its work-stealing algorithm in which work threads that are free steal tasks from other busy threads, so all threads are working at all times. Following are the basics you should know in order to start using the framework:
  • Fork means splitting the task into subtasks and work on them.
  • Join means merging the solution of every subtask into one general solution.
  • java.lang.Runtime use this class in order to obtain the number of processors available to the Java virtual machine. Use the method +availableProcessors():int in order to do so.
  • java.util.concurrent.ForkJoinPool Main class of the framework, is the one that implements the work-stealing algorithm and is responsible for running the tasks.
  • java.util.concurrent.ForkJoinTask Abstract class for the tasks that run in a java.util.concurrent.ForkJoinPool. Understand a task as a portion of the whole work, for example, if you need to to do something on an array, one task can work on positions 0 to n/2 and another task can work on positions (n/2) +1 to n-1, where n is the length of the array.
    • java.util.concurrent.RecursiveAction Subclass of the abstract task class, use it when you don't need the task to return a result, for example, when the task works on positions of an array, it doesn't return anything because it worked on the array. The method you should implement in order to do the job is compute():void, notice the void return.
    • java.util.concurrent.RecursiveTask Subclass of the abstract task class, use it when your tasks return a result. For example, when computing Fibonacci numbers, each task must return the number it computed in order to join them and obtain the general solution. The method you should implement in order to do the job is compute():V, where V is the type of return; for the Fibonacci example, V may be java.lang.Integer.

When using the framework, you should define a flag that indicates whether it is necessary to fork/join the tasks or whether you should compute the work directly. For example, when working on an array, you may specify that if the length of the array is bigger than 500_000_000 you should fork/join the tasks, otherwise, the array is small enough to compute directly. In essence, the algorithm you should follow is shown next:

if(the job is small enough)
{
   compute directly
}
else
{
   split the work in two pieces (fork)
   invoke the pieces and join the results (join)
}

OK, too much theory for now, let's review an example.

The Example
Blurring an image requires to work on every pixel of the image. If the image is big enough we are going to have a big array of pixels to work on and so we can use fork/join to work on them and use the processing resources to the maximum. You can download the source code from the Java™ Tutorials site.

Once you download the source code, open NetBeans IDE 7.x and create a new project:



Then select Java Project with Existing Sources from the Java category in the displayed pop-up window:



Select a name and a project folder and click Next >



Now, select the folder where you downloaded the source code for the Blur on an image example:



And select the file ForkBlur.java then click finish:



The source code will be imported and a new project will be created. Notice that the new project is shown with erros, this is because Java 7 is not enable for default:



To fix this, right click on the project name and select the option Properties. On the pop-up dialog, go to Libraries and select JDK 1.7 from the Java Platform ComboBox:



Now, go to the option Sources and select JDK 7 from the Source/Binary Format ComboBox:



Last but not least, increase the memory assigned to the virtual machine when running this application as we'll be accessing a 5 million positions array (or more). Go to the option Run and insert -Xms1024m -Xmx1024m on the VM Options TextBox:


Click OK and your project should be compiling with no errors. Now, we need to find an image bigger enough so we can have a large array to work on. After a while, I found some great images (around 150 MB) from planet Mars, thanks to the curiosity robot, you can download yours from here. Once you download the image, past it on the project's folder.

Before we run the example, we need to modify the source code in order to control when to run it using the Fork/Join framework. In the ForkBlur.java file, go to line 104 in order to change the name of the image that we are going to use:

//Change for the name of the image you pasted 
//on the project's folder.
String filename = "red-tulips.jpg";

Then, replace lines 130 to 136 with the following piece of code:

ForkBlur fb = new ForkBlur(src, 0, src.length, dst);
        boolean computeDirectly = true;

        long startTime = System.currentTimeMillis();
        if (computeDirectly) {
            fb.computeDirectly();
        } else {
            ForkJoinPool pool = new ForkJoinPool();
            pool.invoke(fb);
        }
        long endTime = System.currentTimeMillis();

Notice the computeDirectly flag. When true, we'll NOT be using the fork/Join Framework, instead we will compute the task directly. When false, the fork/join framework will be used.

The compute():void method in the ForkBlur class implements the fork/join algorithm. It's based on the length of the array, when the length of the array is bigger than 10_000, the task will be forked, otherwise, the task will be computed directly.

Following you can see my 2 processors when executing the Blur on an image example without using the Fork/Join framework (computeDirectly = true), it took about 14s to finish the work:



You can see that the processors are working, but not to the maximum. When using the Fork/Join framework (computeDirectly = false) you can see them working at 100% and it took almost 50% less time to finish the work:



This video shows the complete process:




I hope you can see how useful this framework is. Of course, you cannot use it all around your code, but whenever you have a task that can be divided into small tasks then you know who to call.

For more tutorials and information about concurrency in Java, check the Java™ Tutorials site.

see ya!


References:

The Java™ Tutorials. Oracle [online].
Available on Internet: http://docs.oracle.com/javase/tutorial/essential/concurrency/
[accessed on October 10 2012].

PHOTOJOURNAL. NASA Jet Propulsion Laboratory [online].
Available on Internet: http://photojournal.jpl.nasa.gov/catalog/PIA16101
[accessed on October 10 2012].

Monday, October 8, 2012

ADF Essentials

Hello all. Today I'm going to present you a great framework for bulding Rich Web applications with Java. It is called ADF Essentials and for those of you who haven't heard about it, let me tell you its benefits:
  • 150 Ajax-enabled JSF components.
  • Support for Skinning.
  • Visual and declarative development.
  • Free to develop and deploy.
  • Glassfish server officially certified, check the ADF Essentials product certification page.
  • Includes ADF Faces, ADF Data Visualization Tools (DVT), ADF Controller, ADF Model, ADF Share, and ADF Business Components. Check this page for a complete list of components included.
  • For more information and other benefits visit the ADF Essentials product home page.

The framework is built over JSF 2 so if you have previous experience in building Web applications using JSF you are likely to start developing with ADF Essentials pretty fast. On the contrary, if you are just beggining with Web development, the visual and declarative development this framework offers will let you build the application in a fast pace. Either case, there are tons of documentation online: books, tutorials and  videos to help you.

What you will need:

I've been using ADF Faces (which is the complete version of the framework) for the last 3 years and I can tell how easy it is to develop RIA (Rich Internet Applications) with it. In future posts I will show you how to deploy a Web application developed with ADF Essentials on Glassfish server and even on Tomcat (which is not yet officially supported).

Two things before we finish:
  • ADF Faces is the complete framework (which is free to develop but not free to deploy) and ADF Essentials is a subset of ADF Faces and is free to develop and deploy.
  • Check the following video from ADF Insider Essentials's channel on youtube so you can see the framework in action:




see ya!


References:

Oracle ADF Essentials. Oracle [online].
Available on Internet: http://www.oracle.com/technetwork/developer-tools/adf/overview/adfessentials-1719844.html
[accessed on October 06 2012].

Friday, October 5, 2012

My "Make the Future Java" Tool Kit arrived!

Hello all. I want to share with you that my "Make the Future Java" Tool Kit just arrived! It took about 15 days to travel from Redwood, CA to Colombia, but it's finally here and I'm going to show you what's inside.

Make the Future Java motivates each of us to share our knowledge and to inspire future technologists to learn more about Java. You can order your Tool Kit too, is FREE. For more information, please visit the program website.

So what's inside? According to Oracle: "The Make the Future Java Tool Kit contains both learning resources and Java branded materials to give your outreach project more impact". It comes with a nice T-Shirt, postcards, posters and DVDs with the following:


All the tools, tutorials and HOL (Hands On Lab) are available online as well. I'll be posting about our JUG meetings and events where we Make the Future Java. Remember, You can help too, order your Tool Kit and inspire others!

see ya!!




Friday, September 28, 2012

Decorator Pattern and Java

So, you want to extend behavior but want to avoid subclassing? Then the Decorator Pattern is for you. Decorators change behavior by adding new functionality to the components they decorate without modifying those components. This pattern is based on the Open-Closed OO principle:
Classes should be open for extension but closed for modification.
Designs must be flexible and opened for behavior extension but without modifications to existing code. That way, you avoid introducing new bugs to previous tested and reliable code. Let's check the definition of the Decorator pattern, according to the Head First Design Patterns book:
Attach additional responsabilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
And the basic class diagram for this pattern is as follows:


Let's review each class from the above diagram:
  • Component: Most of the time it's an abstract class with abstract methods. Represents the base class of the hierarchy.
  • ConcreteComponent: Concrete class that implements the methods from the abstract Component class, during the implementation of the methods you should define default behavior.  It's the real class you want to decorate. You may have as many ConcreteComponent classes as you need.
  • Decorator: Base class for decorators, it's abstract so decorators are required to implement the abstract methods. It's composed with a reference to the Component class, so decorators may access the object they are decorating. Notice that both ConcreteComponent and Decorator subclass the Component class, that way decorators may be transparent to you, I mean, you are going to have a reference to a Component object and it may or may not be decorated, you just don't know (or care).
  • ConcreteDecorator: A concrete decorator that implements the methods from the abstract Decorator class. It's the class that executes the real job of decorating. It can access the object it is decorating.  You can have as many ConcreteDecorator classes as you need.

OK, that's kind of confusing, I know. Let's see a real example of the Decorator pattern in action so you can understand the concept. If you have used the java.io API you have already used this pattern, just think about opening streams from a file:

//in a class...
public void printLines(String file) throws Exception
{
  DataInputStream rin = null;
  rin = new DataInputStream(new FileInputStream(file));

  //more code...
}

The last piece of code is making use of the Decorator Pattern, it is decorating a java.io.FileInputStream so we can read primitive Java data types instead of bytes. Let's review the most important points:

As you can see, every decorator adds behavior to a component (in this case to a FileInputStream so it can read primitive Java data types). The following diagram was generated using Architexa's Free Tool for Understanding Code and it shows the relations between the input-stream classes we were talking about (and some others) and we can see the exact same structure of the Decorator Pattern:


Something to be aware of is that every decorator is another class in your design, so if you have a lot of decorators, your design will have a lot of small classes and it may become complex.

One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.


See ya!

References:

Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Wednesday, September 26, 2012

Observer Pattern and Java

"Don't call us, we'll call you"... that's the Hollywood OO (Object Oriented) Principle and it's exactly what the Observer pattern is about. In this post we'll review this pattern and how it is used in Java, you may already have used it without knowing...

According to Head First Design Patterns book, this is the definition of the Observer pattern:
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
Sounds familiar? Have you ever worked with Swing? Looks like the event handling mechanism is using the Observer Pattern. Let's think about it, suppose you have a JButton and you want other objects to be notified when the button is pressed... have you done that? sure! The other objects are not asking all the time to the button whether it is pressed or not, they only wait for a notification from the button. Swing does it using the java.awt.event.ActionListener, but in essence it is using the Observer Pattern, even if we are not using  interfaces like java.util.Observer or classes like java.util.Observable...

Now, talking about observers and observables, this two exist since JDK 1.0 and you can use them to implement the Observer Pattern in your applications. Let's see the how to do it:

The objects you want to be waiting for notifications are called Observers, they implement the interface java.util.Observer. This interface defines only one method: +update(Observable,Object):void which is called whenever the observed object is changed. The first parameter, an Observable, is the object that changed. The second parameter may be used as follows:

  • If using PUSH notifications, the Object parameter contains the information needed by the observers about the change. 
  • If using PULL notifications,  the Object parameter  is null and you should use the Observable parameter in order to extract the information needed.

When to PUSH or PULL? It's up to your implementation. The Object you want to be observed is called the Observable and it has to subclass the java.util.Observable class. Yes, subclass. That's the dark side of the built-in implementation of the Observer Pattern in Java, sometimes you simply can't subclass, we'll talk about this in a minute... Once subclassed, you will inherit the following methods, among others:

  • +addObserver(Observer):void which adds the Observer passed in as parameter to the set of observers.
  • +deleteObserver(Observer):void which deletes the Observer passed in as parameter from the set of observers.
  • setChanged():void which marks the Observable as having been changed. This method is protected, so  you can only call it if you subclass the  java.util.Observable class. Call it before notifying your observers.
  • +notifyObservers():void which notifies the registered observers using PULL. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be null.
  • +notifyObservers(Object):void  which notifies the registered observers using PUSH. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be the same parameter passed in the +notifyObservers(Object):void .

So, what happens if the class you want to be the Observable is already subclassing another class? Well, then you have to write your own Observer Pattern implementation because you can't use the one built-in Java. The following diagram shows you the basic concepts of the Observer Pattern, so you can built your own implementation:


One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.


See ya!

References:

Freeman Eric and Freeman Elisabeth and Sierra Kathy and Bates Bert (2004). Head First Design Patterns. United States of America: O'Reilly Media, Inc.

Duke's choice award 2012 is coming to LAD

Duke's Choice Award 2012 LAD
Hello all, I have great news!! The tenth year running Duke's choice award program is expanding and will focus on regional winners from Latin America (LAD), Europe Middle East Africa (EMEA), and Asia. The goal of the regional awards is to celebrate Java innovation happening within specific regions and provides an opportunity to recognize winners locally.

The program looks for the most compelling implementations of Java technology. Innovation is the only criteria. The nomination form can be found on the Duke's Choice Java.net site

Winners will be announced on stage during JavaOne LAD (Brasil) December 4th through 6th, and will also be featured in the January/February issue of Java Magazine. Winners will receive a free JavaOne LAD full conference pass and a Duke's Choice Award Statue.

So, you are in Latin America (LAD) and have an innovative Java project? what are you waiting for? The end date for nominations is October 30th, 2012.

Don't you know if you got what it takes? Check the 2011 winners (when there was only one global program).

more info: Duke's Choice Java.net site

see ya!

Monday, September 10, 2012

Java 7 conference for ASUOC

Colombia Oracle Users Group
Hello all, I'm attending a Colombia Oracle Users Group meeting this week and I'll be speaking at it about Java 7, so if you are around, please come and join us. You can also watch the event via streaming at ASUOC's web site. I will be speaking at the event presenting Project Coin, NIO.2 and the Fork/Join Framework.

The information of my presentation is as follows:

LanguageSpanish
WhereICESI University
Auditorio Varela S.A.
Cali, Colombia
WhenSeptember 13th 2012
16:00 - 17:30 (GMT-5)

More info (in spanish):

Colombia Oracle Users Group
ICESI University

See ya!


Thursday, August 23, 2012

Head First Design Patterns Book Review

Book cover from
http://www.headfirstlabs.com
I guess every software engineer should know about design patterns, they give us a way to solve design problems based on the experience of many other software engineers who have had the same or similar challenges in OO design. To be honest, I remember studying them during my B.S., applied some of them in my projects, but after years of experience in software development, is now that I realize how useful they may be. In this post I'm going to review the book "Head First Design Patterns", written by Eric Freeman, Elisabeth Robson, Bert Bates, Kathy Sierra and published by O'Reilly.
As others "Head First" titles, this book is well written, easy and funny to read, it has a lot of graphics, jokes, examples in the book and on the web site to be downloaded... I just loved it! Click here to know why Head First books are great.

The book covers the following design patterns:
  • Observer: Subscribe to receive updates when object's state changes.
  • Decorator: Wraps an object to provide new behavior.
  • Factory: When you want to encapsulate instantiation.
  • Singleton: Ensures one and only one of a kind.
  • Command: Encapsulates a request as an object.
  • Adapter: Wraps an object and provides a different interface to it.
  • Facade: When you need to simplify the interface of a set of classes.
  • Template Method: Subclasses decide how to implement steps in an algorithm.
  • Iterator: Allows to traverse a collection without exposing its implementation.
  • Composite: When you need to treat collections of objects and individual objects uniformly.
  • State: Encapsulates state-based behaviors and uses delegation to switch between behaviors.
  • Proxy: When you need to control access to an object.
  • Some other patterns: Bridge, Prototype, Interpreter, Chain of responsibility, mediator, etc.

Each pattern is explained in detail using an application sample in what they have called "ObjectVille". They also give you examples of its use in real life and its class diagram. Each chapter has a summary at the end (they've called it "Tools for your Design Toolbox") with the most important concepts and definitions.

Many of the above patterns were discovered by the Gang of Four (GoF), who were the first ones in writing about this topic back in 1995. Since then, new patterns have been discovered (yes, they are discovered not created), this book guides you to other reading materials where you can find more design patterns, shows you how looks the formal documentation of a pattern and describes the steps you should consider if you discover new ones.

But it is not all about design patterns, the book also explains the Object Oriented Design Principles (OODP) that every software engineer must know in order to design extensible and maintainable software:
  • Encapsulate what varies
  • Favor composition over inheritance
  • Program to interfaces, not to implementations
  • Strive for loosely coupled designs between objects that interact
  • Classes should be open for extension but closed for modification
  • Depend on abstractions. Do not depend on concrete classes
  • Only talk to your friends
  • Don't call us, we'll call you
  • A class should have only one reason to change

Something really important I learned with this book is: Always use the simplest solution that meets your needs, even if it doesn't include a pattern. So don't try to fill your design with patterns all around, first try using the Object Oriented Design Principles (OODP) then, if necessary, make use of patterns.

One more thing, the book is published in a lot of formats: printed book, kindle, PDF, so you have many options to read it. I have the kindle edition and it looks pretty much the same as in PDF. The kindle edition is available only on Kindle Fire, iPad, PC and Mac (not the portable kindle device).

In future posts I'll write about these patterns and how they are applied in the Java API.


See ya!!

Tuesday, June 26, 2012

Campus Party Colombia 2012 - CPCO5

Hello all, Campus Party Colombia (#CPCO5) is ON!! and I'm having a Java 7 presentation at this event, so if you are around, please come and join us. I will be speaking at the event presenting the Colombia Java Users Group and talking about Project Coin and NIO.2.

The information of my presentation is as follows:

LanguageSpanish
WhereCorferias
Innovation/Development Section
Bogotá, Colombia
WhenJune 28th 2012
9pm-10pm (GMT-5)

More info (in spanish):

Colombia Java Users Group official web site
Campus Party Colombia

See ya!


Sunday, February 5, 2012

JavaCup 2012 - Java Hispano

Hi all, I just wanted to share with you a cool Java Tournament called JavaCup 2012 which is presented by JavaHispano (an hispanic java community).


What you need
JDK 5+


The idea
It's a soccer tournament, where you have to program, in java (JDK 5+), the behaviour of your team. It's based on a framework, so you just have to implement interfaces from that framework in order to define the behaviour of your players during the match.

The idea is simple, there are situations in the match that are passed to the methods in your classes and you have to decide what to do in such situations. There is a tool that helps you to create the team, players, etc. The same tool simulates a match using the code you just wrote. The API is easy to use and remember:

You do not have to create the graphics or write the code to render the match, the framework does it for you!

Prices are in cash, first price is 1000€.
Deadline is March 9th 2012 23:59:59 (UTC + 1) (check this link in order to convert timezones)

Here is a presentation of the tournament:




I'm in for the tournament, hope to see you around!

bye.


References:

JavaHispano.[online].
Available on Internet: http://www.javahispano.org/
[accessed on February 3rd 2012].

JavaCup 2012. JavaHispano [online].
Available on Internet: http://javacup.javahispano.org/
[accessed on February 4rd 2012].

Tuesday, January 24, 2012

Java 7 - Project Coin Decompiled

Hi all, it's time to start writing in 2012. As you may have seen already in other blogs, there are a few changes that can make your developer life a lot easier when programming in Java: diamond operator, Strings in Switch, try with resources, multi catch, etc. In this post (PART I) we are going to see some of the small changes presented in Java 7 Project Coin (JSR 334) and then (in PART II) we are going to decompile them in order to see what's the compiler doing (for educational purposes only).


What you need
NetBeans 7+ or any other IDE that supports Java 7
Diamond Operator
Generics helped us to reduce ClassCastExceptions among other things, but some times it can make the code hard to read. Diamond operator is a really nice change. Imaging that you need to group customers by city. You would need something like this:

//suppose the classes City and Customer exist
...
Map<City,List<Customer>> map = new HashMap<City,List<Customer>>();
...

Now, what if you also need to group the data by country:

//suppose the classes Country, City and Customer exist
...
Map<Country,Map<City,List<Customer>>> map = new HashMap<Country,Map<City,List<Customer>>>();
...

Now, it starts to be very hard to read, right? What if you also need to group by Region?

//suppose the classes Region, Country, City and Customer exist
...
Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<Region, Map<Country,Map<City,List<Customer>>>>();
...

So what do you think? It's not easy at all to read code like that. Fortunately, the new Diamond Operator helps a lot in the readability of code. The last code can be recoded in Java 7 like this:

//suppose the classes Region, Country, City and Customer exist
...
Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<>();
...

A lot better!


Strings in Switch
I've been waiting for this a lot!!! I remember the days when I was starting in the Java world and I really needed to use Strings in switch. Well, my  waiting is finally over. In earlier versions of Java you had to write something like this:

//in a class
...
public void stringToNumber(String str)
{
   if(str.equalsIgnoreCase("one"))
   {
      System.out.println(1);
   }
   else if(str.equalsIgnoreCase("two"))
   {
      System.out.println(2);
   }
   else if(str.equalsIgnoreCase("three"))
   {
      System.out.println(3);
   }
}
...

In Java 7 you can write it like this:

//in a class
...
public void stringToNumber(String str)
{
   switch(str)
   {
      case "one":
         System.out.println(1);
         break;
      case "two":   
         System.out.println(2);
         break;   
      case "three":
         System.out.println(3);
         break;
   }
}
...

Even NetBeans has an option to convert it automatically:





Try with resources and Multi Catch
This is a nice enhancement in this version, now you don't have to worry about closing those ResultSets, Statements, FileInputStreams...etc. You just need to use the new try structure and the compiler will care about it for you. You can even create your own classes to be Closeable (this is a new interface) by the new try structure. Following is a classic file access via streams:

//in a class
import java.io.*;
...
public static void copyFile(String path) 
              throws IOException, NullPointerException 
{
        File file = new File(path);

        FileOutputStream fout = null;
        FileInputStream fin = null;
        try {
            try {
                fout = new FileOutputStream("file.dat");
                fin = new FileInputStream(file);

                byte[] bytes = new byte[1024];
                int leido = 0;
                while ((leido = fin.read(bytes)) != -1) {
                    fout.write(bytes, 0, leido);
                }
            } finally {
                if (fout != null) {
                    fout.close();
                }
                if (fin != null) {
                    fin.close();
                }
            }
        } catch (NullPointerException ex) {
            ex.printStackTrace();
            throw ex;
        }catch (IOException ex) {
            ex.printStackTrace();
            throw ex;
        }
    }
...

If you notice, in order to be sure that the opened Streams are being closed once they finish, you have to code a try/finally block and close them by yourself. In Java 7, you can achieve the same behaviour in a better way and with less lines of code using the new try structure and the new NIO.2 classes:

//in a class
import java.nio.file.*;
import java.io.*;
...
public static void copyFile(String src) 
              throws IOException, NullPointerException 
{
        Path path = FileSystems.getDefault().getPath(src);
        
        try (FileOutputStream fout = new FileOutputStream("file.dat")) {
            Files.copy(path, fout);
        } catch (NullPointerException | IOException ex) {
            ex.printStackTrace();
            throw ex;
        }
}
...


Binary literals and underscores in literals
Now you can express an integer as a binary literal, this is ideal when programming low-level APIs, also you can use underscores in order to make your values more readable:

//in a class
...
public static void coin() 
{
   int binaryNum = 0b10; //This is number 2 in binary code

   double value1 = 1000000000; //hard to read?
   double value2 = 1_000_000_000; //Easy to read with Java 7

   double value3 = 0b101010110111; //hard to read?
   double value4 = 0b1010_1011_0111; //Easy to read with Java 7

   double pi = 3.14_15_92; //another example of readability
}
...

So, less code, more productivity and a better code readability that's what Project Coin is about! (Among other things not seen here).

That's it for PART I of this post, in PART II we are going to see what's the compiler doing when we Decompile the code we have seen here.


References:

Overview of JDK 7 Support in NetBeans IDE. NetBeans [online].
Available on Internet: http://netbeans.org/kb/docs/java/javase-jdk7.html
[accessed on January 22 2012].