Sunday, August 26, 2012

Most Java objects are not immutable

For many junior programmers fact that Java objects are not immutable is like a science. Recently, our junior programmer has asked me to debug the next code as he was so confused about the output:

private SomeObject{

private AnotherObject anObj;

public setAnotherObject (AnotherObject anObj){
  this.anObj = anObj;
}

useObject(){
System.out.println("Object value is " + this.anObj.getX()); // line 15
}

}


private ActionObjet{

private someMethod(){
     private AnotherObject anObj = new AnotherObject();
     anObj.setX(55);
     SomeObject sm = SomeObjec();
     sm.setAnotherObjec(anObj);
//here goes stupidity
     anObj.setX(999);
//here goes another stupidity
     sm.useObject();
// he gets that output is 999
// oh my God he says, its something unrealistic and so on...IT SHOULD BE 55. I AN CERTAIN
}

}

Main problem is if you give an object to another object instance variable and change that object somewhere in the future the object instance variable refers to the change object.

In order not to make so stupid mistakes give your junior programmers a book about Java language!

Tuesday, August 14, 2012

H2, Spring Framework configuration

In order to simplify communication with database sometimes we use light-weight databases. That databases could be started in embedded mode(you do not have to install database at all). I will show how   to configure H2 database for using with Spring Framework and IBatis(MyBatis).

First of all, define sqlSessionFactory bean.


        <bean id= "sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
              <property name= "dataSource" ref ="dataSource" />
              <property name= "configLocation" value="WEB-INF/mybatis/sqlmap-config.xml" />
        </bean>
 
So, define dataSource

<jdbc:embedded-database id ="dataSource" type= "H2">
              <jdbc:script location= "/WEB-INF/table_data.sql" />
    </jdbc:embedded-database>
 
And declare transaction manager
        
        <bean id= "transactionManager"
               class= "org.springframework.jdbc.datasource.DataSourceTransactionManager"
              p:dataSource-ref="dataSource" />

    

And of course, we need SQL statements in file table_data.sql 


DROP TABLE IF EXISTS User;

CREATE TABLE User(
ID INTEGER AUTO_INCREMENT PRIMARY KEY ,
NAME VARCHAR(50),
ADDRESS VARCHAR (50),
AGE INTGERE
);

INSERT INTO User (ID, NAME, ADDRESS, AGE) VALUES (1, 'Jevgeni', 'Rae XX' , '34'); 

Use with pleasure!

Tuesday, July 31, 2012

Functional testing(Selenium Web driver, Java, Maven, TestNG/JUnit)

Functional testing is a black box testing, because we do not how the software works(I mean we do not see code). We know what we should click and what output should be. Yes, we have specification. So, I will not give you here theoretical overview, just create a custom sample project and will show you the main features of Selenium Java Web Driver, JUnit and lets get it done using Maven.

The first thing we have to do is to select the page we want to test. I do not like thinking too much - lets just test my blogspot page - http://jevgenimarenkov.blogspot.com/. When we click on the link byJevgeni(its on the right just below the about section) we want to get label "On Blogger since September 2010". So lets start:

1. Download and Install Selenium IDE for Firefox (http://release.seleniumhq.org/selenium-ide/1.8.1/). You can read some tutorials on the same page(http://seleniumhq.org/projects/ide/) as well. It is not prohibited!

2. Start Selenium IDE,it starts automatically recording actions that you perform. To understand that Selenium is recording your actions, make sure that red button in the right upper corner is pressed.
Go to http://jevgenimarenkov.blogspot.com/
Click on link by Jevgeni.
Right click on label (On Blogger since September 2010)
Choose assertText css=p.sidebar-item.item-key On Blogger since September 2010

3. If You watch on Selenium ID console than you will get a picture like that one. In order to confirm that you recorded a valid test than click on green button (play entire suite) browser will automatically perform recorder actions in the right order.

4.Next step is to generate Java code from this test. To generate java code press File/Export Test Case As/JUnit 4 (Web Driver). Will get the next java code:
package com.example.tests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class JUnitWebDrivver {
    private WebDriver driver;
    private String baseUrl;
    private StringBuffer verificationErrors = new StringBuffer();
    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "http://jevgenimarenkov.blogspot.com/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void testJUnitWebDrivver() throws Exception {
        driver.get(baseUrl + "/");
        driver.findElement(By.cssSelector("a.profile-name-link")).click();
        assertEquals("On Blogger since September 2010", driver.findElement(By.cssSelector("p.sidebar-item.item-key")).getText());
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
        String verificationErrorString = verificationErrors.toString();
        if (!"".equals(verificationErrorString)) {
            fail(verificationErrorString);
        }
    }

    private boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }
}


5. We have to change out Java code a little in order to do it more flexible. JUnit by default searches for Firefox in Program Files, so if You have installed somewhere else than it will not find it. It is better to define the path to Firefox. But you can try without it.

     @Before
    public void setUp() throws Exception {
        FirefoxBinary binary = new FirefoxBinary(new File(
                "path//to//firefox"));
        driver = new FirefoxDriver(binary, null);
        baseUrl = "http://jevgenimarenkov.blogspot.com";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

6. Next step is to create a Maven project using Eclipse (or something else). If you do not have Maven than just install it! So You installed Maven and You created a sample project. What is your next step you ask?(at least i believe so)

7. Your next step is to add next dependencies to the pom.xml file: org.seleniumhq.selenium and junit

8. You added dependencies, you have Maven project and you have a java file somewhere on your desktop. You have to add generated by Selenium java class to the project classpath and that is it!

9. Run that class as JUnit(if you use Eclipse it is installed by default). And that fluke! firefox starts automatically and performs some actions!.

That is all. In conclusions, goes my 4 if:
- if you have questions ask them here
- if you want more tutorials ask me
- if you want to speak with me do it
- if you want to add me as a friend on Facebook do it

And of course, my code is available at GitHub - https://github.com/jevgenimarenkov/selenium-test

Saturday, July 21, 2012

Play! framework. First experience.

Do we always need to use complex and powerful frameworks such as Spring, Wicket, Struts with different multiple-level functionalities. Of course not. Sometimes we need a lightweight framework for developing simple java-based web applications. Lately I tried a new Play framework 2.0.1 to develop a simple Rest applications.

The framework is based on MVC pattern, the connection between different elements is understandable. To understand how the framework performs you do not need a lot of time. We have models (could be represented as hibernate entities in a table format)

Views (consist of scala/html/coffescript)

Controllers (perform some operations and redirect users to the views)

Framework proposes to use in-memory H2 database for initial development. On the other hand, to use another database we have to change config file. In order to map client request to a specific controller is used config file with name route. Here are not used annotations(like in Spring), everything is done in a separate file(after Spring I thing that annotations are the best!!!). The example of route file is:

# Routes
 # This file defines all application routes (Higher priority routes first)
 # ~~~~
# Home page GET / controllers.Application.index()
# Tasks
GET /tasks controllers.Application.tasks()
POST /tasks controllers.Application.newTask()
POST /tasks/:id/delete controllers.Application.deleteTask(id: Long)
 # Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)

What I liked is its speed. In Spring we use JRebel, Play framework does not need that plugin, we could edit/change our product live. Just change the code and press F5 and YES everything is changed. WE could change everything, config files, html etc. Of course it is a big plus. The Error messages are represented in a fancy way. It is really nice!


And yes it supports Scala. You can develop with Scala or with Java or  Scala and Java simultaneously. 

IMHO, it’s a good possibility to develop not complex applications. Its just very quick and fancy framework for limited needs. Try it out, understand the concepts and start developing. It is simple. Its very simple.