zondag 9 december 2012

xml and java

Introduction:

There are several ways to deal with xml in Java. Depending on the requierements that are stated, you choose the weapons for your duel. Roughly you can divide the xml libraries that are available in Java in the following groups:

  1. Dom. Document Object Model.
  2. Marshalling
  3. Sax. Simple Api for Xml.
  4. Stax. Streaming Api for Xml.
  5. Xslt Extensible Stylesheet Language Transformations
The API's:
1. Dom:

These kind of API's create the full xml into memory and structure it in Java classes. The benefit of this is that all the information contained in the xml document is searchable and available. The downside is that, if there are several, bigger documents, it costs a lot of resources to work with it. 

Examples of Dom API's are:
2. Marshalling

Marshalling is the technique where an object (xml in our case) is transformed in a suitable and workable object which can be used for transformation or storage.

Examples of Marshalling libraries are:

3.  Sax. Simple Api for Xml.

A Sax parser  does not read the whole dom object into memory but reads as a sequential stream. This makes that the resource usage, compared to the dom parsers is significant less. The downside is, that you can retreive anything back from the top ones you passed it. It is event based.

Examples of Sax parsers:
4. Stax. Streaming Api for Xml.

Stax libraries are stuck in the middel of Sax and Dom. It is not designed to push the data from the xml stream to the application, but vica versa. It pulls the required data into the application from the xml stream. 

Examples of Stax parsers: 
Axiom (parses not only Stax)
woodstox 
jax


5.  Xslt Extensible Stylesheet Language Transformations

Xslt is a language which can do operations on a existing xml structure, and transform this into a new xml structure. In java this means that the xml file will be parsed by a sax parser like Xerces or Crimson. From here we can use the xslt language combined with xpath queries.

Examples of xslt parsers:


XDK

Conclusion

To work with Java and Xml you need to know want and what your  requirements are.
So, research and Have Fun.

woensdag 3 oktober 2012

Java Thread safely

Introduction.

The cycle of learning never ends but starts often.  In the case where threads are used It is an interesting cycle. One of the dangers of Java is that everybody can create and run threads. But the avoiding the pitfalls is needs a bit more experience.  So lets see what we can do to avoid the known pitfalls.

The pitfalls:
Lets make a list of some pitfalls:
  1. Use the Runnable Interface
  2. Granuality of the synchronized parts
  3. Static code
  4. Scoping the objects in the threads.
  5. Order of executing the threads 
  6. Setting members to Final

1. The Runnable Interface

This is important. Dont overload your class with unnecessary weight by letting it inherit from Thread.
Create a Thread and feed it with your object.

2. Granuality of the synchronized parts

You can ask yourself why is that important. You can say The more I have in my synchronized block the Less can go wrong. Or Why not the whole method that is easy and save anyway.
The consideration here is performance. Threads will wait on eachother when reaching a synchronized block. So the less you put in there the better it performs.

3. Static code:

Static code is something that gives a headache in multi threaded environments. It is on class level and not on an instance level. This means it is out of the scope of the ThreadManager and out of the scope of the garbage collector. My advice in most of the cases you setup an application, use it only when necessary and don't use it in a threaded envirnonment.

4. Scoping the objects in threads:

All the objects that are accesible in multiple threads should be scoped correctly. Public accessible member are also accesible over threads. This could give the case where you are using the synchronized block to prevent the threads to alter the values of the object while this is not necessarily.

5. Order of executing the threads

As you might create a number of threads, beware of the fact that in Java you cann't predict the order in which the threads will be executed.  To test copy my example and instancate the ThreadObject in multiple threads with different names.

6. Setting members to Final

The final keyword in Java is a debatable one. As it does not occur in the compiled code it seems to be useless for many developers. My personal opinion about it is: It is not useless it is a programmers safety net. You do not need it to be compiled. It is like a frontdoor lock. So even in the matter of threads we can set members to finalThis helps us to prevent other programmers to change the object. and leave them with nothing else then changing the values of the members of this object.

Example of a save thread:

public class NewThread {

