niedziela, 26 maja 2013

What is Tomcat default administrator password ?

If you installed and started Tomcat server and you couldn't login to 'Tomcat manager' because you dont know login and password to your admin account, you should look closer to the file "%TOMCAT_HOME%/conf/tomcat-users.xml".

In mentioned file there is section where are defined tomcat user roles which by default are commented:

<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->


If you want fully use tomcat server you have to add your admin account to tomcat-users.xml file: 

<tomcat-users>

<!--
  <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->

  <role rolename="manager"/>
  <role rolename="admin"/>
  <user username="admin" password="admin" roles="admin,manager"/>

</tomcat-users>


Save this file and restart tomcat server.

Now just login to your server using already defined account.

środa, 22 maja 2013

SetUp Groovy development with Maven

Groovy is an object-oriented programming language for Java Virtual Machine(JVM), provides dynamic programming features similar to Python, Ruby, Smalltalk, ... . The moust commont use of Groovy is scripting language and interacts freely with existing Java code and libraries.

Groovy is defined as an agile and dynamic programming/scripting language build for Java Virtual Machine. Groovy for Java developer it promises an almost-zero learning curve. Groovy is based on JVM and that is why it interoperates with existing Java infrastructure, libraries and framwork.

This is why in the past few years, Groovy has become popular for scripting and DSLs(Domain Specific Languages) in addition to its use in application development. The next advantage from using Groovy is that connected with Java, enhances developer productivity by reducing scaffolding code while providing built-in capability for unit and mock testing.

To start you adventure with Groovy lets generate Groovy simple project using Maven:

mvn archetype:generate / 
-DarchetypeGroupId=org.codehaus.groovy.maven.archetypes / 
-DarchetypeArtifactId=gmaven-archetype-basic

The completion of this operation has created a Groovy project with simple "Hello World!" Groovy application: file Example.groovy:

class Example
{
    def show() {
        println 'Hello World'
    }

  
Now look to POM file. It is configured in way that integrated the build lifecycle with the Maven Groovy plugin:

    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.groovy.maven</groupId>
                <artifactId>gmaven-plugin</artifactId>
                <version>1.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generateStubs</goal>
                            <goal>compile</goal>
                            <goal>generateTestStubs</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>



mvn compile - compile project
mvn test - run tests


The next think you can find in POM file are dependencies:
    
     <dependencies>
        <dependency>
            <groupId>org.codehaus.groovy.maven.runtime</groupId>
            <artifactId>gmaven-runtime-1.6</artifactId>
            <version>1.0</version>
        </dependency>
       
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>


The second you should already know:). The first listed here is the GMaven runtime, that is gmaven-runtime-1.6. 
With the help of the GMaven plugin, these two dependencies are integrated with Maven build lifecycle and the build workflow for the developer is achieved through Apache Maven.

It is one more think which is worth to mention. Groovy Shell provides the developer with a very convenient command-line shell to execute Groovy commands. The GMaven plugin provides for command-line access to the Groovy shell with the following command:

mvn groovy:shell 

If you like a GUI access to the shell run 

mvn groovy:console 
 

poniedziałek, 20 maja 2013

SetUp Scala development with Maven

To generate simple scala application by maven execute:

 mvn archetype:generate \
-DarchetypeGroupId=org.scala-tools.archetypes \
-DarchetypeArtifactId=scala-archetype-simple \ -DremoteRepositories=http://scala-tools.org/repo-releases \ -DgroupId=org.scala.test.app \
-DartifactId=TestScalaApp \
-Dversion=1.0-SNAPSHOT

Scala stands for "Scalable Language". It is defined as a multi-paradigm programming language and has integrated support for object-oriented programming and functional programming. It runs on the JVM and on Android. It can read existing Java libraries which give it a huge advantage in cases where there is a lot of existing code infrastructure in Java.

Now we can look to generated code:
Simple Hello world App.scala:

package org.scala.test.app

object App {
 
  def foo(x : Array[String]) = x.foldLeft("")((a,b) => a + b)
 
