Thursday, 29 September 2016

Apache Maven - A java build tool

Maven
  • Build automation tool 
    • Build
      • Compiling 
      • running unit tests 
      • running integration tests
      • Package jar/war
      • Deploy to server
  • Uses POM.xml to describe Project, dependencies, build order & plugins.
  • Convention over configuration
Commands
  • mvn install - install to repository
Objectives:
  • Make build process EASY
  • Uniform build system
  • Describes how software is built
    • It is described by POM(Project Object model)
  • Describes the dependencies the software has
  • Build life cycle- made of up phases
  •  It is collection of plugins. Plugins perform action in maven.
  • It suggest default 'Project Structure' & 'build life cycles'
Generate new project from archetype- Command line
POM
  1. General information
  2. Build settings(Customize the maven lifecycles, add new 'Plugins' and 'Goals')
  3. Build environment(Profiles used to configure different deployment environments, Dev, Test, Prod)
  4. POM Relationships(Modules and SubModules)
  
  • Compile - Dependency available in all build phases & packaged with application
  • Test - Test complication & execution
  • runtime - required only at runtime and not at compile time
  • provided - When container provides dependency
  • system  - Same as provided but you will tell system where exactly is the provided jar
LifeCycles(3 life cycles)
  1. clean - Cleaning up previous build
  2. default or build - building and deployment
  3. site - creating project site documentation