     /** this one is running in the main thread to execute the application.
      *  Dont use it as something that lives in one of your threads.
      **/
     public static void main(String[] args){
         ThreadObject threadObject = new ThreadObject();
         threadObject.setName("Pieter");
         Thread thread = new Thread(threadObject);
         thread.start();
       
     }

public class ThreadObject implements Runnable {
    private String name;

    public String getName() {
        /**
         * HERE COULD HAVE BEEN SOME OTHER CODE
         */        synchronized (name) {
            return name;
        }
            /**
             * HERE COULD HAVE BEEN SOME OTHER CODE
             */       
    }

    protected void setName(String name) {
        /**
         * HERE COULD HAVE BEEN SOME OTHER CODE
         */
        synchronized (name) {
            this.name = name;
        }
        /**
         * HERE COULD HAVE BEEN SOME OTHER CODE
         */
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        System.out.println(getName());
    }

Have fun!

donderdag 27 september 2012

keep on scoping on different packages

Introduction:

Scoping the methods and constructors the right way can be quite a headache. In a lot of libraries I see that most of the classes are public accessable. This makes it for the user of those libraries confusing to use. So to keep myself in shape I write this little reminder.

Scoping
  1. Public methods and constructors are accesible everywhere in your application and also in the applications that are using your application as a library. 
  2. Protected methods are only accesible inside the package where the classes are and outside when inherited.
  3. Package aka scope or friendly, is only accesible inside the package including inherited. 
  4. Private is only accesible inside the class scope.
  5. Local is only accesible inside the method where it is declared. 
 Examples

Public class Scoping{
   public String publicScope; 
   protected String protectedScope; 
   String packageScope;
   private privateScope; 
}

If you write a library that can be used by others, I think with the design, the word userFriendly should be considered.
Beside good and working examples and completed documentation scoping can be helpfull. If your contract is one of the few things which is accesible, mistakes by your users (other programmers) are made less.

One of the last things I show as an example is a small trick to avoid using public when you are using classes from different packages:

package example.superclass;

public abstract class SuperClass{
  protected String protectedScope;

   protected String getProtectedScope{
     return this.protectedScope;
  }

  protected String setPrivateScope(String privateScope){
    this.protectedScope = protectedScope;
  }

 }

package example.subclass;

public  class SubClass{
   protected String getProtectedScope{
     return super.protectedScope;
  }

