Posts tagged ‘Java’

Java Spring MVC 3.2.0 UnitTests

I had a bit of a fight today, I wanted to UnitTest some Java Spring MVC code that I’m using for a demo application. But after a lot of Googling, StackOverflow and hitting different documentation of Spring 3.0, 3.1 and 3.2 I finally came to an acceptable solution. Mind you a minimal sample to test MVC controller without having to go crazy with decelerations, attributes, injections and so on and so forth, you catch my drift. There has been a lot of movement from those three versions I mentioned and finally the spring UnitTesting lib has now been folded into Spring itself, this is good news.
Btw, I found the answer in the Spring MVC showcase on GitHub, where else ?

So lets take a look at what you need, bare minimum just the way I like it.

Using Maven, you will need the ref in your POM file

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.2.0.RELEASE</version>
            <scope>test</scope>
        </dependency>

The controller class I’m using comes pretty much directly from creating a new MVC Spring project from Eclipse.

package us.kristjansson.springTest;
//
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
//
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Handles requests for the application home page.
 */

@Controller
public class CxHomeController
{
       
        private static final Logger logger = LoggerFactory.getLogger(CxHomeController.class);
       
        /**
         * Simply selects the home view to render by returning its name.
        */

        @RequestMapping(value = “/”, method = RequestMethod.GET)
        public String home(Locale locale, Model model)
        {
                logger.info(“Welcome home! The client locale is {}.”, locale);
                //
                Date date = new Date();
                DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
                String formattedDate = dateFormat.format(date);
                model.addAttribute(“serverTime”, formattedDate );
               
                return “home”;
        }
       
}

Then lets look at the Test itself.

//
package us.kristjansson.springTest;
//
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.springframework.test.web.servlet.MockMvc;
//
import org.junit.Before;
import org.junit.Test;

public class TxHomeController
{
         //
         private static final Logger logger = LoggerFactory.getLogger(TxSample.class);
         private MockMvc mockMvc;

         @Before
         public void setup() throws Exception
         {
                 logger.info( “Setup CxHomeController” );
                 this.mockMvc = standaloneSetup(new CxHomeController()).build();
         }

         @Test
         public void TestController() throws Exception
         {

                 //
                 logger.info( “testing CxHomeController” );
                
                 // The CxHomeController’s view is "home" without content
                 this.mockMvc.perform(
                           get(“/”))
                                 .andExpect(status().isOk())
                                 .andExpect(content().string(“”))
                                 .andExpect(view().name(“home”) 
                                 );

         }
       
}

Maven Sonar plugin for your Java project

I needed to add Sonar reporting to a small Java project that uses Maven for the build. There is a Maven Sonar plugin available for this task here.

First add sonar properties file ( sonar-project.properties ) to your java project, put it in root.

# info
sonar.projectKey=javaTest
sonar.projectVersion=1.0
sonar.projectName=Sample java spring MVC project

# Comma-separated paths to directories with sources (required)
sonar.sources=src

# Language
sonar.language=java

# Encoding of the source files
sonar.sourceEncoding=UTF-8

Make Maven aware of the Sonar location etc, add that to the Maven settings \maven\conf\settings.xml

Something like this

<profile>
       <id>sonar</id>
       <activation>
          <activeByDefault>true</activeByDefault>
       </activation>
       <properties>
          <!– SERVER ON A REMOTE HOST –>
          <sonar.host.url>http://remotebox.com:9000</sonar.host.url>
          <sonar.jdbc.url>jdbc:h2:tcp://remotebox.com:9092/sonar</sonar.jdbc.url>
       </properties>
    </profile>

For Maven version 3+ add this to the POM file in the build section, else Maven version 2 ( below ).

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>sonar-maven-plugin</artifactId>
        <version>2.1</version>
      </plugin>

For Maven 2.

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>sonar-maven-plugin</artifactId>
        <version>1.0</version>
     </plugin>

Pass the sonar:sonar goal to the Maven script then kick off a build, the dependencies should be downloaded automatically. The report for your project displays on the Sonar server dashboard.

GoogleTv getting started

