Friday, December 14, 2012

How to generate hashed passwords with JBoss

If you want your JBoss to hash passwords for you can do it using the command line

In linux
java -cp client/jboss-logging-spi.jar:lib/jbosssx.jar djordje

In windows
java -cp "c:/opt/jboss/lib/jbosssx.jar;c:/opt/jboss/client/jboss-logging-spi.jar" djordje

Here a print screen of how to use the cygwin terminal in windows to hash the password:

Sunday, November 18, 2012

Fancy a cup of tea?

In most parts of Eastern Europe, they often drink it with lemon and honey,
in India with milk and cardamom,
in Spain they drink it just with sugar,
in Ireland they drink it with milk and some people with a fascinating new taste called brown sauce (If you dont belive me see this movie: Intermission).

But in all cases the recipe has 2 mandatory components:
  1. Boiling water
  2. Tea

In this video I am going to talk about a new design pattern that was created by Marco Castigliego, called
"The Step Builder".

"The Step Builder" is a variant of the creational pattern "Builder".
The advantages of using Castigliego's pattern are:

  • The user will see only one or few selected methods per time during the Object creation.
  • Based on the user choice different paths can be taken during the Object creation.
  • The final build step will be available only at the end, after all mandatory steps are completed returning an Object in a consistent state.
  • The user experience will be greatly improved by the fact that he will only see the next step

 methods available.

More information about this pattern and also a wiki definition of it can be found at Marco Castigliego's blog: Remove duplications and fix bad names

 Note: Don't forget to select the maximum quality in the video player

Monday, November 12, 2012

The all mighty regex

We often use regular expressions when programming.
In many occasions they make our live easier and help us avoiding lots of lines of code. I was just navigating around, and by a chance I found a blog that shows probably the one of coolest regex.
Have a look at this regular expression:

Personally I never used this one before. The thing that I find cool about it is, its simplicity.
For those who are not familiar with regex terminology, this one matches a character that is within(inclusive )the characters SPACE and tilde in the ASCII table.

Hehe.. cool, isn't it? I am looking forward to use it somewhere.

I can't resist, let's just give it a quick try :)

1:  import java.util.regex.Matcher;  
2:  import java.util.regex.Pattern;  
3:  public class AllMightyRegex {  
4:       public static void main(String[] args) {  
5:            String someASCIICharacters = "!#$%&\'()*+,-.0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";  
6:            Pattern pattern = Pattern.compile("[ -~]");  
7:            Matcher matcher;   
8:            for (int variableIndex = 0; variableIndex < someASCIICharacters.length(); variableIndex++) {  
9:                 matcher = pattern.matcher(getCharAt(someASCIICharacters, variableIndex));  
10:                 if(matcher.matches()) {  
11:                      System.out.println("The character: " + getCharAt(someASCIICharacters, variableIndex) + " matches the pattern");  
12:                 }  
13:            }  
14:       }  
15:       private static String getCharAt(String someASCIICharacters,  
16:                 int variableIndex) {  
17:            return someASCIICharacters.charAt(variableIndex) + "";  
18:       }  
19:  }  

Tuesday, November 6, 2012

How to print into a remote application server log with eclipse.

  1. From the debug perspective access the debug configurations
  2. Use the Remote Java Application option in the debug menu to create a new debug configuration.
  3. Enter the ip of the remote host and the debug port.
  4. Click on Debug
  5. Once the debugger is hooked, open the display view
  6. Type the command you want to execute and execute it.
  7. tail -f of vi into server.log file to see the results

Thursday, November 1, 2012

How to conquer the world? Well... you need a strategy

This weekend i went through old notes i had on  my hard disk, I wanted to refresh my mind about some design patterns.
Patterns is a topic I like very much and from my point of view they represent some foundation which is mandatory to understand if we want to have better understanding of software architectures.
The most popular authors that wrote about design patterns are known as GoF (Gang of Four), we could say that they are the icon every developer looks at when talking about design patterns. Their writings are present in almost every university and in many occasions are even a mandatory subject(Well.. at least it was in mine :) ).

I think the "Strategy" pattern was the first, or at least one of the first patterns i studied when I started with java. Also i noticed the large amount on articles on the web about this pattern.
Here a really good one you can read latter (But for now, focus on my one ;) ).

So since this pattern is so popular, and interesting, maybe it deserves a post.
Also since there are many articles on this topic already on the internet and all of them are very similar, I thought about making a little surprise at the end of my  presentation, to make it more fun and beautiful.
I hope you like it.