Each lifecycle has Phases;
  • Clean(3 phases) - Few phases have builtin goals/plugins
  • Build(23 Phases)
  • Site(
Plugins
  • They have goals associated with it
    • help:describe -Dcmd =compile ->
Installation: Env variable setup

export M2_HOME=/Users/vdesu/maven/apache-maven-3.6.2
export PATH=$M2_HOME/bin:$PATH

mvn -version
---

Apache Maven- Most used build management tool/Project management tool.
Building a project means
  • Compile
  • Run tests
  • Package into jar files
  • Bundle jar into war files
  • Deploy to server
Maven automates all the above. It follows convention over configuration
  • myproject
    • src/main/java
    • src/main/resources
    • src/test/java
    • src/test/resources
    •  
Archetypes are similar to templates.  Different archtypes are Standalone, webapp, ear etc. Maven creates folder structure based on Archetypes.

Why use Maven:
  • Common interface (standard structure)
  • Dependencies
  • Repositories

Maven Plugin & Goals: Maven Plugin is group of one or more goals. Each plugin exposes atleast one goal.  mvn <plugin name>:<goal name> followed by parameters

  • archetype:generate
  • install:install
  • eg: mvn archetype:generate -DgroupId=com.venkat -DartifactId=hellomaven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
Maven coordinates
  • group id
  • artifact id
  • packaging
  • version
POM: Project Object Model

  • Helps to manage all dependency in web application

Maven Build Life cycle:
  • Validate -> validate pom.xml 
  • Compile -> generate .classfiles
  • Test ->  run the unit tests
  • Package -> create jar file
  • Integration Test-> 
  • Verify -> 
  • Install -> install to local repository
  • Deploy

Core concepts:
  • POM
  • Plugins & goals
  • Coordinates
  • Repositories
Maven Plugins & Goals
  • Plugin is collection of one or more goals
    • syntax: pluginId:goalId
    • eg: 
      • mvn archetype:generate -DgroupId=com.desu -DartifactId=hellomaven -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
      • cd hellomaven
      • mvn install   -> this will compile, run test & package
      • java -cp target\hellomaven-1.0-SNAPSHOT.jar com.desu.App
Lifecycle phases - Phases are associated with one or more goals.
  1. process-resources > resources:resources
  2. compile > compiler:compiler
  3. test > surefire:test
  4. package > jar:jar
When a phase is executed, system runs all its prior phases before executing it. 
Coordinates
  • groupId similar to package name in Java
  • artifactId similar to class name in java
  • packaging (extension)
  • version
Repositories
  • It describes 'how' the software is built.
  • It describes 'Dependencies' the software has. 
  • It is described by 'POM' - Project Object Model - stored in xml format
  • Sheilds from build complexities
Maven Build life cycle
  • Validate -> Compile -> Test -> Package -> Integration Test -> Verify -> Install -> Deploy
Multi Module Project
  • Create/copu POM.xml in parent folder of the 2 projects(childs)
    • Change the artifact id to 'parent', name,  
    • set Packaging to POM
  • Define child projects as Modules
  • Make following changes to Child project POM
    • Add <parent> element with maven coordinates of Parent
  • Build multi module project
    • mvn clean install  // builds all 3 projects
    • Add <dependency> element incase one project is dependent on other
Scopes
  • In dependency tag
    • Compile
      • default scope
    • runtime
      •  not required for compilation
    • provided 
      • required during test and run locally. Hence not exported to war/jar
    • test
      • compile & run Tests only
    • system 
      • similar to provided .. but not provided either by maven or system
    • import
      • used for pom based projects.

Friday, 23 September 2016

Hibernate ORM

  • Persistence 
    • The state of an object can be saved to  a data store, and recreated at a later point in time. It can be persisted to a file or a db.
  • ORM
    • Object Relational mapping
    • It refers to the technique of mapping the representation of data from Java Objects to Relational Database (and vice versa).
  • Hibernate
    • Object Relational mapping solution for Java
    • Framework for mapping Object model to Relational databases
    • It maps Java data types to Database specific data types
    • Generates sql queries automatically and hence, reduces the development time
    • Database independent - can switch to different DB by editing single configuration file
    • Communication happens between Java -> Hibernate -> DB, and vice versa
  • Setup Steps
    • 1. Download hybernate orm zip from http://hibernate.org/
    • 2. Create lib directory in the project, copy jars from downloaded zip lib folders -> required, jpa, java8 directories to project lib folder in eclipse
    • 3. Copy jdbc driver into project lib folder
    • 4. Add jar to class path
        project properties -> build path -> libraries -> add jars
  • Hibernate configuration
    • 1. Add hibernate configuration file to src directory hibernate.cfg.xml
      <!DOCTYPE hibernate-configuration PUBLIC
              "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
              "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

      <hibernate-configuration>
          <session-factory>
              <!-- JDBC Database connection settings -->
              <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
              <property name="connection.url">jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=SLC03RYC.us.oracle.com)(PORT=1521)) (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xe)))</property>
              <property name="connection.username">vdesu</property>
              <property name="connection.password">vdesu</property>

              <!-- JDBC connection pool settings ... using built-in test pool -->
              <property name="connection.pool_size">1</property>

              <!-- Select our SQL dialect -->
              <property name="dialect">org.hibernate.dialect.OracleDialect</property>

              <!-- Echo the SQL to stdout -->
              <property name="show_sql">true</property>

              <!-- Set the current session context -->
              <property name="current_session_context_class">thread</property>

          </session-factory>
      </hibernate-configuration>
    • Annotate java class(mapping class to db table).  Entity class - Java class that is mapped to a database table
      • Option 1: XML config file (legacy)
      • Option 2: Java annotations (modern, preferred)
        • @Entity
          @Table(name="student")
        •     @Id
              @Column(name="id")
        •     @Column(name="first_name")
    •  Develop java code to perform database operations
      • package com.luv2code.hibernate.demo;

        import org.hibernate.Session;
        import org.hibernate.SessionFactory;
        import org.hibernate.cfg.Configuration;

        import com.luv2code.hibernate.demo.entity.Student;

        public class CreateStudentDemo {

            public static void main(String[] args) {
               
                SessionFactory factory = new Configuration()
                                        .configure("hibernate.cfg.xml")
                                        .addAnnotatedClass(Student.class)
                                        .buildSessionFactory();
               
                Session session = factory.getCurrentSession();

              try{
                Student tempStudent = new Student("venkat","desu","venkat.desu@gmail.com");
                 session.beginTransaction();
                session.save(tempStudent);
                session.getTransaction().commit();
                System.out.println("done");
            } finally {
                factory.close();
            }
               

            }

        }
    • Execute the program.
  • Retrieve a java object with hibernate
    • Student mystudent=session.get(Student.class, <ID value>);
  • Retrieve all Students using Hibernate Query Language (HQL)
    • List<Student> theStudents = session.createQuery("from Student").list();
    • List<Student> theStudents = session.createQuery("from Student s where s.lastName='desu'").list();
    •  List<Student> theStudents = session.createQuery("from Student s where s.lastName='desu' OR s.firstName='venkat'").list();
    • List<Student> theStudents = session.createQuery("from Student s where s.lastName like 'desu%'").list(); 
  • Update Object
    • Student mystudent=session.get(Student.class, <ID value>);
      mystudent.setFirstName("asdf");
  • Bulk Update
    •  session.createQuery("update Student set lastName='desu'").executeUpdate();
  • Delete Object
    • Student mystudent=session.get(Student.class, <ID value>);
      session.delete(mystudent);
  • Bulk Delete
    •  session.createQuery("delete from Student where id=0").executeUpdate();