There were some GoogleTv guys ( Les Vogel and Paul Carff ) coming to town to hold a session on GoogleTv development. This event was facilitated by the local Android meetup group. Naturally I wanted to attend, I haven’t looked at GoogleTv before so why not jump on the oppertunity to get to know GoogleTv development a little. To my surprise I was handed a nice GoogleTv T-shirt and a Vizio GoogleTv device as I walked in the door, w00t !

Lets look at developing for the device, it’s recommended that you develop on Linux, as the Google Tv emulator uses KVM virtual machine to run in, most people use Eclipse as the IDE. Other than that setting up for coding for Google Tv is pretty much the same as coding for Android. First download and install the Android SDK, then download and install the Google Tv extension. Here is a little snag I ran into, when running the Android SDK Manager you will have to toggle the radio button to sort by repository rather than API level to find, “Google Inc. ( dl-ssl.google.com )” in the list. Once you see that you can find “Google Tv Addon” below, that’s the one you want, check the box and install the package. With that out of the way, next you need to setup a Android Virtual machine using the Android Virtual Device Manager. When you create your new GoogleTv AVD see if you can set the data partition to 1024 instead of 128, this will help with errors about the emulator not having enough space for installing your application. Otherwise you can also run it from command prompt, after you add the /tools and /platform-tools directories from the sdk to your path. Like this

$ emulator -avd googleTv -partition-size 1024

For some your keyboard might not work either in the Emulator, in order to activate that add Keyboard support in the harware properties of the AVD configuration and set it to “yes”. Now you should be good to go, you might have to start the Emulator from command prompt depending on your setup. Now in your Package Manger, you can look for KVM and install. You will also need computer that supports BIOS virtualization extensions, in order to check on that run

$ kvm-ok

you should see some message like “KVM acceleration can be used” if your good, otherwise you will get some kind of error.

That’s the Emulator at work

I wrote a sample app that plays different media over the internet, it turns out the emulator is not as capable of playing different formats as the regular Android emulator. Most of my streams played on the Android emulator but not on the GoogleTv emulator. It’s a good thing that they gave us GoogleTv devices when we attended the labs event at Google, now I can start coding and try it on the actual device which will work better than on the emulator. The Vizio GoogleTv is only $99 at the moment, if your going to develop for GoogleTv I would recommend getting the device to test on rather than using the emulator.

A lot of Android applications will work just fine on GoogleTv without any modifycation. The most important thing to keep in mind is that the GoogleTv display is Landscape only and the resolution is usually in the Tv format 1280 x 720 or 1920 x 1080. For example my Android BeerWidget runs fine on the GoogleTv without any modifycation.

Java Postgres connection sample

I had to setup Postgres on my linux box, configure and make sure it was working. Since that was the case I started the install, then wrote a very simple Java program to connect and retrieve some data from one of the database tables. The install is simple and pretty easy to google. Once your Postrgres database is up and running you should be able to connect to it. You will need a java Postgres database driver, the one I downloaded was the postgresql-9.1-901.jdbc4.jar then add the jar to your project. And finally to make sure your database is accessible from a program you can use the sample below.

//
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

// Simple test class to prove connection to Postgres database
public class Main
{

        public Main()
                { super(); }

        public static void main(String[] args)
        {
       
                System.out.println(” Postgres Test”);
                Connection myConn = null;
               
                try
                {
                        // The driver
                        Class.forName(“org.postgresql.Driver”);
                        System.out.println(“PostgreSQL JDBC Driver Registered!”);
               
                        myConn = DriverManager.getConnection( “jdbc:postgresql://127.0.0.1:5432/testDb”,
                                        “testUser”, “myPassword” );

                        // Connected ?
                        if (myConn != null)
                                System.out.println(“Successfully connected to Postgres Database”);
   
                        // Get data from the database
                Statement stGetCount = myConn.createStatement();
            ResultSet rs = stGetCount.executeQuery(“SELECT * from  cars”);
           
            while( rs.next() )
            {
                System.out.println(“result=” + rs.getString(1) + “,” + rs.getString(2) + “,” + rs.getString(3) );
            }
        }
        catch( Exception ex )
        {
            ex.printStackTrace();
        }
        finally
        {
                try{myConn.close();}catch(Exception IDontCare ){}
        }

        }
       
}  // EOC
 