Note: Don't forget to set the quality to HD in the video player

Saturday, October 20, 2012

static factory methods, an alternative to public constructors

The most widely used technique to allow other parts of our programs, to get objects of a certain type, is to create public constructors.

1:  public class Product {  
2:        //..  
3:        public Product() {  
4:        }  
5:       //..  
6:  }  

There is also another technique that provides various advantages and it would be highly recommendable for every programmer to know.
Classes can provide static factory methods. This methods are another way of returning instances.

1:  public class Product {  
2:      //..  
3:        private int price;  
4:        private String description;  
7:        private Product(int price,String description) {  
8:              this.price = price;  
9:              this.description = description;  
10:        }  
11:        public static Product getNewProduct(int price,String description) {  
12:              return new Product(price,description);  
13:        }  
14:      //..  
15:  }  

This are some of the advantages of using this technique:

Methods have names, so we can be more descriptive when constructing our objects.
Constructors cannot have names, but methods can, so by having this types of methods we can express more fluently how the object is constructed.
So instead of this:

1:  new Product("ProductA",12);   

We can create our objects like this:
1:  Product.getNewProductWithValues("ProductA",12);  

We don't have to create new objects if we don't want to. 
Every time the keyword new is called, a new instance is created. In many occasions, specially in large systems, programmers need to be careful with resources. Some techniques to do that are:
-having cached objects and manage that they are cleaned properly.(Google for Singleton pattern).
-work with immutable objects which provide predefined state.(Google for Builder Pattern)
In the following piece of code you will see a very trivial implementation of a cached object:

1:  public class Product {  
2:        private static Product product = new Product();  
3:        private Product() {  
4:        }  
5:        public static Product getDefaultProduct() {              
6:              return product;  
7:        }  
8:  }  

This type of methods can have a subclass as a return type.
By using this type of methods, we can have big flexibility because we can use sub-classes as return types.
This is a very interesting feature which can allow us to create very powerful factories:

In the following example you can see how the static factory method can be used to create instances of subtypes or implementing types.
1:  public final class ProductFactory {  
2:        public static Product getProduct(boolean condition) {  
3:              if(condition) {  
4:                    return new HomeMadeProduct();  
5:              }  
6:              else {  
7:                    return new FactoryMadeProduct();  
8:              }  
9:        }  
10:  }  


Saturday, October 13, 2012

Installing maven in windows

Very brief video that just shows how simple it is to install the latest maven in a windows system.

Note: Don't forget to set the quality to HD in the video player

Sunday, August 26, 2012

Use a martial arts principle to improve your Test Driven Development skills.

In ancient Japan, martial arts were not just defence techniques, they were also  a way of life(jap. budo”).
In this way of life they combined physical, moral and spiritual dimensions with the goal of self-improvement.

Since very young, Japanese kids would join a martial arts school, to study: karate, aikido, judo…  
They learned martial arts using a technique called “Kata”.

The “Kata” technique was based in the principle of “learn by repetition”.
By practicing exercises in a repetitive maner the learner  comes to a point where develops the ability to execute those exercises and movements in a natural and reflexive maner(“intuition”).

Today in software development the amount of trainers that recommend to use Test Driven Development Katas, is increasing.  Some would even say that the TDD katas, are the only way to learn TDD.  The original idea of the kata as a maner of learning software development was introduced by Dave Thomas(author of: The pragmatic Programmer: From Journey man to Master ).

Programming principles such as KISS(Keep It Simple and Stupid) or YAGNI(You Ain’t Gonna Need It ) are very common in the TDD philosophy, but the main mantra behind TDD is the RGR principle (Red, Green, Refactor).

From the theoretical point of view, the RGR principle seems often very simple to new TDD developers.
But when it comes to real life practice, in many occasions the complexity of the software can make less experienced developers to panic.

A great practice to avoid this is to practice a TDD kata once in a while.
Peter Norvost(author of the blog: Geek Noise), recommends to new TDD developers to do simple katas of 30 minutes every morning for 2 weeks. 
Now I will show you an example of a very simple TDD kata and then I will perform a demonstration.

KATA #1: THE STRING CALCULATOR (Kata description taken from:
1-An empty string returns zero
2-A single number returns the value
3-Two numbers, comma delimited, returns the sum
4-Two numbers, newline delimited, returns the sum
5-Three numbers, delimited either way, returns the sum
6-Negative numbers throw an exception
7-Numbers greater than 1000 are ignored