  protected String setPrivateScope(String privateScope){
    super.protectedScope = protectedScope;
  }

 }

package example.superclass;
public class callSubClassThroughSuperClass{
   SuperClass class = new SubClass();
   public static void main(String[] args){
      class.setProtectedScope("scope has been set");
      System.out.println(class.getProtectedScope);
   }
}
As you noticed are the class callSubClassThroughSuperClass and the SuperClass in the same package. This makes the protected methods of the SuperClass accesible for this class. The SubClass
is in a different package and accesses the protected methods through inheritence. This way you can bridge the distance between two packages and still use a scoping that protects usages from the outisde.

Have fun!

woensdag 19 september 2012

split a String and keep the token

Sometimes you want to split a String but still need the token for finding the parts you need. I setup an example to deal with this:

You have a String that contains a list of friends. All you want is to print out those names and not the first part of the String. 
    private void checkNames(){
        String name = "This is a list with friends, Fred, Ted, Robert,Maria, Roberta, Kaya";
        String splitExp = "(?=[:,])"; //The last char in the brackets [] is the token in our case the comma.
        String[] splittedNames = name.split(splitExp);
        for (int i = 0; i < splittedNames.length; i++) {
            if(splittedNames[i].startsWith(",")){
                //print it remove the comma and spaces
                System.out.println(splittedNames[i].substring(1).trim());
            }
}
       
This will give you a clean list of your friends names.
Have fun.

maandag 27 augustus 2012

JSTL Velocity or Freemarker

Introduction:

 After a couple of years of experience, I tried different ways to deal with beans and pages. There are many ways to deal with this. Most of the times I used JSTL, Freemarker, Velocity or the spring Taglibs. Now i am trying to get clear what is the best way of dealing I can use.

Why jstl:

I used jstl a lot for the coupling of the beans and the jsp's. This still gives you the freedom to use also the java  <%%> tags. In my opinion it is not wise to do this simply of the fact, that you run into the risk of starting to use business logic in the jsp's which is straight against the
mvc pattern and the multi tier architecture. The only real downside of the JSTL's for me: is that for different functions you need different libraries declared in your jsp:

- Core tags
- Formatting tags
- Sql tags
- xml tags



  • The only taglib I do not like to use is the sql tags. I believe that this kind of functionality should be left to handled by the persistence tier. 

    The conclusion for using JSTL is: It is a very usefull set of libraries which can help you to create a good separation of your model and view. It still offers a lot of freedom which should be handled thoughtfully. In an development tool as Eclipse you might experience that this tool does not see it as on the classpath and gives compile errors in that sense. At runtime this example will work.

    An examples:

    //This is the jstl import
    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
    //Looping through a list of names in the items you have//
    //to declare the full path. In this case it a list in the customer class.//
    <c:forEach var="costumerNames" items="${com.my.customer.names}">
         //printing the names in al HTML list.//
        <LI> <c:out value="${customerNames.name}"/> </LI>
    </c:forEach> 


  • Why 
    velocity

    Velocity brings you the freedom to use their templates only or embed them in a Jsp. The bridging between the model and view. The plus of Velocity against the JSTL is that it works in different areas of your application. You can as easily use it for pages as for the layout for automated emails. It has a lot more
    functionality which makes it much more flexible to work with. Instead of bringing extra technology into the Jsp, there is an template created a .vm file, wich is compiled into a view. 

    The conclusion:
    If there is a need for a lot of flexibility even in a legacy system where there are allready Jsp's velocity is a  flexible tool.
    • It adapts to many application areas
    • It offers a simple, clear syntax for the template designer
    • It offers a simple programming model for the developer
    • Because templates and code are separate, you can develop and maintain them independently
    • The Velocity engine easily integrates into any Java application environment, especially servlets
    • Velocity enables templates to access any public method of data objects in the context

    an example for a web app:
    The servlet.xml example:


     <!--    register servlet   
             dont take this part to letterly. This is als depending on the frontend
             framework you are using.
     -->
        
        <servlet>
            <servlet-name>applicationServlet</servlet-name>
            <servlet-class>my.velocity.VelocityServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>applicationServlet</servlet-name>
            <url-pattern>/myApplication</url-pattern>
        </servlet-mapping>
        
        <!--    mapping all .vm files to velocity servlets  -->
        <servlet>
            <servlet-name>velocity</servlet-name>
            <servlet-class>org.apache.velocity.tools.view.servlet.VelocityViewServlet</servlet-class>
            <!--    load my toolbox -->
            <init-param>
                 <param-name>org.apache.velocity.toolbox</param-name>
                 <param-value>/WEB-INF/toolbox.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>velocity</servlet-name>
            <url-pattern>*.vm</url-pattern>
        </servlet-mapping>
     
    The toolbo.xml example (place it in the WEB-INF):
    <toolbox>
        <tool>
            <key>date</key>
            <scope>application</scope>
            <class>org.apache.velocity.tools.generic.DateTool</class>
        </tool>
    </toolbox>
    The java part:
    In this part you have to create a bean with a member "name"  that has getters and setters. With whatever framework you use as frontend technology (serlets, struts,spring, etc...) set this as a request parameter with the name "name". This, 
    ofcourse comes back in the html. 
    The html part:
    <h2> $name is using velocity</h2>
    Why freemarker
    Freemarker is an template engine, which might be seen as simular to Velocity. The difference in what they 
    can do sits in the functionality they have. If you have light requirements Velocity is the answer
    to your question on the other hand if you like one of the following functionalities out of the box 
    you might consider using Freemarker:
     
    Number and date support
    • You can perform arithmetic calculations and comparisons on arbitrary number types, including the arbitrary-precision types, not just integers.
    • You can compare and display (format) date/time values.
    Internationalization:
    • You can format numbers locale-sensitively, based on a variety of built-in and custom number-formatting patterns.
    • You can format dates locale- and timezone-sensitively, based on variety of built-in and custom date-formatting patterns.
    • Identifiers (variable names) can contain non-English letters like accented letters, Arabic letters, Chinese letters, etc.
    Loop handling:
    • You can break out of loops.
    • You can access control variables of outer loops from bodies of inner loops.
    • You can test whether you are in the last iteration of the loop.
    Array handling on the template language level:
    • You can access array elements, both primitive and non-primitive by index using the familiar [i] syntax.
    • You can query the length of an array.
    Macros:
    • Macro invocations can pass parameters either by position or by name.
    • Macro parameters can have default values which are effective when the parameter is omitted on invocation.
    • Macro invocations can have a nested body (<@myMacro>body</@myMacro>) that can be called by the macro for processing.
    • Macros are plain variables, so you can select the macro to execute based on an expression, or pass a macro to another macro as parameter.
    • Invoke a macro that is defined later in the template.
    • Local variables in macros, and recursive invocation of macros. In Velocity it is now possible with the currently (Feb. 2005) not officially documented #local function.
    Name-spaces:
    • You can use multiple name-spaces for variables. This is invaluable when you build "macro libraries", because you can prevent name collisions with application specific variables or with variables of other macro libraries.
    Java-independent string, list, and map manipulations with built-in functions/operators:
    • You can turn a string upper-, lower-, or title-case, turn upper-/lowercase only the first letter, convert (escape) the string to HTML, XML, or RTF, extract substrings, split strings, query string length, find/replace substring, ...etc.
    • Access elements of lists by index, extract sublists, concatenate lists, query size of a lists, sort lists.
    • Access map elements by variable key, check if the map is empty, obtain the key or value list.
    Expose typos and other mistakes in template:
    • When you try to access an undefined variable, FreeMarker will not accept that silently. You can configure FreeMarker to stop template rendering with an error message, or skip the wrong part. In either case, FreeMarker will log the problem, so it does not remain hidden.
    • FreeMarker will throw an exception if you mistype a directive name, and will not print the statement silently to the output (unless you use the now deprecated non-strict syntax).
    Advanced rendering control:
    • You can enclose a block of template in a set of tags that will cause it to apply HTML escaping or XML escaping (or any other transformation you can express as a FreeMarker expression for that matter) on all interpolations (${foo}) in the block.
    • FreeMarker has transforms, which are blocks of template that when rendered, go through a transforming filter. Built-in transforms include whitespace compressor, HTML and XML escaper. Best of all, you can implement your own transformers as well (i.e. if you generate Java source code, you can write a Java code pretty-printer transform and insert it into the template). Naturally, transforms can be nested.
    • You can explicitly flush the output writer with a built-in flush-directive.
    • You can stop the rendering with a built-in stop-directive.
    Literals:
    • Beside the usual string, number, and boolean literals you can define list and map literals as well inside templates.
    • There is a support for all Java string literal escapes: \b, \t, \n, \f, \r, \", \', \\, also we support \xXXXX to specify characters with their UNICODE code.
    Advanced white-space removal:
    • FreeMarker consistently removes white-space (spaces, tabs and line-break) from lines that contain non-outputting FreeMarker tags only, thus eliminates most annoying, obviously superfluous white-space.
    • There are directives to explicitly trim lines from needless white-space, just for the extreme cases, when white-space is a real problem.
    Integration with other technologies:
    • You can use JSP custom tag libraries in templates.
    • You can work directly on Python objects.
    Powerful XML transformation capabilities:
    • As of version 2.3, FreeMarker has powerful new XML transformation capabilities that make it a viable replacement for XSLT. Though there have been some attempts to make Velocity more capable in this domain (i.e. DVSL) Velocity is not really competitive in this regard. In our view, it never will be unless certain improvements to the core engine are made, such as support for macro libraries mapped to namespaces, and local variables in macros.
    Advanced template metaprogramming:
    • You can capture the output of an arbitrary part of the template into a context variable.
    • You can interpret arbitrary context variable as if it were a template definition.
    • You can imagine what can you do when you combine the two...
     
      An example:

     The java class:
         //Freemarker configuration object
            Configuration cfg = new Configuration();
            try {
                //Load template from source folder
                Template template = cfg.getTemplate("src/helloworld.ftl");
                 
                // Build the data-model
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("message", "Hello World!");
                //List parsing
                List<String> countries = new ArrayList<String>();
                countries.add("India");
                countries.add("United States");
                countries.add("Germany");
                countries.add("France");
                 
                data.put("countries", countries);
                 
                // Console output
                Writer out = new OutputStreamWriter(System.out);
                template.process(data, out);
                out.flush();
                // File output
                Writer file = new FileWriter (new File("C:\\FTL_helloworld.txt"));
                template.process(data, file);
                file.flush();
                file.close();
                 
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        }

    The ftl Code:

    <#list countries as country>
        ${country_index + 1}. ${country}
    </#list>
    The output:
       1. India
       2. United States
       3. Germany
       4. France
    I hope this helps to choose the tool you need. I started out a new project and decided to use the jstl and the spring taglibs. They provided me with all I need.
    But if I need something heavier the next time I might use Velocity or Freemarker to suit my needs.
    Have fun!
     
    
    

    maandag 6 augustus 2012

    resizing images on the fly

    Intro:

    After determining where the files are and how to move them into another folder as I showed in my previous post Howto create a set of files on the fly, It is fun to resize the files which are images in this case (makes it easier).

    The problem:

    We have a set of images, which might change and dont want to resize them by hand everytime.

    The solution:

    The solution lies hidden in Java as many times. The following example shows howto resize:



    private void createIcons(String path){
        int width=100;
        int height = 100;
        File imageInput = File(path);
       ImageIcon imageIcon = new ImageIcon(path);
       BufferedImage imageResize =
      new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics2D graphics2d = imageResize.createGraphics();
      graphics2d.addRenderingHints(
       new RenderingHints(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY));
       graphics2d.drawImage(imageIcon.getImage(), 0, 0, height, width,
       null);
       String iconName = path.replaceAll(
       IMAGES, ICONS);
       try {
          ImageIO.write(imageResize,
          "png", new File(iconName));
        }
        catch (IOException ioe) {
          LOGGER.error("The image " + iconName + " could not be saved!");
        }
    }

     In my previous post I had a line "String filePath =path.replace(IMAGES, ICONS); " all you have to do is to replace that line with:  "createIcons(image.getAbsolutePath());" and you be on your way with a full subset of folders and resized images. The only kind of images I had it never working with was BMP.

    A working version or the sources you can download from:
    http://sourceforge.net/projects/imageicon/files/imageicon-1.0-SOURCES.jar/download

    Or check out the sources from:
    ssh://git.code.sf.net/p/imageicon/code

     have fun.

    zondag 22 juli 2012

    Howto create a set of files on the fly (after the folders)


    Intro
    In this blog I would like to show what is the easiest way in java to create a set of files after we create the folders see my previous post howto create set of folders on the fly.

    The problem.

    We determined the folders we want to rename and fill them up with files. The first part I described this part is al logical follow up.

    The solution

    The filter we are going to use at this point, is at file level The filter would look something like this:

    package com.hanichi.webshop.controller.image.resize;

    import java.io.File;
    import java.io.FileFilter;
    import java.io.FilenameFilter;
    import java.io.IOException;

    public class ImageFilter implements FileFilter {
    private final static String FILE_NAME_POST_FIX = "png";

    @Override
    public boolean accept(File pathname) {

    return pathname.getAbsolutePath().endsWith(FILE_NAME_POST_FIX);
    }

    }

    for (File folder : imagesFolders) {
       ImageFilter imageFilter = new ImageFilter();
    File[] images = new File(folder.getAbsolutePath()).listFiles(imageFilter);
       String path = image.getAbsolutePath();
    for (File image : images) {
         if(image.isFile()){
           String filePath =path.replace(IMAGES, ICONS); 
          }
    }
    }
    }