Hibernate Query Language:
  • HQL is an Object Oriented Query Language
  • Unlike SQL, HQL uses/operates on Classes instead of Tables
  • Advantages
    • Database independent - Easy migration from one DB to another
    • Easy for Java programmers - Quick to learn and implement
  • Creating Tables with Primary and foreign key
Hibernate Object States & LifeCycle:
  • Transient 
    • It is just a POJO Object eg: Student Object
  • Persistent -> Transient Object have association with table. Starts once Transaction is started. The state ends with Commit()
    • session.save()
    • session.persist()
    • session.saveOrUpdate() 
    • session.load()
    • session.get()
    • session.byId()
    • session.byNaturalId()
  • Detached - starts with one of the following methods
    • session.evict() - evicts from session
    • session.clear()
    • session.close() 
    • We can move from detached to Persistent using update(), merge(), saveOrUpdate()
    • It not used then it will be removed by garbage collector
  • Removed
      • session.delete() 
      • It will be available for garbage collection and cannot be used
JPA vs Hibernate(Entity Manger vs Session)


Friday, 9 September 2016

Jira by Atlassian

Agile -> Team based project management methodology.

Jira  is Agile Project management tool & issue tracker.
There are 2 methods of working with agile in JIRA. Kanban and Scrum(Agile methodologies)

Sprint is a set period of time(commonly 1 to 4 weeks). To start a sprint, the team meets with scrum board(Backlog, todo, in progress, complete) open. Two main questions are asked
  • What went well in the last sprint?
  • What can we improve on for the next sprint?
Go thru tickets to determine and agree on what will get accomplished in the next sprint

Scrum Daily Stand-Up meeting - Each team member answers 3 questions(nothing other than the three questions are discussed)
  • What did I accomplish yesterday
  • What will I do today
  • What roadblocks do I forsee to stop me from accomplishing my goal?
 Epic and user Stories
  • Epic is essentially a large user story that needs multiple sprints to complete 
    • As a content creator, I want to be able to upload any video so that I don't have to know how to convert videos to a web-friendly format myself.
  • A user story (a user focused story), that can be finished with in a sprint.
    • eg/formula: As a [role], I want [desire] so that benefit
    • As a content creator, I want to be able to upload any video so that I can see it online 
    • As a content creator, I want the server to convert videos for me so that I don't have to convert them myself.
 Some resources to
  http://agilemanifesto.org
  http://www.agilealliance.org/agile101/

JIRA
  • Issue:  Every card/ticket on board is what JIRA calls an "issue"
  • Every issue has a unique key. The key is made up of the project & a sequential number(DEMO-251, BUG-45)
  • Jira has different types of issues. Each type has different fields associated
    • Epic
    • story (Due date, assignee, Labels)
    • Feature request
    • User contact(First name, Last name, Email)
    • Bug (OS, Assignee, Screenshot)
    • Task
  • Project
    • Projects are a bucket
    • Issues live inside a project
    • Properties such as user permissions, workflows and more are associated with projects
    •