Note: Don't forget to set the quality to HD in the video player

Monday, August 13, 2012

Subversion Native Library Not Available

Did you ever have to deal with this annoying Subversion update message when Starting your Eclipse IDE?

To avoid it popping up, just go to your preferences and change the SVN interface.

Friday, August 10, 2012

Dynamic initialization of HashMap using double braces

Often we have to work with data structures like: Maps, Arrays,Sets...
And many times it is just more comfortable to initialize them dynamically.

In the following example i use double brace initialization technique to dynamically initialize a map that uses a constant as a key and a List as a value. When we want to initialize this types of structures in a dynamical way, this approach is probably the most comfortable and easy.

1:  new HashMap<ProductCategories, List<Products>>() {  
2:                 {  
3:                      put(ProductCategories.DAIRY_PRODUCTS,  
4:                                new ArrayList<Products>() {  
5:                                     {  
6:                                          add(Products.CHEESE);  
7:                                          add(Products.SOUR_CREAM);  
8:                                          add(Products.YOGURTH);  
9:                                     }  
10:                                 }  
11:                      );  
12:                      put(ProductCategories.MEAT,   
13:                                new ArrayList<Products>() {  
14:                                     {  
15:                                          add(Products.BEEF);  
16:                                          add(Products.CHICKEN);  
17:                                          add(Products.TURKEY);  
18:                                     }  
19:                                }  
20:                      );  
21:                      put(ProductCategories.VEGETABLES,   
22:                                new ArrayList<Products>() {  
23:                                     {  
24:                                          add(Products.TOMATO);  
25:                                          add(Products.ONION);  
26:                                          add(Products.CAGABE);  
27:                                     }  
28:                                }  
29:                      );  
30:                 }  
31:            };  

Sunday, June 10, 2012

Asynchronous communication with JMS(Java Messaging Service) - Part 1

Note: Don't forget to set the quality to HD in the video player

The JMS is a wide topic but that it is very important for a java developer to understand. The use of asynchronous processing in software development is very important and for many systems it is a must.

In this video i wanted to give some brief introduction to JMS and also do some simple to understand practical example that shows how different processes can be performed without the need of having both client and the server waiting for each other until a task is finished.

java, JMS, Queue, Java Messaging System, Asynchronous Processing, Tutorial

Wednesday, May 30, 2012

How many lines of java code does your workspace contain

Did you ever wonder how many lines of java code does your workspace have? Here a little program that can help you find out:

Class 1:

1:  package sample;  
2:  import;  
3:  import java.util.Scanner;  
4:  public class LinesOfCodeCounter {  
5:    private long linesOfCode;  
6:    private int scannedProjects;  
7:    public void analizeFolder(File file) {  
8:  //Check if the current file is a file or a folder  
9:      if (file.isDirectory()) {  
10:  //If it is a folder get the inner files  
11:        File[] filesInFolder = file.listFiles();  
12:  //For each of the inner files check if it is a folder or a file(Recursion)  
13:        for (File innerFile : filesInFolder) {  
14:          analizeFolder(innerFile);  
15:        }  
16:      } else if (file.isFile()) {  
17:  //When you find a file that is not a folder, check if it contains java code  
18:        if (file.getName().endsWith(".java")) {  
19:  //Scan the file  
20:          scanFile(file);  
21:        }  
22:      }  
23:    }  
24:    public void scanFile(File file) {  
25:      try {  
26:        Scanner fileScanner = new Scanner(file);  
27:  //Read each line of code  
28:        String tempDataHolder = fileScanner.nextLine();  
29:  //While the file contain lines of code count them  
30:        while (fileScanner.hasNext()) {  
31:          linesOfCode++;  
32:          tempDataHolder = fileScanner.nextLine();  
33:        }  
34:      } catch (Exception ex) {  
35:        ex.printStackTrace();  
36:      }  
37:    }  
38:    public long getLinesOfCode() {  
39:      return linesOfCode;  
40:    }  
41:  }  

Class 2:
1:  package sample;  
2:  import;  
3:  public class Main {  
4:    public static void main(String[] args) {  
5:      //The workspace root  
6:      final File workSpaceRoot = new File("D:\\JavaWorkspace");  
7:      //Check if the root contains files inside its self  
8:      LinesOfCodeCounter counter = new LinesOfCodeCounter();  
9:      counter.analizeFolder(workSpaceRoot);  
10:      System.out.print(counter.getLinesOfCode());  
11:    }    
12:  }  