    This is a very fast way to code in short time how to copy and rename files.

    Have fun!

    vrijdag 20 juli 2012

    Howto create a set of folders on the fly

    Intro
    In this blog I would like to show what is the easiest way in java to create a set of folders.
    I took for this example the folder structure of images and created the icon folders for them (lazy as I am :-) )

    The problem
    The structure of my images folders would be:

    images/image_galery_1
    images/image_galery_2
    images/image_galery_3
    images/image_galery_4.

    In the past I would loop through the forrest of folder to find these four. There is a much easier way and copy them with other names:


    The solution
            FilenameFilter imageFilter = new ImageFilter();
            File[] imagesFolders = new File("images",.listFiles(imageFilter);

    java.io.FileNameFilter is a standard java interface that helps you to identify the folders you looking for. Create a class yourself that implements this Interface. The class would look something like this:

    public class ImageFilter implements FilenameFilter {
        private static final String FOLDER_PRE_FIX="image";

        @Override
        public boolean accept(File dir, String name) {
            boolean fileImage=false;
            if(name.startsWith(FOLDER_PRE_FIX)){
                fileImage=true;
            }
            return fileImage;
        }

    In this example I just used a simple 2 layered folder structure. You can imagine that in a more complex structure this way realy is helpfull.

    After running this loop you automated the creation of the icon folders with minimized lines of code :
        private static final String ICONS = "icons";
        private static final String IMAGES = "images";

    Looping through the results  the following way:
            for (File file : imagesFolders) {
               //Just to be sure nothing slips through.
                if(file.isDirectory()){
                    String filePath = file.getAbsolutePath().replace(IMAGES, ICONS);
                    File iconsFolder = new File(filePath);
                    iconsFolder.mkdirs();
                }

    have fun!

    woensdag 20 juni 2012

    maven and local selenium tests

    INTRODUCTION:

    Running selenium tests are a must have these days. There are a couple of ways to deal with that The two I know are:

    1. The selenium plugin in Firefox or any other browser
    2. Howto make them run in Eclipse with maven.

    the second one is the one I am going to describe. 

    DESCRIPTION


    1. First of all you have to download eclipse at:
        http://www.eclipse.org/downloads/

    2. Install it where you like and install the two maven plugins you need:
        A. Goto help, Eclipse MarketPlace and type Maven in the searchbox on top.
        B. Install the "Maven Integration for Eclipse WTP".
        C Install the "Maven Integration for Eclipse"
        D Go back to the Eclipse MarketPlace and search for the testNG plugin. Install this to. 

    3. Now comes the exciting part Setting up an environment that helps you to run the selenium tests
        automatic during the build and how to run a local selenium server where you can start any
        selenium test you like.  

     Open your pom file and find the depdencies section. Put the following part in there:

    <dependency>
       <groupId>org.seleniumhq.selenium.client-drivers</groupId>
       <artifactId>selenium-java-client-driver</artifactId>
       <version>1.0-beta-2</version>
    </dependency>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>6.1.1</version>
      <scope>test</scope>
    </dependency>

    After you done that find the <build><plugins> section Put the following part in there:

            <plugins>
                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>selenium-maven-plugin</artifactId>
                    <version>2.3</version>
                    <executions>
                        <execution>
                            <phase>pre-integration-test</phase>
                            <goals>
                                <goal>start-server</goal>
                            </goals>
                            <configuration>
                                <background>true</background>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
               
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <configuration>
                        <!-- Skip the normal tests, we'll run them in the integration-test phase -->
                        <skip>true</skip>
                    </configuration>
                   
                    <executions>
                        <execution>
                            <phase>integration-test</phase>
                            <goals>
                                <goal>test</goal>
                            </goals>
                            <configuration>
                                <skip>false</skip>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

    Now the plumbing part is done. You have a skeleton to work with.

    All you have to do now is to create a new testNG class. Make sure it extends from SeleneseTestCase.
     All the annotations used are imported from testNG.
    import org.testng.annotations.AfterMethod;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.Test;

     You can put the following lines in there to see if it works:
     
          @BeforeMethod
          public void beforeMethod() {
              try {
                setUp("https://www.google.com/", "*firefox");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          }

          @Test
          public void testLabel() {
                selenium.open("https://www.google.com/");
                selenium.type("q", "Selenium with JUnit 4");
          }

    HOW TO RUN IT:
    1. Now your all setup and ready to go for your first selenium test with maven.
        You can do a clean install and it runs while it builds
    2. You can also type the command:
         selenium:start-server and run the test as testNG test.
         In the teardown of the test you can do something like:
            @AfterMethod
            public void tearDown() throws Exception {
                selenium.stop();
            }

    This worked for me and I hope it works for you. Enjoy.

    maandag 28 mei 2012

    Maps versus cache

    The question I asked myself a couple of times before I got around it was: What is the benefit of using caches and implement their overhead instead of using the much lighter and in some cases the faster hashmaps. It looked odd to me that I would be the only one with this question because of the widely used variety of caches. This fenomena did not occur to me like a fashion statement. I digged a bit in to it and try to explain here some very good reasons to use caches to prohibited some issues you might find.  

    The first thing you have to think about is the fact that the most of us work in a multi threaded environment. Not all the maps are threadsave.  The only threadsave map is the concurentHashMap which inherits from the ConcurentMap Interface. Because of the thread safety these kind of maps will give a bit of overhead.


    What I just wrote you might consider to use the ConcurentMap. Using a map might put you in the temptation of using it static, This should be the last thing on your mind static collections are a well known source of memory leaks. The problem with this is that: They stay in the classloader. They are not an instance. This means that they only will be removed until the classloader is removed. Most of the time this happens when the application dies. The donwside of this way of caching is that your application might run out of memory and crashes. A sign that might trigger you is the fact that you get an OutOfMemoryError. With maps instead of caches you are bound to keep track of  what objects in your home made cache still have usefull references or not. Otherwise the garbage collector is not triggered to collect them.  The reference that it will keep in Memory is the fact that the most Maps do not use weak references.

    Concurrency of caches is a very important point. But it is not the only one. If you are aware of the fact that you load huge amounts of data which might endangers the given memory to the jvm. To prevent this the most caches have parameters that can be set to use memory until a certain amount. After these values the caches will start serializing the data to disk for swap purposes. 

    The third point I like to raise is the fact: that all the maps are using strong references for their keys and values in stead of weak references. The only exception on this rule is the WeakHashMap. The downside of this map is that it is not natural threadsave.

    If you are about to load a great amount of data which is pretty much static in the way it is not edited, but used for lookup. Using a Concurrent hashmap might be the right solution. But even then, be carefull using it with the Java keyword static.  


    donderdag 1 maart 2012

    an easy way of copy files with maven from a server

        <build>
            <resources>
            <resource>
                <directory>//IP_ADRESS/FOLDER_STRUCTURE</directory>
                <includes>
                    <include>FILE_FILTER</include>
                </includes>
                <targetPath>DESTINATION_FOLDER </targetPath>
            </resource>
            </resources>
        </build>

    maandag 20 februari 2012

    StringBuilder/Buffer versus concat

    StringBuilder/Buffer versus +
    In short: 
    1. In unconditional statements the + is faster. It allready has been done during compile time.
    2. In conditional statements aspecially the loops, the + has been done at runtime just as the StringBuffer and StringBuilder. In this case the StringBuilder and StringBuffer are faster. 
    Conclusion:
     Use the + only in unconditional statements.
    Use a StringBuilder in conditional Statements aspecially loops.
    The choice beteween the StringBuilder or the StringBuffer is simple. The StringBuffer is thread save and the Stringbuilder is not. In general that means if you do not need threadsafety, use the faster StringBuilder.
    The following  sites demonstrate well howto use String concat.
    http://kaioa.com/node/59
    http://stackoverflow.com/questions/1296571/what-happens-when-java-compiler-sees-many-string-concatenations-in-one-line
    http://www.precisejava.com/javaperf/j2se/StringAndStringBuffer.htm