Análisis y Diseño de Sistemas

Basic Project Scaffold

Apr 8, 2014

This document shows how to create a basic project scaffold using maven, MySql, Junit, java and activejdbc. We use it to teach some basic concepts about software development in an enginering course in UNRC.

Maven

Apache Maven is a tool to build projects. It follows the directives of convention over configuration. Based on the concept of a Project Object Model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information.

An archetype is defined as an original pattern from which all other things of the same kind are made. In short, Archetype is a Maven project templating toolkit. Archetypes will help authors create Maven project templates for users, and provides tools to users to generate parameterized versions of those project templates.

Building the project

    # Create the directory structure
    $ mvn archetype:generate -DgroupId=com.unrc.app \
                             -DartifactId=cars-app \
                             -DarchetypeArtifactId=maven-archetype-quickstart \
                             -DinteractiveMode=false

    # Compile and package in a distribuible format (e.g. JAR)
    $ mvn package

    # Compile source code
    $ mvn compile

    # Check that everything is in place
    $ mvn validate

    # Run test suite
    $ mvn test

    # Deploy a new release
    $ mvn deploy

    # Execute the compile code
    $ java -cp target/cars-app-1.0-SNAPSHOT.jar com.unrc.app.App
    #  java -cp target/carsweb-app-1.0-SNAPSHOT.jar com.unrc.app.Cars
  

Stack of our project

Here is the stack of tools that we will use in our project

Configure and create MySql database

Configure database in your system and create a schema.sql file under a directory named config where you will save all tables and records that you will use through the project
      -- Integrantes: W - X - Y - Z

      DROP TABLE IF EXISTS users; -- Usuarios
      CREATE TABLE users(
          id INT(11) NOT NULL AUTO_INCREMENT,
          email VARCHAR(60) UNIQUE,
          first_name VARCHAR(56),
          last_name VARCHAR(56),
        CONSTRAINT users_pk PRIMARY KEY (id)
      );
    
      $ mysql -u root
      mysql> create database carsapp_development;

      $ mysql -u root carsapp_development < config/schema.sql
    
Add this to pom file
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.0.4</version>
      </dependency>

      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-simple</artifactId>
          <version>1.7.6</version>
      </dependency>
    

Install and configure ActiveJDBC

Here are the installation instuctions.

First add these repositories to your pom:

    <repositories>
      <repository>
          <id>sonatype-nexus-snapshots</id>
          <name>Sonatype Nexus Plugin Snapshots</name>
          <url>https://oss.sonatype.org/content/repositories/snapshots</url>
          <releases>
              <enabled>false</enabled>
          </releases>
          <snapshots>
              <enabled>true</enabled>
          </snapshots>
      </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>sonatype-nexus-plugin-snapshots</id>
            <name>Sonatype Nexus Plugin Snapshots</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
  

then add the dependency and plugin instrumentation

    <dependency>
      <groupId>org.javalite</groupId>
      <artifactId>activejdbc</artifactId>
      <version>1.4.9</version>
    </dependency>

    <build>
      <plugins>
        <plugin>
          <groupId>org.javalite</groupId>
          <artifactId>activejdbc-instrumentation</artifactId>
          <version>1.4.9</version>
          <executions>
              <execution>
                  <phase>process-classes</phase>
                  <goals>
                      <goal>instrument</goal>
                  </goals>
              </execution>
          </executions>
        </plugin>
      </plugins>
    </build>
  

then run mvn package to check that everything is in place.

Create a Model to test things so far

prepare the test suite

Update the file src/test/java/com/unrc/app/AppTest.java to setup the test suite
    package com.unrc.app;

    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.runner.RunWith;
    import org.junit.runners.Suite;
    import org.junit.runners.Suite.SuiteClasses;

    @RunWith(Suite.class)
    @SuiteClasses({ })
    public class AppTest {
        @BeforeClass
        public static void setUpClass() {
            System.out.println("Master setup");
        }

        @AfterClass public static void tearDownClass() {
            System.out.println("Master tearDown");
        }
    }
  

Then we have to create a spec to the model that we want to build, let's play with an user model for exmaple. file to the test the User model. Create a file test/java/com/unrc/app/UserSpec.java

    package com.unrc.app;

    import com.unrc.app.models.User;

    import org.javalite.activejdbc.Base;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;

    import static org.junit.Assert.assertEquals;


    public class UserTest{
        @Before
        public void before(){
            Base.open("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/carsapp_test", "root", "");
            System.out.println("UserTest setup");
            Base.openTransaction();
        }

        @After
        public void after(){
            System.out.println("UserTest tearDown");
            Base.rollbackTransaction();
            Base.close();
        }

        @Test
        public void onlyTesting(){
            User user = new User();

            assertEquals(2 , 2);
        }
    }
  

Here we are in red step (mvn test), I mean test are not passing. We have to get them passing or in green status. Going to green, create the user model file src/main/java/com/unrc/app/models/User.java and add the following code:

      package com.unrc.app.models;

      import org.javalite.activejdbc.Model;

      public class User extends Model {

      }
    

Run the test suite again (now all tests should be passing)

Play just a little with the stack

We want to ensure that all users in our site will have a first_name and a last_name, add the following tests to our UserTest class.

    import static org.javalite.test.jspec.JSpec.the;

    ...

    @Test
    public void shouldValidateMandatoryFields(){
        User user = new User();

        // Check errors
        the(user).shouldNotBe("valid");
        the(user.errors().get("first_name")).shouldBeEqual("value is missing");
        the(user.errors().get("last_name")).shouldBeEqual("value is missing");

        // Set missing values
        user.set("first_name", "John", "last_name", "Doe", "email", "example@email.com");

        // Everything should be good
        the(user).shouldBe("valid");
    }
  

so we are in red status, to check it we can run tests using maven command mvn test. Let's go to green, add the following lines to User model

    static {
        validatePresenceOf("first_name", "last_name");
    }
  

Here we have a correct setup to start our project. Everything is pushed in Github carsapp. Good luck to all.

Second part add Spark server & elasticsearch connection.