Saturday, May 26, 2012

Clustering with Glassfish 3.1



 Here I use the command line to create a cluster in the application server Glassfish 3.1 and add 2 instances to it.
Once the cluster is created I deploy an enterprise application and run it in both instances.

Tuesday, May 1, 2012

File realm & role based security with Glassfish 3.1

Here in this video you can see how i create a simple security realm that uses a file in a safe place in the app server to store the credentials. One thing i forgot was to show you how to logout :)
Don't worry is not very difficult, for that you can implement your own logout servlet to invalidate the session.
Here is some example of code for logging out:

1:  @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})  
2:   public class LogoutServlet extends HttpServlet {  
3:   @Override  
4:   protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
5:    //Invalidates the session  
6:    request.getSession(false).invalidate();  
7:    // Redirects back to the initial page.  
8:    response.sendRedirect(request.getContextPath());  
9:   }  
10:   }  

Also here there is an image to show where can you enable HTTPS for the admin panel:

Note: The SSL certificate that comes with glassfish is expired that is the reason why you will see a warning message before you login.

Saturday, April 7, 2012

Using a fun chalk board to explain how a JEE6 application that uses web services should be organized

I have been studying JAX-RS the last 2 months and i found it very interesting. I wanted to create an interesting video where i explain one of the ways how the .ear application can be organized when using web services. I didn't know that Entities can behave also as JAXB objects. That make things a lot easier.
I think you will like this video, is interesting. It was to big to upload it at once so i divided.
This is the second part of the video. Here i am just showing the code, i am not programming because otherwise the recording would be too long.

I would like to know about what do you think of this architecture? What other alternatives do exist? What are the best practices? Please feel free to comment, i am very interested in reading your comments.

Wednesday, April 4, 2012

The use of marker interfaces

When programming, we often use interfaces, to hide the realization. But in some occasions, we want just want to group classes. We call marker interfaces, to empty interfaces(No methods at all). 

A very simple example is the Serializabe interface: 
It has no methods at all, but all classes that whant to be writen into some kind of file, or network stream, need to implement Serializable. 

In the same way, you could make a Program with classes like Dog,Bird,Cow... and you dont need to add them any functionality extra, just to mark them, because somewhere in the code there will be a method that could look like this : String method(Flyer); So you need to create a marker interface called Flyer, to mark the animals that can fly(So you dont need to have unnecesary variables boolean like isFlyer, in classes Dog and Cow). 

maybe i should give a more pragmatical example, so it is easier to understand. Lets try:

See the folowing code:

1:  //Marking interface flyer  
2:  public interface Flyer {  
3:  //If this is a marker interface, there is no methods in it  
4:  }  
5:  public class Mammal {  
6:  private String someVariable;  
7:  }  
8:  public class Cow extends Mammal {  
9:  //Some code specific to cows  
10:  }  
11:  public class Bat extends Mammal implements Flyer {  
12:  //Some code specific to Mammal  
13:  //Note that the Bat is marked as a Flyer  
14:  }  

I think this example more or less explains my point. Bats are mammals and can fly,so why would you have a boolean variable that can be either true or false, when you can just mark the class. Another reason why i think this is a good approach, i because if the future we need to upgrade the program, we can just mark the classes that can fly with the interface.

Imagine somewhere in the program there is a method like this:

1:  public class AirportControl {  
2:  public void testFly(Animal a) {  
3:  if(a instanceof Flyer) {  
4:  //Perform a test fly  
5:  }  
6:  public void testFly(Vehicle v) {  
7:  if(a instanceof Flyer) {  
8:  //Perform a test fly  
9:  }  
10:  }  

I think this approach is pretty flexible,when creating your domain model.

Monday, April 2, 2012

What is JAXP and what tools does it provide?

I had this video in my hard disk where i explain what XML parsers are and what java offer us by default to perform XML parsing.
I thought it may be handy if someone wants to get a brief  theoretical introduction to the world of  XML parsing using Java. There are lots of other tools out there for doing parsing with java, the video just mentions the ones that are included in the SDK.
If you want to know more, check out the resources:

Monday, March 12, 2012

How to increase performance on overridden methods.

All annotations resolve themselves at compile time, java features like inheritance and polimorfism resolve at runtime on client request.
So this means that things that are already resolved at compile time have a faster performance when the application is running latter.
A little trick to increase performance of overriden methods is to anotate them with the annotation @Override.

Share with your friends