Java Authenticated POST

I came across this TeamCity Twitter plugin via StackOverflow the idea is to Tweet the build status as it changes. Pretty neat idea, however it will only run under Java 1.6. I tried to install on our build server at work but the TeamCity version we are running doesn’t run under Java 1.6 There was only one thing to do, write my own that will work under Java 1.5. It has to do authenticated POST request to the Twitter REST API. The build Twitter account can be found here, not that your that interested in our build Twitter feed 🙂

//
import java.io.*;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.net.URLEncoder;
import java.net.URLConnection;
//
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.serverSide.SRunningBuild;
import jetbrains.buildServer.messages.Status;
//
import com.intellij.openapi.diagnostic.Logger;

// Tweets build start / finish to the build account
public class TwitterNotifier extends BuildServerAdapter
{
   private final static Logger LOG = Logger.getInstance(TwitterNotifier.class.getName());
   
   
   // Constructor, register the listener ( this )
   public TwitterNotifier(SBuildServer aBuildServer)
   {
       LOG.info(“*** Notifier adding listener=” + this );

       // Register with TC
       aBuildServer.addListener(this);
   }

   // Build started, set the version number
   public void buildStarted(SRunningBuild build)
   {
       String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” started on “ + build.getAgentName() );
   }

   public void buildChangedStatus(SRunningBuild build, Status oldStatus, Status newStatus)
   {
           String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” status, “ + newStatus.getText() );
   }
     
   public void buildInterrupted(SRunningBuild build)
   {
           String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” interrupted status, “ + build.getBuildStatus().getText() );
   }
   
   public void buildFinished(SRunningBuild build)
   {
           String sTcBuildNumber = build.getBuildNumber();
       sendTweet( “Build “ + sTcBuildNumber + ” finished, “ + build.getBuildStatus().getText() );          
   }
   
   // Updates the twitter account
   public static void sendTweet( String psText )
   {
           try
           {
               LOG.info( “*** TwitterNotifier plugin, “ + psText );
              
               //  Using paramaters known to work
               String urlString = “http://twitter.com/statuses/update.xml”;
               String data = “status=” + URLEncoder.encode( psText, “UTF-8”);
               String username = “twitteruser”;
               String password = “twitterpassword”;
              
               // 
               Authenticator.setDefault(new MyAuthenticator(username, password));
               // Send data
                URL url = new URL(  urlString );
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
                out.write(data);
                out.flush();
                
                // Get the response
                StringBuffer sb = new StringBuffer();
                BufferedReader readIn = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = readIn.readLine()) != null)
                        sb.append(line + \n );

                //
                //System.out.println( "*** Response=" + sb.toString() );
                
                // Close       
                out.close();
                readIn.close();
           }
           catch( Exception ex )
           {
               LOG.info( “***ERROR=” + exception2string( ex ) );
           }
   }

   public static String exception2string(Exception e)
   {
      try
      {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return “——\r\n + sw.toString() + “——\r\n;
      }
      catch(Exception ex)
      {
        return “error converting exception to string”;
      }
   }

   
   static class MyAuthenticator extends Authenticator
   {
       private String username, password;

       public MyAuthenticator(String user, String pass)
       {
         username = user;
         password = pass;
       }

       protected PasswordAuthentication getPasswordAuthentication()
       {
         /*
         System.out.println("Requesting Host  : " + getRequestingHost());
         System.out.println("Requesting Port  : " + getRequestingPort());
         System.out.println("Requesting Prompt : " + getRequestingPrompt());
         System.out.println("Requesting Protocol: "
             + getRequestingProtocol());
         System.out.println("Requesting Scheme : " + getRequestingScheme());
         System.out.println("Requesting Site  : " + getRequestingSite());
         */

         return new PasswordAuthentication(username, password.toCharArray());
       }
   }

}  // EOC
 

Boulder Java User Group Meet, March 10

I went yesterday to see my friend Eric Wendelin speak about javaFX at the BoulderJUG meeting.   Eric did a great job with a fresh and informative presentation.   Also on tap was Tim Berglund giving a talk about Liquibase and Database Refactoring in general, good job.

Since we are on the topic of java, why not check out the new jQuery talk by young Dmitri.