  def main(args : Array[String]) {
    println( "Hello World!" )
    println("concat arguments = " + foo(args))
  }

}


The pom.xml file is configured in a way that inntegrated the build lifecycle with Maven Scala plugin:

      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <version>2.15.0</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
            <configuration>
              <args>
                <arg>-make:transitive</arg>
                <arg>-dependencyfile</arg>
                <arg>${project.build.directory}/.scala_dependencies</arg>
              </args>
            </configuration>
          </execution>
        </executions>
      </plugin>


Compile  project: mvn compile
Run tests: mvn test

The generated pom.xml file contains Scala dependencies:

 <properties>
    <maven.compiler.source>1.5</maven.compiler.source>
    <maven.compiler.target>1.5</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.version>2.8.0</scala.version>
  </properties>

    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
    <dependency>
      <groupId>org.scala-tools.testing</groupId>
      <artifactId>specs_${scala.version}</artifactId>
      <version>1.6.5</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.scalatest</groupId>
      <artifactId>scalatest</artifactId>
      <version>1.2</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.8.1</version>
      <scope>test</scope>
    </dependency>

The first dependency is the Scala programming language, that is org.scala-lang.scala-library. The next two are for running Scala tests. The last one is for junit tests.


The last think what we will look on is the maven scala plugin. This are available goals and their explanations:
  • mvn scala:compile -Compile the Scala source directory
  • mvn scala:console - Launches the Scala REPL with all project dependencies
  • mvn scala:doc - Generates the documentation for all Scala sources
  • mvn scala:help - Displays the Scala compiler help
  • mvn scala:run - Executes a Scala class
  • mvn scala:script - Executes a Scala Scripts
  • mvn scala:testCompile - Compiles the Scala test sources



niedziela, 19 maja 2013

Using Hibernate persistence with Maven

First lets generate same basic maven project:

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId=net.hibernateApp.packt.maven -DartifactId=TestHibernateApp -Dversion=1.0.0

Now we identify and include all Hibernate artifacts and its dependencies into Maven project:
      
    <repositories>
        <repository>
            <id>JBoss repository</id>
            <url>http://repository.jboss.com/maven2/</url>
        </repository>
    </repositories>


    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- Hibernate core -->
        <dependency>
            <groupId>hibernate</groupId>
            <artifactId>hibernate3</artifactId>
            <version>3.2.3.GA</version>
        </dependency>

        <!-- Hibernate annotation -->
        <dependency>
            <groupId>hibernate-annotations</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.3.0.GA</version>
        </dependency>

        <dependency>
            <groupId>hibernate-commons-annotations</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>3.0.0.GA</version>
        </dependency>

        <!-- Hibernate library dependecy start -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate</artifactId>
            <version>3.2.6.ga</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.4.0.GA</version>
        </dependency>
        <!-- Hibernate library dependecy end -->


        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.5.2</version>
        </dependency>

        <dependency>
             <groupId>javax.transaction</groupId>
             <artifactId>jta</artifactId>
             <version>1.1</version>
        </dependency>


  The next step is to create entity class, lets say User:

import javax.persistence.*;
import java.sql.Date;

@Entity
@Table(name = "User")
public class User {

    @Id
    @GeneratedValue
    private long id;

    @Column(name = "firstName")
    private  String firstName;

    @Column(name = "surName")
    private  String surName;

    @Column(name = "birthDate")
    private Date birthDate;

    @Column (name = "address")
    private  String address;

    public User() {
    }

    public User(String firstName, String surName, Date birthDate, String address) {
        this.firstName = firstName;
        this.surName = surName;
        this.birthDate = birthDate;
        this.address = address;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getSurName() {
        return surName;
    }

    public void setSurName(String surName) {
        this.surName = surName;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}


Notice the use of the @Table, @Entity, @Id, @Column annotations. There is two constructor in POJO User class, first default and second with arguments. The second is optional but note that it is nessesery to define a default(non-argument) constructor in your mapping class. This user class will be mapped by hibernate to User table.

Now we have to define util class which will be resposible for connection to our mysql database:

package net.hibernateApp.packt.maven.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtils {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure().buildSessionFactory();

        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}





When we already have class which will be keep connection to database, we have to configure that connection. Lets add file hibernate.cfg.xml to location /src/main/java/resources:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="connection.username">{user}</property>
        <property name="connection.password">{pass}</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">false</property>

        <property name="hbm2ddl.auto">create-drop</property>

        <mapping class="net.hibernateApp.packt.maven.domain.User"/>

    </session-factory>
</hibernate-configuration>


The first six properties are specific to the underlying MYSQL database and the connection pool size available. hibernate.show_sql echoes all queries onto the console. hbm2ddl.auto = create-drop drops and generates the tables in the database each time the application is executed. Other possible values are validate, update and create. 

Finally, we will create the main class of our application to test CRUD basic database operations:

import net.hibernateApp.packt.maven.domain.User;
import net.hibernateApp.packt.maven.hibernate.HibernateUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Session;


import java.sql.Date;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        // Read
        System.out.println("******* READ *******");
        List users = list();
        System.out.println("Total Users: " + users.size());

        // Write
        System.out.println("******* WRITE *******");
        User user = new User("Christopher", "Stepniak", new Date(System.currentTimeMillis()), "Poland");
        user = save(user);
        user = read(user.getId());
        System.out.printf("%d %s %s \n", user.getId(), user.getFirstName(), user.getSurName());

        // Update
        System.out.println("******* UPDATE *******");
        User user2 = read(1l);
        System.out.println("Name Before Update:" + user2.getFirstName());
        user2.setFirstName("James");
        update(user2);  // save the updated user details

        user2 = read(1l);
        System.out.println("Name Aftere Update:" + user2.getFirstName());


        // Delete
        System.out.println("******* DELETE *******");
        delete(user);
        User user3 = read(user.getId());
        System.out.println("Object:" + user3);
    }

    private static List list() {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        List employees = session.createQuery("from User").list();
        session.close();
        return employees;
    }

    private static User save(User user){
        SessionFactory sf;
        sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        session.beginTransaction();

        Long id = (Long) session.save(user);
        user.setId(id);

        session.getTransaction().commit();

        session.close();

        return user;
    }

    private static User read(Long id) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        User user = (User) session.get(User.class, id);
        session.close();
        return user;
    }

    private static User update(User user) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        session.beginTransaction();

        session.merge(user);

        session.getTransaction().commit();

        session.close();
        return user;

    }

    private static void delete(User user) {
        SessionFactory sf = HibernateUtils.getSessionFactory();
        Session session = sf.openSession();

        session.beginTransaction();

        session.delete(user);

        session.getTransaction().commit();

        session.close();
    }

}







Hibernate Error – java.lang.NoClassDefFoundError: org.slf4j.impl.StaticLoggerBinder

Error:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
Exception in thread "main" java.lang.ExceptionInInitializerError
    at net.hibernateApp.packt.maven.hibernate.HibernateUtils.buildSessionFactory(HibernateUtils.java:26)
    at net.hibernateApp.packt.maven.hibernate.HibernateUtils.<clinit>(HibernateUtils.java:15)
    at net.hibernateApp.packt.maven.app.Main.save(Main.java:34)
    at net.hibernateApp.packt.maven.app.Main.main(Main.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder
    at org.slf4j.LoggerFactory.<clinit>(LoggerFactory.java:60)
    at org.hibernate.cfg.annotations.Version.<clinit>(Version.java:12)
    at org.hibernate.cfg.AnnotationConfiguration.<clinit>(AnnotationConfiguration.java:78)
    at net.hibernateApp.packt.maven.hibernate.HibernateUtils.buildSessionFactory(HibernateUtils.java:20)
    ... 8 more
Caused by: java.lang.ClassNotFoundException: org.slf4j.impl.StaticLoggerBinder
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 12 more









Solution:

Solution:

Add dependency to you pom file:
  • Maven central repository:

  <dependencies>
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-log4j12</artifactId>
       <version>1.5.2</version>
     </dependency>
   </dependencies>

Hibernate Error – java.lang.NoClassDefFoundError: javax/transaction/Synchronization

While executing hibernate application:

Initial SessionFactory creation failed.java.lang.NoClassDefFoundError: javax/transaction/Synchronization
Exception in thread "main" java.lang.ExceptionInInitializerError
    at net.hibernateApp.packt.maven.hibernate.HibernateUtils.buildSessionFactory(HibernateUtils.java:26)
    at net.hibernateApp.packt.maven.hibernate.HibernateUtils.<clinit>(HibernateUtils.java:15)
    at net.hibernateApp.packt.maven.app.Main.save(Main.java:34)
    at net.hibernateApp.packt.maven.app.Main.main(Main.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.NoClassDefFoundError: javax/transaction/Synchronization
    at org.hibernate.impl.SessionFactoryImpl.buildCurrentSessionContext(SessionFactoryImpl.java:999)
    at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:334)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1300)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
    at net.hibernateApp.packt.maven.hibernate.HibernateUtils.buildSessionFactory(HibernateUtils.java:20)
    ... 8 more
Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 13 more


Solution:

Add dependency to you pom file:

  • Maven central repository:

   <dependencies>
     <dependency>
       <groupId>javax.transaction</groupId>
       <artifactId>jta</artifactId>
       <version>1.1</version>
     </dependency>
   </dependencies> 
  • JBoss maven repository:

Add JBoss Maven repository

 <repositories>
  <repository>
   <id>JBoss repository</id>
   <url>http://repository.jboss.com/maven2/</url>
  </repository>
 </repositories

and add jar dependency:

 <dependencies>
  <dependency>
   <groupId>javax.transaction</groupId>
   <artifactId>jta</artifactId>
   <version>1.1</version>
  </dependency>
 </dependencies>

wtorek, 14 maja 2013

Using Spring Framework with Maven

You need have Maven Java project to start with Spring Framework. I you don't have one, you can run this maven command to generate some:

mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart -DgroupId={project packaging} -DartifactId=TestAppSpringMvn -Dverison=1.0-SNAPSHOT

Now you can import generated project to IDE.

To start with Spring Framework you need add its artifacts to POM file. The following list contains all Spring Framework dependencies which allow you to work with Spring 3:

<!--
    Core utilities used by other modules.
    Define this if you use Spring Utility APIs (org.springframework.core.*/org.springframework.util.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Expression Language (depends on spring-core)
    Define this if you use Spring Expression APIs (org.springframework.expression.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-expression</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Bean Factory and JavaBeans utilities (depends on spring-core)
    Define this if you use Spring Bean APIs (org.springframework.beans.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Aspect Oriented Programming (AOP) Framework (depends on spring-core, spring-beans)
    Define this if you use Spring AOP APIs (org.springframework.aop.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Application Context (depends on spring-core, spring-expression, spring-aop, spring-beans)
    This is the central artifact for Spring's Dependency Injection Container and is generally always defined
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Various Application Context utilities, including EhCache, JavaMail, Quartz, and Freemarker integration
    Define this if you need any of these integrations
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Transaction Management Abstraction (depends on spring-core, spring-beans, spring-aop, spring-context)
    Define this if you use Spring Transactions or DAO Exception Hierarchy
    (org.springframework.transaction.*/org.springframework.dao.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-tx</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    JDBC Data Access Library (depends on spring-core, spring-beans, spring-context, spring-tx)
    Define this if you use Spring's JdbcTemplate API (org.springframework.jdbc.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA, and iBatis.
    (depends on spring-core, spring-beans, spring-context, spring-tx)
    Define this if you need ORM (org.springframework.orm.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX, Castor, XStream, and XML Beans.
    (depends on spring-core, spring-beans, spring-context)
    Define this if you need OXM (org.springframework.oxm.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Web application development utilities applicable to both Servlet and Portlet Environments
    (depends on spring-core, spring-beans, spring-context)
    Define this if you use Spring MVC, or wish to use Struts, JSF, or another web framework with Spring (org.springframework.web.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Spring MVC for Servlet Environments (depends on spring-core, spring-beans, spring-context, spring-web)
    Define this if you use Spring MVC with a Servlet Container such as Apache Tomcat (org.springframework.web.servlet.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Spring MVC for Portlet Environments (depends on spring-core, spring-beans, spring-context, spring-web)
    Define this if you use Spring MVC with a Portlet Container (org.springframework.web.portlet.*)
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc-portlet</artifactId>
  <version>${org.springframework.version}</version>
</dependency>
<!--
    Support for testing Spring applications with tools such as JUnit and TestNG
    This artifact is generally always defined with a 'test' scope for the integration testing framework and unit testing stubs
-->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${org.springframework.version}</version>
  <scope>test</scope>
</dependency>

Now you have to define context configuration XML file. This file has contains bean declarations, but since Spring 3 support annotation-based bean declarations, the context file can also contains additional configuration such as the package paths which Spring should scan for annotation-based beans. This autoscan context file component can looks like this:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <context:component-scan base-package="com.springApp.packt.maven" />

</beans>


If you using Spring in your project, you will need to write tests that require the injection of Spring Beans. Now I will show you simple example of that test:

First lets create service class:

package com.springApp.packt.maven.services;

import org.springframework.stereotype.Service;

@Service("myServiceOne")
public class MyServiceOneImpl {

    public String getA(){
        return "A";
    }

}


@Service - annotation preceding the class definition and note that the annotation contains the bean name: @Service("beanNameHere")

Before you start to create your test class, you have to add jUnit dependencies to your pom.xml file:

</dependencies>
    ...
     <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.8.1</version>
     </dependency>

  </dependencies>



Test class with one simple test looks like this:

package com.springApp.packt.maven.services;

import junit.framework.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;


@ContextConfiguration("classpath:context.xml")
public class MyServiceOneTest extends AbstractJUnit4SpringContextTests{

    @Autowired
    private MyServiceOneImpl myServiceOne;

   @Test
   public void shoulGetA(){
       Assert.assertEquals(myServiceOne.getA(),"A");
   }

}


AbstractIUnit4SpringContextTests-initialize Spring
@ContextConfiguration - define the location of the context file for Test
@Autowired - injecting the bean


Now if you build you project by command mvn clean install, you should see short test execution raport in the end of your build process.


środa, 8 maja 2013

Simple maven web application deployed on jetty server

Required:
  • jdk
  • maven

Use maven to generate simple web application:
 
mvn archetype:generate -DgroupId={project-packaging} -DartifactId={project-name} -DarchetypeArtifactId=maven-archetype-webapp -Dversion=1.0-SNAPSHOT
 
Genereted project open in your IDE. Now you can view structure of generated web application. 
Using maven you can compile, run test or build you application:
 
mvn compile
mvn test
mvn install
 
After a successful build, maven generate target folder. You will find there WAR 
with name of you application(appName.war). If you will look closer to pom.xml file you will 
find out that the packaging type was set there:
 ...
  <artifactId>appName</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version> 
 ...
 
To run generated project on jetty server at first you have to edit you pom.xml file 
and add jetty plugin declaration:
 
...
  <build>
      <plugins>
      <plugin>
          <groupId>org.mortbay.jetty</groupId>
          <artifactId>maven-jetty-plugin</artifactId>
          <version>6.1.10</version>
      </plugin>
      </plugins>
  </build> 
... 
 
Now using command
   mvn jetty:run
you can start jetty server with generated WAR file.
 
Open your browser and  under address 
   http://localhost:8080/appName/
you can see page of your running application. 
 
 
 
Important!!!
For windows enviroment make sure that firewall does not interfere 
Jetty server to execute on port 8080.